Skip to content

The open alternative to Salesforce, designed for AI.

Email campaigns 4/4: honour unsubscribes and meter sends (#25125)

neo773b57d23f4e42e
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index bb2a207908f..b3d82fe2ae5 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -2718,6 +2718,8 @@ type EmailingDomain {
updatedAt: DateTime!
domain: String!
status: EmailingDomainStatus!
+ tenantStatus: EmailingDomainTenantStatus!
+ unsubscribeHostnameStatus: UnsubscribeHostnameStatus
verificationRecords: [VerificationRecord!]
verifiedAt: DateTime
}
@@ -2729,6 +2731,18 @@ enum EmailingDomainStatus {
TEMPORARY_FAILURE
}
+enum EmailingDomainTenantStatus {
+ ACTIVE
+ PAUSED
+ SANDBOX
+}
+
+enum UnsubscribeHostnameStatus {
+ PENDING
+ ACTIVE
+ FAILED
+}
+
type MessageChannel {
id: UUID!
visibility: MessageChannelVisibility!
@@ -2811,6 +2825,7 @@ type CampaignAudiencePreviewDTO {
totalMembers: Int!
withoutEmail: Int!
duplicateEmails: Int!
+ overCap: Int!
globallyUnsubscribed: Int!
topicUnsubscribed: Int!
sendable: Int!
@@ -2825,16 +2840,10 @@ type SendEmailViaDomainOutput {
messageId: String!
}
-type CampaignSkippedRecipientsDTO {
- noEmail: Int!
- deduped: Int!
- overCap: Int!
-}
-
type SendMessageCampaignOutputDTO {
campaignId: String!
queuedCount: Int!
- skipped: CampaignSkippedRecipientsDTO!
+ audience: CampaignAudiencePreviewDTO!
}
type MessageSuppression {
@@ -3803,6 +3812,8 @@ type Mutation {
sendMessageCampaign(input: SendMessageCampaignInput!): SendMessageCampaignOutputDTO!
cancelMessageCampaign(input: CancelMessageCampaignInput!): CancelMessageCampaignOutputDTO!
sendMessageCampaignTest(input: SendMessageCampaignTestInput!): SendEmailViaDomainOutput!
+ createMessageSuppression(input: CreateMessageSuppressionInput!): MessageSuppression!
+ deleteMessageSuppression(id: UUID!): Boolean!
createUnsubscribeTopic(input: CreateUnsubscribeTopicInput!): UnsubscribeTopic!
updateUnsubscribeTopic(input: UpdateUnsubscribeTopicInput!): UnsubscribeTopic!
deleteUnsubscribeTopic(id: String!): Boolean!
@@ -4888,6 +4899,11 @@ input SendMessageCampaignTestInput {
fromAddress: String!
}
+input CreateMessageSuppressionInput {
+ emailAddress: String!
+ unsubscribeTopicId: UUID
+}
+
input CreateUnsubscribeTopicInput {
name: String!
description: String
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 34dc089c80b..bbf77287ac7 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -2363,6 +2363,8 @@ export interface EmailingDomain {
updatedAt: Scalars['DateTime']
domain: Scalars['String']
status: EmailingDomainStatus
+ tenantStatus: EmailingDomainTenantStatus
+ unsubscribeHostnameStatus?: UnsubscribeHostnameStatus
verificationRecords?: VerificationRecord[]
verifiedAt?: Scalars['DateTime']
__typename: 'EmailingDomain'
@@ -2370,6 +2372,10 @@ export interface EmailingDomain {
export type EmailingDomainStatus = 'PENDING' | 'VERIFIED' | 'FAILED' | 'TEMPORARY_FAILURE'
+export type EmailingDomainTenantStatus = 'ACTIVE' | 'PAUSED' | 'SANDBOX'
+
+export type UnsubscribeHostnameStatus = 'PENDING' | 'ACTIVE' | 'FAILED'
+
export interface MessageChannel {
id: Scalars['UUID']
visibility: MessageChannelVisibility
@@ -2420,6 +2426,7 @@ export interface CampaignAudiencePreviewDTO {
totalMembers: Scalars['Int']
withoutEmail: Scalars['Int']
duplicateEmails: Scalars['Int']
+ overCap: Scalars['Int']
globallyUnsubscribed: Scalars['Int']
topicUnsubscribed: Scalars['Int']
sendable: Scalars['Int']
@@ -2437,17 +2444,10 @@ export interface SendEmailViaDomainOutput {
__typename: 'SendEmailViaDomainOutput'
}
-export interface CampaignSkippedRecipientsDTO {
- noEmail: Scalars['Int']
- deduped: Scalars['Int']
- overCap: Scalars['Int']
- __typename: 'CampaignSkippedRecipientsDTO'
-}
-
export interface SendMessageCampaignOutputDTO {
campaignId: Scalars['String']
queuedCount: Scalars['Int']
- skipped: CampaignSkippedRecipientsDTO
+ audience: CampaignAudiencePreviewDTO
__typename: 'SendMessageCampaignOutputDTO'
}
@@ -3274,6 +3274,8 @@ export interface Mutation {
sendMessageCampaign: SendMessageCampaignOutputDTO
cancelMessageCampaign: CancelMessageCampaignOutputDTO
sendMessageCampaignTest: SendEmailViaDomainOutput
+ createMessageSuppression: MessageSuppression
+ deleteMessageSuppression: Scalars['Boolean']
createUnsubscribeTopic: UnsubscribeTopic
updateUnsubscribeTopic: UnsubscribeTopic
deleteUnsubscribeTopic: Scalars['Boolean']
@@ -5861,6 +5863,8 @@ export interface EmailingDomainGenqlSelection{
updatedAt?: boolean | number
domain?: boolean | number
status?: boolean | number
+ tenantStatus?: boolean | number
+ unsubscribeHostnameStatus?: boolean | number
verificationRecords?: VerificationRecordGenqlSelection
verifiedAt?: boolean | number
__typename?: boolean | number
@@ -5905,6 +5909,7 @@ export interface CampaignAudiencePreviewDTOGenqlSelection{
totalMembers?: boolean | number
withoutEmail?: boolean | number
duplicateEmails?: boolean | number
+ overCap?: boolean | number
globallyUnsubscribed?: boolean | number
topicUnsubscribed?: boolean | number
sendable?: boolean | number
@@ -5925,18 +5930,10 @@ export interface SendEmailViaDomainOutputGenqlSelection{
__scalar?: boolean | number
}
-export interface CampaignSkippedRecipientsDTOGenqlSelection{
- noEmail?: boolean | number
- deduped?: boolean | number
- overCap?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
export interface SendMessageCampaignOutputDTOGenqlSelection{
campaignId?: boolean | number
queuedCount?: boolean | number
- skipped?: CampaignSkippedRecipientsDTOGenqlSelection
+ audience?: CampaignAudiencePreviewDTOGenqlSelection
__typename?: boolean | number
__scalar?: boolean | number
}
@@ -6836,6 +6833,8 @@ export interface MutationGenqlSelection{
sendMessageCampaign?: (SendMessageCampaignOutputDTOGenqlSelection & { __args: {input: SendMessageCampaignInput} })
cancelMessageCampaign?: (CancelMessageCampaignOutputDTOGenqlSelection & { __args: {input: CancelMessageCampaignInput} })
sendMessageCampaignTest?: (SendEmailViaDomainOutputGenqlSelection & { __args: {input: SendMessageCampaignTestInput} })
+ createMessageSuppression?: (MessageSuppressionGenqlSelection & { __args: {input: CreateMessageSuppressionInput} })
+ deleteMessageSuppression?: { __args: {id: Scalars['UUID']} }
createUnsubscribeTopic?: (UnsubscribeTopicGenqlSelection & { __args: {input: CreateUnsubscribeTopicInput} })
updateUnsubscribeTopic?: (UnsubscribeTopicGenqlSelection & { __args: {input: UpdateUnsubscribeTopicInput} })
deleteUnsubscribeTopic?: { __args: {id: Scalars['String']} }
@@ -7266,6 +7265,8 @@ export interface CancelMessageCampaignInput {campaignId: Scalars['String']}
export interface SendMessageCampaignTestInput {toAddress: Scalars['String'],unsubscribeTopicId?: (Scalars['String'] | null),subject: Scalars['String'],body: Scalars['String'],fromAddress: Scalars['String']}
+export interface CreateMessageSuppressionInput {emailAddress: Scalars['String'],unsubscribeTopicId?: (Scalars['UUID'] | null)}
+
export interface CreateUnsubscribeTopicInput {name: Scalars['String'],description?: (Scalars['String'] | null),visibility?: (UnsubscribeTopicVisibility | null)}
export interface UpdateUnsubscribeTopicInput {id: Scalars['String'],name?: (Scalars['String'] | null),description?: (Scalars['String'] | null),visibility?: (UnsubscribeTopicVisibility | null)}
@@ -9152,14 +9153,6 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null
- const CampaignSkippedRecipientsDTO_possibleTypes: string[] = ['CampaignSkippedRecipientsDTO']
- export const isCampaignSkippedRecipientsDTO = (obj?: { __typename?: any } | null): obj is CampaignSkippedRecipientsDTO => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isCampaignSkippedRecipientsDTO"')
- return CampaignSkippedRecipientsDTO_possibleTypes.includes(obj.__typename)
- }
-
-
-
const SendMessageCampaignOutputDTO_possibleTypes: string[] = ['SendMessageCampaignOutputDTO']
export const isSendMessageCampaignOutputDTO = (obj?: { __typename?: any } | null): obj is SendMessageCampaignOutputDTO => {
if (!obj?.__typename) throw new Error('__typename is missing in "isSendMessageCampaignOutputDTO"')
@@ -10255,6 +10248,18 @@ export const enumEmailingDomainStatus = {
TEMPORARY_FAILURE: 'TEMPORARY_FAILURE' as const
}
+export const enumEmailingDomainTenantStatus = {
+ ACTIVE: 'ACTIVE' as const,
+ PAUSED: 'PAUSED' as const,
+ SANDBOX: 'SANDBOX' as const
+}
+
+export const enumUnsubscribeHostnameStatus = {
+ PENDING: 'PENDING' as const,
+ ACTIVE: 'ACTIVE' as const,
+ FAILED: 'FAILED' as const
+}
+
export const enumMessageChannelVisibility = {
METADATA: 'METADATA' as const,
SUBJECT: 'SUBJECT' as const,
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index a66078ee623..a0af5ec7c16 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -73,29 +73,31 @@ export default {
255,
288,
296,
+ 297,
298,
- 299,
300,
301,
302,
303,
304,
- 312,
+ 305,
+ 306,
313,
- 316,
- 353,
- 360,
- 362,
+ 314,
+ 317,
+ 354,
+ 361,
363,
364,
365,
- 367,
- 369,
- 374,
- 389,
- 401,
- 515,
- 539
+ 366,
+ 368,
+ 370,
+ 375,
+ 390,
+ 402,
+ 517,
+ 541
],
"types": {
"BillingProductDTO": {
@@ -5338,6 +5340,12 @@ export default {
"status": [
296
],
+ "tenantStatus": [
+ 297
+ ],
+ "unsubscribeHostnameStatus": [
+ 298
+ ],
"verificationRecords": [
294
],
@@ -5349,12 +5357,14 @@ export default {
]
},
"EmailingDomainStatus": {},
+ "EmailingDomainTenantStatus": {},
+ "UnsubscribeHostnameStatus": {},
"MessageChannel": {
"id": [
3
],
"visibility": [
- 298
+ 300
],
"handle": [
1
@@ -5363,16 +5373,16 @@ export default {
1
],
"type": [
- 299
+ 301
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 300
+ 302
],
"messageFolderImportPolicy": [
- 301
+ 303
],
"excludeNonProfessionalEmails": [
8
@@ -5381,7 +5391,7 @@ export default {
8
],
"pendingGroupEmailsAction": [
- 302
+ 304
],
"isSyncEnabled": [
8
@@ -5390,10 +5400,10 @@ export default {
4
],
"syncStatus": [
- 303
+ 305
],
"syncStage": [
- 304
+ 306
],
"syncStageStartedAt": [
4
@@ -5429,7 +5439,7 @@ export default {
"MessageChannelSyncStage": {},
"CreateEmailGroupChannelOutput": {
"messageChannel": [
- 297
+ 299
],
"forwardingAddress": [
1
@@ -5448,6 +5458,9 @@ export default {
"duplicateEmails": [
26
],
+ "overCap": [
+ 26
+ ],
"globallyUnsubscribed": [
26
],
@@ -5480,20 +5493,6 @@ export default {
1
]
},
- "CampaignSkippedRecipientsDTO": {
- "noEmail": [
- 26
- ],
- "deduped": [
- 26
- ],
- "overCap": [
- 26
- ],
- "__typename": [
- 1
- ]
- },
"SendMessageCampaignOutputDTO": {
"campaignId": [
1
@@ -5501,8 +5500,8 @@ export default {
"queuedCount": [
26
],
- "skipped": [
- 309
+ "audience": [
+ 308
],
"__typename": [
1
@@ -5519,10 +5518,10 @@ export default {
1
],
"reason": [
- 312
+ 313
],
"source": [
- 313
+ 314
],
"unsubscribeTopicId": [
3
@@ -5535,7 +5534,7 @@ export default {
"MessageSuppressionSource": {},
"MessageSuppressionList": {
"records": [
- 311
+ 312
],
"totalCount": [
26
@@ -5561,7 +5560,7 @@ export default {
1
],
"visibility": [
- 316
+ 317
],
"__typename": [
1
@@ -5607,7 +5606,7 @@ export default {
1
],
"location": [
- 318
+ 319
],
"__typename": [
1
@@ -5635,13 +5634,13 @@ export default {
1
],
"IMAP": [
- 320
+ 321
],
"SMTP": [
- 320
+ 321
],
"CALDAV": [
- 320
+ 321
],
"__typename": [
1
@@ -5661,7 +5660,7 @@ export default {
3
],
"connectionParameters": [
- 321
+ 322
],
"__typename": [
1
@@ -5886,7 +5885,7 @@ export default {
1
],
"series": [
- 330
+ 331
],
"xAxisLabel": [
1
@@ -5935,7 +5934,7 @@ export default {
1
],
"data": [
- 332
+ 333
],
"__typename": [
1
@@ -5943,7 +5942,7 @@ export default {
},
"LineChartData": {
"series": [
- 333
+ 334
],
"xAxisLabel": [
1
@@ -5980,7 +5979,7 @@ export default {
},
"PieChartData": {
"data": [
- 335
+ 336
],
"showLegend": [
8
@@ -6085,13 +6084,13 @@ export default {
},
"EventLogQueryResult": {
"records": [
- 340
+ 341
],
"totalCount": [
26
],
"pageInfo": [
- 341
+ 342
],
"__typename": [
1
@@ -6155,7 +6154,7 @@ export default {
1
],
"parts": [
- 326
+ 327
],
"processedAt": [
4
@@ -6224,7 +6223,7 @@ export default {
},
"AiSystemPromptPreview": {
"sections": [
- 346
+ 347
],
"estimatedTokenCount": [
26
@@ -6252,7 +6251,7 @@ export default {
26
],
"error": [
- 348
+ 349
],
"__typename": [
1
@@ -6285,10 +6284,10 @@ export default {
},
"StartWorkspaceSetupChatResult": {
"outcome": [
- 353
+ 354
],
"thread": [
- 345
+ 346
],
"__typename": [
1
@@ -6326,10 +6325,10 @@ export default {
3
],
"evaluations": [
- 354
+ 355
],
"messages": [
- 344
+ 345
],
"createdAt": [
4
@@ -6385,7 +6384,7 @@ export default {
9
],
"scope": [
- 360
+ 361
],
"__typename": [
1
@@ -6400,19 +6399,19 @@ export default {
1
],
"syncStatus": [
- 362
+ 363
],
"syncStage": [
- 363
+ 364
],
"visibility": [
- 364
+ 365
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 365
+ 366
],
"isSyncEnabled": [
8
@@ -6463,7 +6462,7 @@ export default {
1
],
"pendingSyncAction": [
- 367
+ 368
],
"messageChannelId": [
3
@@ -6505,7 +6504,7 @@ export default {
1
],
"provenance": [
- 369
+ 370
],
"__typename": [
1
@@ -6534,7 +6533,7 @@ export default {
3
],
"through": [
- 370
+ 371
],
"__typename": [
1
@@ -6554,7 +6553,7 @@ export default {
1
],
"emit": [
- 371
+ 372
],
"action": [
1
@@ -6589,7 +6588,7 @@ export default {
},
"CollectionHash": {
"collectionName": [
- 374
+ 375
],
"hash": [
1
@@ -6653,13 +6652,13 @@ export default {
},
"MinimalMetadata": {
"objectMetadataItems": [
- 375
+ 376
],
"views": [
- 376
+ 377
],
"collectionHashes": [
- 373
+ 374
],
"__typename": [
1
@@ -6719,7 +6718,7 @@ export default {
184,
{
"input": [
- 379
+ 380
]
}
],
@@ -6844,7 +6843,7 @@ export default {
2,
{
"input": [
- 380,
+ 381,
"GetApiKeyInput!"
]
}
@@ -6953,7 +6952,7 @@ export default {
10,
{
"input": [
- 381,
+ 382,
"AgentIdInput!"
]
}
@@ -6966,7 +6965,7 @@ export default {
"CursorPaging!"
],
"filter": [
- 382,
+ 383,
"ObjectFilter!"
]
}
@@ -6996,7 +6995,7 @@ export default {
21,
{
"input": [
- 383,
+ 384,
"LogicFunctionIdInput!"
]
}
@@ -7008,7 +7007,7 @@ export default {
9,
{
"input": [
- 383,
+ 384,
"LogicFunctionIdInput!"
]
}
@@ -7017,7 +7016,7 @@ export default {
1,
{
"input": [
- 383,
+ 384,
"LogicFunctionIdInput!"
]
}
@@ -7236,28 +7235,28 @@ export default {
46
],
"previewMessageCampaignAudience": [
- 306,
+ 308,
{
"input": [
- 384,
+ 385,
"PreviewMessageCampaignAudienceInput!"
]
}
],
"messageSuppressions": [
- 314,
+ 315,
{
"input": [
- 385,
+ 386,
"FindMessageSuppressionsInput!"
]
}
],
"unsubscribeTopics": [
- 315
+ 316
],
"myMessageChannels": [
- 297,
+ 299,
{
"connectedAccountId": [
3
@@ -7268,7 +7267,7 @@ export default {
295
],
"getToolIndex": [
- 325
+ 326
],
"getToolInputSchema": [
9,
@@ -7280,10 +7279,10 @@ export default {
}
],
"webhooks": [
- 324
+ 325
],
"webhook": [
- 324,
+ 325,
{
"id": [
3,
@@ -7292,7 +7291,7 @@ export default {
}
],
"myMessageFolders": [
- 366,
+ 367,
{
"messageChannelId": [
3
@@ -7300,7 +7299,7 @@ export default {
}
],
"myCalendarChannels": [
- 361,
+ 362,
{
"connectedAccountId": [
3
@@ -7308,17 +7307,17 @@ export default {
}
],
"minimalMetadata": [
- 377
+ 378
],
"appKeyValue": [
- 359,
+ 360,
{
"key": [
1,
"String!"
],
"scope": [
- 360
+ 361
]
}
],
@@ -7326,7 +7325,7 @@ export default {
217,
{
"filter": [
- 386
+ 387
]
}
],
@@ -7340,13 +7339,13 @@ export default {
}
],
"findWorkspaceAiStats": [
- 356
+ 357
],
"chatThreads": [
- 345
+ 346
],
"chatThread": [
- 345,
+ 346,
{
"id": [
3,
@@ -7355,7 +7354,7 @@ export default {
}
],
"chatMessages": [
- 344,
+ 345,
{
"threadId": [
3,
@@ -7364,7 +7363,7 @@ export default {
}
],
"chatStreamCatchupChunks": [
- 349,
+ 350,
{
"threadId": [
3,
@@ -7373,13 +7372,13 @@ export default {
}
],
"getAiSystemPromptPreview": [
- 347
+ 348
],
"skills": [
- 343
+ 344
],
"skill": [
- 343,
+ 344,
{
"id": [
3,
@@ -7388,7 +7387,7 @@ export default {
}
],
"agentTurns": [
- 355,
+ 356,
{
"agentId": [
3,
@@ -7397,13 +7396,13 @@ export default {
}
],
"timelineActivityTypes": [
- 372
+ 373
],
"metadataTranslations": [
- 368,
+ 369,
{
"input": [
- 387,
+ 388,
"MetadataTranslationsInput!"
]
}
@@ -7466,37 +7465,37 @@ export default {
223
],
"eventLogs": [
- 342,
+ 343,
{
"input": [
- 388,
+ 389,
"EventLogQueryInput!"
]
}
],
"pieChartData": [
- 336,
+ 337,
{
"input": [
- 392,
+ 393,
"PieChartDataInput!"
]
}
],
"lineChartData": [
- 334,
+ 335,
{
"input": [
- 393,
+ 394,
"LineChartDataInput!"
]
}
],
"barChartData": [
- 331,
+ 332,
{
"input": [
- 394,
+ 395,
"BarChartDataInput!"
]
}
@@ -7511,7 +7510,7 @@ export default {
}
],
"getConnectedImapSmtpCaldavAccount": [
- 322,
+ 323,
{
"id": [
3,
@@ -7520,7 +7519,7 @@ export default {
}
],
"getAutoCompleteAddress": [
- 317,
+ 318,
{
"address": [
1,
@@ -7539,7 +7538,7 @@ export default {
}
],
"getAddressDetails": [
- 319,
+ 320,
{
"placeId": [
1,
@@ -7596,10 +7595,10 @@ export default {
},
"ObjectFilter": {
"and": [
- 382
+ 383
],
"or": [
- 382
+ 383
],
"id": [
29
@@ -7653,7 +7652,7 @@ export default {
},
"FindMessageSuppressionsInput": {
"reason": [
- 312
+ 313
],
"searchTerm": [
1
@@ -7701,10 +7700,10 @@ export default {
},
"EventLogQueryInput": {
"table": [
- 389
+ 390
],
"filters": [
- 390
+ 391
],
"first": [
26
@@ -7725,7 +7724,7 @@ export default {
1
],
"dateRange": [
- 391
+ 392
],
"recordId": [
1
@@ -7786,7 +7785,7 @@ export default {
8,
{
"input": [
- 396,
+ 397,
"AddQuerySubscriptionInput!"
]
}
@@ -7795,7 +7794,7 @@ export default {
8,
{
"input": [
- 397,
+ 398,
"RemoveQueryFromEventStreamInput!"
]
}
@@ -7804,7 +7803,7 @@ export default {
156,
{
"inputs": [
- 398,
+ 399,
"[CreateNavigationMenuItemInput!]!"
]
}
@@ -7813,7 +7812,7 @@ export default {
156,
{
"input": [
- 398,
+ 399,
"CreateNavigationMenuItemInput!"
]
}
@@ -7822,7 +7821,7 @@ export default {
156,
{
"inputs": [
- 399,
+ 400,
"[UpdateOneNavigationMenuItemInput!]!"
]
}
@@ -7831,7 +7830,7 @@ export default {
156,
{
"input": [
- 399,
+ 400,
"UpdateOneNavigationMenuItemInput!"
]
}
@@ -7905,7 +7904,7 @@ export default {
153,
{
"file": [
- 401,
+ 402,
"Upload!"
]
}
@@ -7914,7 +7913,7 @@ export default {
153,
{
"file": [
- 401,
+ 402,
"Upload!"
]
}
@@ -7923,7 +7922,7 @@ export default {
153,
{
"file": [
- 401,
+ 402,
"Upload!"
]
}
@@ -7932,7 +7931,7 @@ export default {
153,
{
"file": [
- 401,
+ 402,
"Upload!"
]
}
@@ -7941,7 +7940,7 @@ export default {
153,
{
"file": [
- 401,
+ 402,
"Upload!"
]
}
@@ -7950,7 +7949,7 @@ export default {
153,
{
"file": [
- 401,
+ 402,
"Upload!"
],
"fieldMetadataId": [
@@ -7963,7 +7962,7 @@ export default {
153,
{
"file": [
- 401,
+ 402,
"Upload!"
],
"fieldMetadataUniversalIdentifier": [
@@ -7976,7 +7975,7 @@ export default {
75,
{
"input": [
- 402,
+ 403,
"UpsertUsageLimitInput!"
]
}
@@ -7994,7 +7993,7 @@ export default {
54,
{
"input": [
- 403,
+ 404,
"CreateViewFilterGroupInput!"
]
}
@@ -8007,7 +8006,7 @@ export default {
"String!"
],
"input": [
- 404,
+ 405,
"UpdateViewFilterGroupInput!"
]
}
@@ -8034,7 +8033,7 @@ export default {
56,
{
"input": [
- 405,
+ 406,
"CreateViewFilterInput!"
]
}
@@ -8043,7 +8042,7 @@ export default {
56,
{
"input": [
- 406,
+ 407,
"UpdateViewFilterInput!"
]
}
@@ -8052,7 +8051,7 @@ export default {
56,
{
"input": [
- 408,
+ 409,
"DeleteViewFilterInput!"
]
}
@@ -8061,7 +8060,7 @@ export default {
56,
{
"input": [
- 409,
+ 410,
"DestroyViewFilterInput!"
]
}
@@ -8070,7 +8069,7 @@ export default {
62,
{
"input": [
- 410,
+ 411,
"CreateViewInput!"
]
}
@@ -8083,7 +8082,7 @@ export default {
"String!"
],
"input": [
- 411,
+ 412,
"UpdateViewInput!"
]
}
@@ -8110,7 +8109,7 @@ export default {
62,
{
"input": [
- 412,
+ 413,
"UpsertViewWidgetInput!"
]
}
@@ -8119,7 +8118,7 @@ export default {
59,
{
"input": [
- 418,
+ 419,
"CreateViewSortInput!"
]
}
@@ -8128,7 +8127,7 @@ export default {
59,
{
"input": [
- 419,
+ 420,
"UpdateViewSortInput!"
]
}
@@ -8137,7 +8136,7 @@ export default {
8,
{
"input": [
- 421,
+ 422,
"DeleteViewSortInput!"
]
}
@@ -8146,7 +8145,7 @@ export default {
8,
{
"input": [
- 422,
+ 423,
"DestroyViewSortInput!"
]
}
@@ -8155,7 +8154,7 @@ export default {
52,
{
"input": [
- 423,
+ 424,
"UpdateViewFieldInput!"
]
}
@@ -8164,7 +8163,7 @@ export default {
52,
{
"input": [
- 425,
+ 426,
"CreateViewFieldInput!"
]
}
@@ -8173,7 +8172,7 @@ export default {
52,
{
"inputs": [
- 425,
+ 426,
"[CreateViewFieldInput!]!"
]
}
@@ -8182,7 +8181,7 @@ export default {
52,
{
"input": [
- 426,
+ 427,
"DeleteViewFieldInput!"
]
}
@@ -8191,7 +8190,7 @@ export default {
52,
{
"input": [
- 427,
+ 428,
"DestroyViewFieldInput!"
]
}
@@ -8200,7 +8199,7 @@ export default {
61,
{
"input": [
- 428,
+ 429,
"UpdateViewFieldGroupInput!"
]
}
@@ -8209,7 +8208,7 @@ export default {
61,
{
"input": [
- 430,
+ 431,
"CreateViewFieldGroupInput!"
]
}
@@ -8218,7 +8217,7 @@ export default {
61,
{
"inputs": [
- 430,
+ 431,
"[CreateViewFieldGroupInput!]!"
]
}
@@ -8227,7 +8226,7 @@ export default {
61,
{
"input": [
- 431,
+ 432,
"DeleteViewFieldGroupInput!"
]
}
@@ -8236,7 +8235,7 @@ export default {
61,
{
"input": [
- 432,
+ 433,
"DestroyViewFieldGroupInput!"
]
}
@@ -8245,7 +8244,7 @@ export default {
62,
{
"input": [
- 433,
+ 434,
"UpsertFieldsWidgetInput!"
]
}
@@ -8254,7 +8253,7 @@ export default {
2,
{
"input": [
- 436,
+ 437,
"CreateApiKeyInput!"
]
}
@@ -8263,7 +8262,7 @@ export default {
2,
{
"input": [
- 437,
+ 438,
"UpdateApiKeyInput!"
]
}
@@ -8272,7 +8271,7 @@ export default {
2,
{
"input": [
- 438,
+ 439,
"RevokeApiKeyInput!"
]
}
@@ -8474,7 +8473,7 @@ export default {
152,
{
"input": [
- 439,
+ 440,
"CreateApprovedAccessDomainInput!"
]
}
@@ -8483,7 +8482,7 @@ export default {
8,
{
"input": [
- 440,
+ 441,
"DeleteApprovedAccessDomainInput!"
]
}
@@ -8492,7 +8491,7 @@ export default {
152,
{
"input": [
- 441,
+ 442,
"ValidateApprovedAccessDomainInput!"
]
}
@@ -8501,7 +8500,7 @@ export default {
126,
{
"input": [
- 442,
+ 443,
"CreatePageLayoutTabInput!"
]
}
@@ -8514,7 +8513,7 @@ export default {
"String!"
],
"input": [
- 443,
+ 444,
"UpdatePageLayoutTabInput!"
]
}
@@ -8532,7 +8531,7 @@ export default {
127,
{
"input": [
- 444,
+ 445,
"CreatePageLayoutInput!"
]
}
@@ -8545,7 +8544,7 @@ export default {
"String!"
],
"input": [
- 445,
+ 446,
"UpdatePageLayoutInput!"
]
}
@@ -8567,7 +8566,7 @@ export default {
"String!"
],
"input": [
- 446,
+ 447,
"UpdatePageLayoutWithTabsInput!"
]
}
@@ -8603,7 +8602,7 @@ export default {
83,
{
"input": [
- 449,
+ 450,
"CreatePageLayoutWidgetInput!"
]
}
@@ -8616,7 +8615,7 @@ export default {
"String!"
],
"input": [
- 450,
+ 451,
"UpdatePageLayoutWidgetInput!"
]
}
@@ -8634,7 +8633,7 @@ export default {
10,
{
"input": [
- 451,
+ 452,
"CreateAgentInput!"
]
}
@@ -8643,7 +8642,7 @@ export default {
10,
{
"input": [
- 452,
+ 453,
"UpdateAgentInput!"
]
}
@@ -8652,7 +8651,7 @@ export default {
10,
{
"input": [
- 381,
+ 382,
"AgentIdInput!"
]
}
@@ -8661,7 +8660,7 @@ export default {
23,
{
"input": [
- 453,
+ 454,
"CreateOneObjectInput!"
]
}
@@ -8670,7 +8669,7 @@ export default {
23,
{
"input": [
- 455,
+ 456,
"DeleteOneObjectInput!"
]
}
@@ -8679,7 +8678,7 @@ export default {
23,
{
"input": [
- 456,
+ 457,
"UpdateOneObjectInput!"
]
}
@@ -8688,7 +8687,7 @@ export default {
245,
{
"input": [
- 459,
+ 460,
"CreateOneIndexInput!"
]
}
@@ -8697,7 +8696,7 @@ export default {
245,
{
"input": [
- 462,
+ 463,
"DeleteOneIndexInput!"
]
}
@@ -8706,7 +8705,7 @@ export default {
21,
{
"input": [
- 383,
+ 384,
"LogicFunctionIdInput!"
]
}
@@ -8715,7 +8714,7 @@ export default {
21,
{
"input": [
- 463,
+ 464,
"CreateLogicFunctionFromSourceInput!"
]
}
@@ -8724,7 +8723,7 @@ export default {
148,
{
"input": [
- 464,
+ 465,
"ExecuteOneLogicFunctionInput!"
]
}
@@ -8733,7 +8732,7 @@ export default {
8,
{
"input": [
- 465,
+ 466,
"UpdateLogicFunctionFromSourceInput!"
]
}
@@ -8742,7 +8741,7 @@ export default {
14,
{
"input": [
- 467,
+ 468,
"CreateCommandMenuItemInput!"
]
}
@@ -8751,7 +8750,7 @@ export default {
14,
{
"input": [
- 468,
+ 469,
"UpdateCommandMenuItemInput!"
]
}
@@ -8778,7 +8777,7 @@ export default {
13,
{
"input": [
- 469,
+ 470,
"CreateFrontComponentInput!"
]
}
@@ -8787,7 +8786,7 @@ export default {
13,
{
"input": [
- 470,
+ 471,
"UpdateFrontComponentInput!"
]
}
@@ -8805,7 +8804,7 @@ export default {
68,
{
"data": [
- 472,
+ 473,
"ActivateWorkspaceInput!"
]
}
@@ -8814,7 +8813,7 @@ export default {
68,
{
"data": [
- 473,
+ 474,
"UpdateWorkspaceInput!"
]
}
@@ -8845,7 +8844,7 @@ export default {
214,
{
"input": [
- 474,
+ 475,
"CreateApplicationRegistrationInput!"
]
}
@@ -8854,7 +8853,7 @@ export default {
74,
{
"input": [
- 475,
+ 476,
"UpdateApplicationRegistrationInput!"
]
}
@@ -8881,7 +8880,7 @@ export default {
188,
{
"input": [
- 477,
+ 478,
"CreateApplicationRegistrationVariableInput!"
]
}
@@ -8890,7 +8889,7 @@ export default {
188,
{
"input": [
- 478,
+ 479,
"UpdateApplicationRegistrationVariableInput!"
]
}
@@ -8908,7 +8907,7 @@ export default {
74,
{
"file": [
- 401,
+ 402,
"Upload!"
],
"universalIdentifier": [
@@ -8970,7 +8969,7 @@ export default {
"UUID!"
],
"input": [
- 480,
+ 481,
"UpdateApplicationInput!"
]
}
@@ -8991,7 +8990,7 @@ export default {
237,
{
"input": [
- 481,
+ 482,
"CreateOneFieldMetadataInput!"
]
}
@@ -9000,7 +8999,7 @@ export default {
237,
{
"input": [
- 483,
+ 484,
"UpdateOneFieldMetadataInput!"
]
}
@@ -9009,7 +9008,7 @@ export default {
237,
{
"input": [
- 485,
+ 486,
"DeleteOneFieldInput!"
]
}
@@ -9018,7 +9017,7 @@ export default {
58,
{
"input": [
- 486,
+ 487,
"CreateViewGroupInput!"
]
}
@@ -9027,7 +9026,7 @@ export default {
58,
{
"inputs": [
- 486,
+ 487,
"[CreateViewGroupInput!]!"
]
}
@@ -9036,7 +9035,7 @@ export default {
58,
{
"input": [
- 487,
+ 488,
"UpdateViewGroupInput!"
]
}
@@ -9045,7 +9044,7 @@ export default {
58,
{
"inputs": [
- 487,
+ 488,
"[UpdateViewGroupInput!]!"
]
}
@@ -9054,7 +9053,7 @@ export default {
58,
{
"input": [
- 489,
+ 490,
"DeleteViewGroupInput!"
]
}
@@ -9063,7 +9062,7 @@ export default {
58,
{
"input": [
- 490,
+ 491,
"DestroyViewGroupInput!"
]
}
@@ -9085,7 +9084,7 @@ export default {
46,
{
"createRoleInput": [
- 491,
+ 492,
"CreateRoleInput!"
]
}
@@ -9094,7 +9093,7 @@ export default {
46,
{
"updateRoleInput": [
- 492,
+ 493,
"UpdateRoleInput!"
]
}
@@ -9112,7 +9111,7 @@ export default {
43,
{
"upsertObjectPermissionsInput": [
- 494,
+ 495,
"UpsertObjectPermissionsInput!"
]
}
@@ -9121,7 +9120,7 @@ export default {
44,
{
"upsertPermissionFlagsInput": [
- 496,
+ 497,
"UpsertPermissionFlagsInput!"
]
}
@@ -9130,7 +9129,7 @@ export default {
38,
{
"upsertFieldPermissionsInput": [
- 497,
+ 498,
"UpsertFieldPermissionsInput!"
]
}
@@ -9139,7 +9138,7 @@ export default {
258,
{
"input": [
- 499,
+ 500,
"UpsertRowLevelPermissionPredicatesInput!"
]
}
@@ -9167,55 +9166,73 @@ export default {
}
],
"sendEmailViaEmailingDomain": [
- 308,
+ 310,
{
"input": [
- 502,
+ 503,
"SendEmailViaDomainInput!"
]
}
],
"sendMessageCampaign": [
- 310,
+ 311,
{
"input": [
- 503,
+ 504,
"SendMessageCampaignInput!"
]
}
],
"cancelMessageCampaign": [
- 307,
+ 309,
{
"input": [
- 504,
+ 505,
"CancelMessageCampaignInput!"
]
}
],
"sendMessageCampaignTest": [
- 308,
+ 310,
{
"input": [
- 505,
+ 506,
"SendMessageCampaignTestInput!"
]
}
],
+ "createMessageSuppression": [
+ 312,
+ {
+ "input": [
+ 507,
+ "CreateMessageSuppressionInput!"
+ ]
+ }
+ ],
+ "deleteMessageSuppression": [
+ 8,
+ {
+ "id": [
+ 3,
+ "UUID!"
+ ]
+ }
+ ],
"createUnsubscribeTopic": [
- 315,
+ 316,
{
"input": [
- 506,
+ 508,
"CreateUnsubscribeTopicInput!"
]
}
],
"updateUnsubscribeTopic": [
- 315,
+ 316,
{
"input": [
- 507,
+ 509,
"UpdateUnsubscribeTopicInput!"
]
}
@@ -9230,34 +9247,34 @@ export default {
}
],
"updateMessageChannel": [
- 297,
+ 299,
{
"input": [
- 508,
+ 510,
"UpdateMessageChannelInput!"
]
}
],
"createEmailGroupChannel": [
- 305,
+ 307,
{
"input": [
- 510,
+ 512,
"CreateEmailGroupChannelInput!"
]
}
],
"updateEmailGroupChannel": [
- 297,
+ 299,
{
"input": [
- 511,
+ 513,
"UpdateEmailGroupChannelInput!"
]
}
],
"deleteEmailGroupChannel": [
- 297,
+ 299,
{
"id": [
3,
@@ -9269,7 +9286,7 @@ export default {
295,
{
"input": [
- 512,
+ 514,
"CreateEmailingDomainInput!"
]
}
@@ -9293,34 +9310,34 @@ export default {
}
],
"runAgent": [
- 327,
+ 328,
{
"input": [
- 513,
+ 515,
"RunAgentInput!"
]
}
],
"createWebhook": [
- 324,
+ 325,
{
"input": [
- 516,
+ 518,
"CreateWebhookInput!"
]
}
],
"updateWebhook": [
- 324,
+ 325,
{
"input": [
- 517,
+ 519,
"UpdateWebhookInput!"
]
}
],
"deleteWebhook": [
- 324,
+ 325,
{
"id": [
3,
@@ -9329,37 +9346,37 @@ export default {
}
],
"updateMessageFolder": [
- 366,
+ 367,
{
"input": [
- 519,
+ 521,
"UpdateMessageFolderInput!"
]
}
],
"updateMessageFolders": [
- 366,
+ 367,
{
"input": [
- 521,
+ 523,
"UpdateMessageFoldersInput!"
]
}
],
"updateCalendarChannel": [
- 361,
+ 362,
{
"input": [
- 522,
+ 524,
"UpdateCalendarChannelInput!"
]
}
],
"setAppKeyValue": [
- 359,
+ 360,
{
"input": [
- 524,
+ 526,
"SetAppKeyValueInput!"
]
}
@@ -9372,33 +9389,33 @@ export default {
"String!"
],
"scope": [
- 360
+ 361
]
}
],
"enqueueJob": [
- 357,
+ 358,
{
"input": [
- 525,
+ 527,
"EnqueueJobInput!"
]
}
],
"enqueueJobs": [
- 358,
+ 359,
{
"input": [
- 526,
+ 528,
"EnqueueJobsInput!"
]
}
],
"createChatThread": [
- 345
+ 346
],
"sendChatMessage": [
- 350,
+ 351,
{
"threadId": [
3,
@@ -9419,13 +9436,13 @@ export default {
1
],
"fileAttachments": [
- 527,
+ 529,
"[FileAttachmentInput!]"
]
}
],
"retryChatMessage": [
- 350,
+ 351,
{
"threadId": [
3,
@@ -9437,7 +9454,7 @@ export default {
}
],
"answerAgentChatQuestion": [
- 350,
+ 351,
{
"threadId": [
3,
@@ -9448,14 +9465,14 @@ export default {
"UUID!"
],
"answers": [
- 528,
+ 530,
"[AgentChatQuestionAnswerInput!]!"
],
"modelId": [
1
],
"fileAttachments": [
- 527,
+ 529,
"[FileAttachmentInput!]"
]
}
@@ -9470,7 +9487,7 @@ export default {
}
],
"renameChatThread": [
- 345,
+ 346,
{
"id": [
3,
@@ -9483,7 +9500,7 @@ export default {
}
],
"archiveChatThread": [
- 345,
+ 346,
{
"id": [
3,
@@ -9492,7 +9509,7 @@ export default {
}
],
"unarchiveChatThread": [
- 345,
+ 346,
{
"id": [
3,
@@ -9519,7 +9536,7 @@ export default {
}
],
"startWorkspaceSetupChat": [
- 352,
+ 353,
{
"companyContext": [
9
@@ -9530,25 +9547,25 @@ export default {
}
],
"createSkill": [
- 343,
+ 344,
{
"input": [
- 529,
+ 531,
"CreateSkillInput!"
]
}
],
"updateSkill": [
- 343,
+ 344,
{
"input": [
- 530,
+ 532,
"UpdateSkillInput!"
]
}
],
"deleteSkill": [
- 343,
+ 344,
{
"id": [
3,
@@ -9557,7 +9574,7 @@ export default {
}
],
"activateSkill": [
- 343,
+ 344,
{
"id": [
3,
@@ -9566,7 +9583,7 @@ export default {
}
],
"deactivateSkill": [
- 343,
+ 344,
{
"id": [
3,
@@ -9575,7 +9592,7 @@ export default {
}
],
"evaluateAgentTurn": [
- 354,
+ 355,
{
"turnId": [
3,
@@ -9584,7 +9601,7 @@ export default {
}
],
"runEvaluationInput": [
- 355,
+ 356,
{
"agentId": [
3,
@@ -9597,16 +9614,16 @@ export default {
}
],
"updateTimelineActivityType": [
- 372,
+ 373,
{
"input": [
- 531,
+ 533,
"UpdateTimelineActivityTypeInput!"
]
}
],
"resetTimelineActivityType": [
- 372,
+ 373,
{
"id": [
3,
@@ -9618,7 +9635,7 @@ export default {
267,
{
"input": [
- 532,
+ 534,
"GetAuthorizationUrlForSSOInput!"
]
}
@@ -9784,7 +9801,7 @@ export default {
270,
{
"input": [
- 533
+ 535
]
}
],
@@ -9796,7 +9813,7 @@ export default {
"String!"
],
"file": [
- 401,
+ 402,
"Upload!"
]
}
@@ -9962,7 +9979,7 @@ export default {
8,
{
"input": [
- 534,
+ 536,
"UpdateWorkspaceMemberSettingsInput!"
]
}
@@ -9996,7 +10013,7 @@ export default {
224,
{
"input": [
- 535,
+ 537,
"SetupOIDCSsoInput!"
]
}
@@ -10005,7 +10022,7 @@ export default {
224,
{
"input": [
- 536,
+ 538,
"SetupSAMLSsoInput!"
]
}
@@ -10014,7 +10031,7 @@ export default {
220,
{
"input": [
- 537,
+ 539,
"DeleteSsoInput!"
]
}
@@ -10023,13 +10040,13 @@ export default {
221,
{
"input": [
- 538,
+ 540,
"EditSsoInput!"
]
}
],
"createObjectEvent": [
- 339,
+ 340,
{
"event": [
1,
@@ -10049,10 +10066,10 @@ export default {
}
],
"trackAnalytics": [
- 339,
+ 340,
{
"type": [
- 539,
+ 541,
"AnalyticsType!"
],
"name": [
@@ -10067,7 +10084,7 @@ export default {
}
],
"duplicateDashboard": [
- 337,
+ 338,
{
"id": [
3,
@@ -10092,25 +10109,25 @@ export default {
282
],
"createCalendarEvent": [
- 329,
+ 330,
{
"input": [
- 540,
+ 542,
"CreateCalendarEventInput!"
]
}
],
"sendEmail": [
- 338,
+ 339,
{
"input": [
- 541,
+ 543,
"SendEmailInput!"
]
}
],
"startChannelSync": [
- 328,
+ 329,
{
"connectedAccountId": [
3,
@@ -10119,14 +10136,14 @@ export default {
}
],
"saveImapSmtpCaldavAccount": [
- 323,
+ 324,
{
"handle": [
1,
"String!"
],
"connectionParameters": [
- 543,
+ 545,
"EmailAccountConnectionParameters!"
],
"id": [
@@ -10138,7 +10155,7 @@ export default {
185,
{
"input": [
- 545,
+ 547,
"UpdateLabPublicFeatureFlagInput!"
]
}
@@ -10203,7 +10220,7 @@ export default {
284,
{
"file": [
- 401,
+ 402,
"Upload!"
],
"applicationUniversalIdentifier": [
@@ -10228,7 +10245,7 @@ export default {
"String!"
],
"files": [
- 546,
+ 548,
"[ApplicationFileUploadRequestInput!]!"
]
}
@@ -10351,7 +10368,7 @@ export default {
3
],
"update": [
- 400
+ 401
],
"__typename": [
1
@@ -10490,7 +10507,7 @@ export default {
3
],
"update": [
- 407
+ 408
],
"__typename": [
1
@@ -10661,19 +10678,19 @@ export default {
3
],
"view": [
- 413
+ 414
],
"viewFields": [
- 414
+ 415
],
"viewFilters": [
- 415
+ 416
],
"viewFilterGroups": [
- 416
+ 417
],
"viewSorts": [
- 417
+ 418
],
"__typename": [
1
@@ -10822,7 +10839,7 @@ export default {
3
],
"update": [
- 420
+ 421
],
"__typename": [
1
@@ -10860,7 +10877,7 @@ export default {
3
],
"update": [
- 424
+ 425
],
"__typename": [
1
@@ -10936,7 +10953,7 @@ export default {
3
],
"update": [
- 429
+ 430
],
"__typename": [
1
@@ -11000,10 +11017,10 @@ export default {
3
],
"groups": [
- 434
+ 435
],
"fields": [
- 435
+ 436
],
"__typename": [
1
@@ -11023,7 +11040,7 @@ export default {
8
],
"fields": [
- 435
+ 436
],
"__typename": [
1
@@ -11194,7 +11211,7 @@ export default {
8
],
"tabs": [
- 447
+ 448
],
"__typename": [
1
@@ -11217,7 +11234,7 @@ export default {
87
],
"widgets": [
- 448
+ 449
],
"__typename": [
1
@@ -11382,7 +11399,7 @@ export default {
},
"CreateOneObjectInput": {
"object": [
- 454
+ 455
],
"__typename": [
1
@@ -11442,7 +11459,7 @@ export default {
},
"UpdateOneObjectInput": {
"update": [
- 457
+ 458
],
"id": [
3
@@ -11495,7 +11512,7 @@ export default {
24
],
"translations": [
- 458
+ 459
],
"__typename": [
1
@@ -11517,7 +11534,7 @@ export default {
},
"CreateOneIndexInput": {
"index": [
- 460
+ 461
],
"__typename": [
1
@@ -11528,7 +11545,7 @@ export default {
3
],
"fields": [
- 461
+ 462
],
"indexType": [
246
@@ -11613,7 +11630,7 @@ export default {
3
],
"update": [
- 466
+ 467
],
"__typename": [
1
@@ -11773,7 +11790,7 @@ export default {
3
],
"update": [
- 471
+ 472
],
"__typename": [
1
@@ -11900,7 +11917,7 @@ export default {
1
],
"update": [
- 476
+ 477
],
"__typename": [
1
@@ -11954,7 +11971,7 @@ export default {
1
],
"update": [
- 479
+ 480
],
"__typename": [
1
@@ -11984,7 +12001,7 @@ export default {
},
"CreateOneFieldMetadataInput": {
"field": [
- 482
+ 483
],
"__typename": [
1
@@ -12057,7 +12074,7 @@ export default {
3
],
"update": [
- 484
+ 485
],
"__typename": [
1
@@ -12116,7 +12133,7 @@ export default {
9
],
"translations": [
- 458
+ 459
],
"__typename": [
1
@@ -12155,7 +12172,7 @@ export default {
3
],
"update": [
- 488
+ 489
],
"__typename": [
1
@@ -12240,7 +12257,7 @@ export default {
},
"UpdateRoleInput": {
"update": [
- 493
+ 494
],
"id": [
3
@@ -12295,7 +12312,7 @@ export default {
3
],
"objectPermissions": [
- 495
+ 496
],
"__typename": [
1
@@ -12337,7 +12354,7 @@ export default {
3
],
"fieldPermissions": [
- 498
+ 499
],
"__typename": [
1
@@ -12368,10 +12385,10 @@ export default {
3
],
"predicates": [
- 500
+ 501
],
"predicateGroups": [
- 501
+ 502
],
"__typename": [
1
@@ -12497,6 +12514,17 @@ export default {
1
]
},
+ "CreateMessageSuppressionInput": {
+ "emailAddress": [
+ 1
+ ],
+ "unsubscribeTopicId": [
+ 3
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"CreateUnsubscribeTopicInput": {
"name": [
1
@@ -12505,7 +12533,7 @@ export default {
1
],
"visibility": [
- 316
+ 317
],
"__typename": [
1
@@ -12522,7 +12550,7 @@ export default {
1
],
"visibility": [
- 316
+ 317
],
"__typename": [
1
@@ -12533,7 +12561,7 @@ export default {
3
],
"update": [
- 509
+ 511
],
"__typename": [
1
@@ -12541,16 +12569,16 @@ export default {
},
"UpdateMessageChannelInputUpdates": {
"visibility": [
- 298
+ 300
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 300
+ 302
],
"messageFolderImportPolicy": [
- 301
+ 303
],
"isSyncEnabled": [
8
@@ -12606,7 +12634,7 @@ export default {
3
],
"messages": [
- 514
+ 516
],
"__typename": [
1
@@ -12614,7 +12642,7 @@ export default {
},
"RunAgentMessageInput": {
"role": [
- 515
+ 517
],
"content": [
1
@@ -12649,7 +12677,7 @@ export default {
3
],
"update": [
- 518
+ 520
],
"__typename": [
1
@@ -12677,7 +12705,7 @@ export default {
3
],
"update": [
- 520
+ 522
],
"__typename": [
1
@@ -12696,7 +12724,7 @@ export default {
3
],
"update": [
- 520
+ 522
],
"__typename": [
1
@@ -12707,7 +12735,7 @@ export default {
3
],
"update": [
- 523
+ 525
],
"__typename": [
1
@@ -12715,13 +12743,13 @@ export default {
},
"UpdateCalendarChannelInputUpdates": {
"visibility": [
- 364
+ 365
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 365
+ 366
],
"isSyncEnabled": [
8
@@ -12738,7 +12766,7 @@ export default {
9
],
"scope": [
- 360
+ 361
],
"__typename": [
1
@@ -12866,7 +12894,7 @@ export default {
8
],
"translations": [
- 458
+ 459
],
"__typename": [
1
@@ -13032,7 +13060,7 @@ export default {
1
],
"files": [
- 542
+ 544
],
"__typename": [
1
@@ -13054,13 +13082,13 @@ export default {
1
],
"IMAP": [
- 544
+ 546
],
"SMTP": [
- 544
+ 546
],
"CALDAV": [
- 544
+ 546
],
"__typename": [
1
@@ -13125,13 +13153,13 @@ export default {
259,
{
"input": [
- 548,
+ 550,
"LogicFunctionLogsInput!"
]
}
],
"onAgentChatEvent": [
- 351,
+ 352,
{
"threadId": [
3,
@@ -13140,10 +13168,10 @@ export default {
}
],
"eventLogsLive": [
- 340,
+ 341,
{
"table": [
- 389,
+ 390,
"EventLogTable!"
]
}
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index c165078da79..d9b6906f876 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -900,19 +900,13 @@ export type CampaignAudiencePreviewDto = {
__typename?: 'CampaignAudiencePreviewDTO';
duplicateEmails: Scalars['Int']['output'];
globallyUnsubscribed: Scalars['Int']['output'];
+ overCap: Scalars['Int']['output'];
sendable: Scalars['Int']['output'];
topicUnsubscribed: Scalars['Int']['output'];
totalMembers: Scalars['Int']['output'];
withoutEmail: Scalars['Int']['output'];
};
-export type CampaignSkippedRecipientsDto = {
- __typename?: 'CampaignSkippedRecipientsDTO';
- deduped: Scalars['Int']['output'];
- noEmail: Scalars['Int']['output'];
- overCap: Scalars['Int']['output'];
-};
-
export type CancelMessageCampaignInput = {
campaignId: Scalars['String']['input'];
};
@@ -1293,6 +1287,11 @@ export type CreateLogicFunctionFromSourceInput = {
workflowActionTriggerSettings?: InputMaybe<Scalars['JSON']['input']>;
};
+export type CreateMessageSuppressionInput = {
+ emailAddress: Scalars['String']['input'];
+ unsubscribeTopicId?: InputMaybe<Scalars['UUID']['input']>;
+};
+
export type CreateNavigationMenuItemInput = {
color?: InputMaybe<Scalars['String']['input']>;
folderId?: InputMaybe<Scalars['UUID']['input']>;
@@ -1670,6 +1669,8 @@ export type EmailingDomain = {
domain: Scalars['String']['output'];
id: Scalars['UUID']['output'];
status: EmailingDomainStatus;
+ tenantStatus: EmailingDomainTenantStatus;
+ unsubscribeHostnameStatus?: Maybe<UnsubscribeHostnameStatus>;
updatedAt: Scalars['DateTime']['output'];
verificationRecords?: Maybe<Array<VerificationRecord>>;
verifiedAt?: Maybe<Scalars['DateTime']['output']>;
@@ -1682,6 +1683,12 @@ export enum EmailingDomainStatus {
VERIFIED = 'VERIFIED'
}
+export enum EmailingDomainTenantStatus {
+ ACTIVE = 'ACTIVE',
+ PAUSED = 'PAUSED',
+ SANDBOX = 'SANDBOX'
+}
+
export type EmailsConfiguration = {
__typename?: 'EmailsConfiguration';
configurationType: WidgetConfigurationType;
@@ -2747,6 +2754,7 @@ export type Mutation = {
createManyViewFieldGroups: Array<ViewFieldGroup>;
createManyViewFields: Array<ViewField>;
createManyViewGroups: Array<ViewGroup>;
+ createMessageSuppression: MessageSuppression;
createNavigationMenuItem: NavigationMenuItem;
createOIDCIdentityProvider: SetupSso;
createObjectEvent: Analytics;
@@ -2785,6 +2793,7 @@ export type Mutation = {
deleteEmailingDomain: Scalars['Boolean']['output'];
deleteFrontComponent: FrontComponent;
deleteManyNavigationMenuItems: Array<NavigationMenuItem>;
+ deleteMessageSuppression: Scalars['Boolean']['output'];
deleteNavigationMenuItem: NavigationMenuItem;
deleteOneAgent: Agent;
deleteOneField: Field;
@@ -3141,6 +3150,11 @@ export type MutationCreateManyViewGroupsArgs = {
};
+export type MutationCreateMessageSuppressionArgs = {
+ input: CreateMessageSuppressionInput;
+};
+
+
export type MutationCreateNavigationMenuItemArgs = {
input: CreateNavigationMenuItemInput;
};
@@ -3335,6 +3349,11 @@ export type MutationDeleteManyNavigationMenuItemsArgs = {
};
+export type MutationDeleteMessageSuppressionArgs = {
+ id: Scalars['UUID']['input'];
+};
+
+
export type MutationDeleteNavigationMenuItemArgs = {
id: Scalars['UUID']['input'];
};
@@ -5563,9 +5582,9 @@ export type SendMessageCampaignInput = {
export type SendMessageCampaignOutputDto = {
__typename?: 'SendMessageCampaignOutputDTO';
+ audience: CampaignAudiencePreviewDto;
campaignId: Scalars['String']['output'];
queuedCount: Scalars['Int']['output'];
- skipped: CampaignSkippedRecipientsDto;
};
export type SendMessageCampaignTestInput = {
@@ -5805,6 +5824,12 @@ export type UuidFilterComparison = {
notLike?: InputMaybe<Scalars['UUID']['input']>;
};
+export enum UnsubscribeHostnameStatus {
+ ACTIVE = 'ACTIVE',
+ FAILED = 'FAILED',
+ PENDING = 'PENDING'
+}
+
export type UnsubscribeTopic = {
__typename?: 'UnsubscribeTopic';
createdAt: Scalars['DateTime']['output'];
@@ -7099,7 +7124,7 @@ export type SendMessageCampaignMutationVariables = Exact<{
}>;
-export type SendMessageCampaignMutation = { __typename?: 'Mutation', sendMessageCampaign: { __typename?: 'SendMessageCampaignOutputDTO', campaignId: string, queuedCount: number, skipped: { __typename?: 'CampaignSkippedRecipientsDTO', noEmail: number, deduped: number, overCap: number } } };
+export type SendMessageCampaignMutation = { __typename?: 'Mutation', sendMessageCampaign: { __typename?: 'SendMessageCampaignOutputDTO', campaignId: string, queuedCount: number, audience: { __typename?: 'CampaignAudiencePreviewDTO', totalMembers: number, withoutEmail: number, duplicateEmails: number, overCap: number, globallyUnsubscribed: number, topicUnsubscribed: number, sendable: number } } };
export type SendMessageCampaignTestMutationVariables = Exact<{
input: SendMessageCampaignTestInput;
@@ -9759,7 +9784,7 @@ export const CreateCalendarEventDocument = {"kind":"Document","definitions":[{"k
export const PreviewMessageCampaignAudienceDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"PreviewMessageCampaignAudience"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"PreviewMessageCampaignAudienceInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"previewMessageCampaignAudience"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"totalMembers"}},{"kind":"Field","name":{"kind":"Name","value":"withoutEmail"}},{"kind":"Field","name":{"kind":"Name","value":"duplicateEmails"}},{"kind":"Field","name":{"kind":"Name","value":"globallyUnsubscribed"}},{"kind":"Field","name":{"kind":"Name","value":"topicUnsubscribed"}},{"kind":"Field","name":{"kind":"Name","value":"sendable"}}]}}]}}]} as unknown as DocumentNode<PreviewMessageCampaignAudienceQuery, PreviewMessageCampaignAudienceQueryVariables>;
export const UnsubscribeTopicsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"UnsubscribeTopics"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"unsubscribeTopics"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}}]}}]}}]} as unknown as DocumentNode<UnsubscribeTopicsQuery, UnsubscribeTopicsQueryVariables>;
export const SendEmailDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SendEmail"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SendEmailInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sendEmail"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"success"}},{"kind":"Field","name":{"kind":"Name","value":"error"}},{"kind":"Field","name":{"kind":"Name","value":"messageThreadId"}}]}}]}}]} as unknown as DocumentNode<SendEmailMutation, SendEmailMutationVariables>;
-export const SendMessageCampaignDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SendMessageCampaign"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SendMessageCampaignInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sendMessageCampaign"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"campaignId"}},{"kind":"Field","name":{"kind":"Name","value":"queuedCount"}},{"kind":"Field","name":{"kind":"Name","value":"skipped"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"noEmail"}},{"kind":"Field","name":{"kind":"Name","value":"deduped"}},{"kind":"Field","name":{"kind":"Name","value":"overCap"}}]}}]}}]}}]} as unknown as DocumentNode<SendMessageCampaignMutation, SendMessageCampaignMutationVariables>;
+export const SendMessageCampaignDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SendMessageCampaign"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SendMessageCampaignInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sendMessageCampaign"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"campaignId"}},{"kind":"Field","name":{"kind":"Name","value":"queuedCount"}},{"kind":"Field","name":{"kind":"Name","value":"audience"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"totalMembers"}},{"kind":"Field","name":{"kind":"Name","value":"withoutEmail"}},{"kind":"Field","name":{"kind":"Name","value":"duplicateEmails"}},{"kind":"Field","name":{"kind":"Name","value":"overCap"}},{"kind":"Field","name":{"kind":"Name","value":"globallyUnsubscribed"}},{"kind":"Field","name":{"kind":"Name","value":"topicUnsubscribed"}},{"kind":"Field","name":{"kind":"Name","value":"sendable"}}]}}]}}]}}]} as unknown as DocumentNode<SendMessageCampaignMutation, SendMessageCampaignMutationVariables>;
export const SendMessageCampaignTestDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SendMessageCampaignTest"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SendMessageCampaignTestInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sendMessageCampaignTest"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"messageId"}}]}}]}}]} as unknown as DocumentNode<SendMessageCampaignTestMutation, SendMessageCampaignTestMutationVariables>;
export const ResetTimelineActivityTypeDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ResetTimelineActivityType"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"resetTimelineActivityType"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}}]}}]}}]} as unknown as DocumentNode<ResetTimelineActivityTypeMutation, ResetTimelineActivityTypeMutationVariables>;
export const UpdateTimelineActivityTypeIsActiveDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateTimelineActivityTypeIsActive"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateTimelineActivityTypeInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateTimelineActivityType"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}}]}}]}}]} as unknown as DocumentNode<UpdateTimelineActivityTypeIsActiveMutation, UpdateTimelineActivityTypeIsActiveMutationVariables>;
diff --git a/packages/twenty-front/src/modules/activities/emails/graphql/mutations/sendMessageCampaign.ts b/packages/twenty-front/src/modules/activities/emails/graphql/mutations/sendMessageCampaign.ts
index 675a4988360..1e6730a6399 100644
--- a/packages/twenty-front/src/modules/activities/emails/graphql/mutations/sendMessageCampaign.ts
+++ b/packages/twenty-front/src/modules/activities/emails/graphql/mutations/sendMessageCampaign.ts
@@ -5,10 +5,14 @@ export const SEND_MESSAGE_CAMPAIGN = gql`
sendMessageCampaign(input: $input) {
campaignId
queuedCount
- skipped {
- noEmail
- deduped
+ audience {
+ totalMembers
+ withoutEmail
+ duplicateEmails
overCap
+ globallyUnsubscribed
+ topicUnsubscribed
+ sendable
}
}
}
diff --git a/packages/twenty-front/src/modules/activities/emails/hooks/useSendMessageCampaign.ts b/packages/twenty-front/src/modules/activities/emails/hooks/useSendMessageCampaign.ts
index 2e51fecde22..c1b29c1974c 100644
--- a/packages/twenty-front/src/modules/activities/emails/hooks/useSendMessageCampaign.ts
+++ b/packages/twenty-front/src/modules/activities/emails/hooks/useSendMessageCampaign.ts
@@ -37,8 +37,8 @@ export const useSendMessageCampaign = () => {
return false;
}
- const { queuedCount, skipped } = queued;
- const skippedCount = skipped.noEmail + skipped.deduped + skipped.overCap;
+ const { queuedCount, audience } = queued;
+ const skippedCount = audience.totalMembers - audience.sendable;
if (queuedCount === 0) {
enqueueErrorSnackBar({
diff --git a/packages/twenty-server/src/database/commands/cron-register-all.command.ts b/packages/twenty-server/src/database/commands/cron-register-all.command.ts
index c50c34e6b78..20b313062e7 100644
--- a/packages/twenty-server/src/database/commands/cron-register-all.command.ts
+++ b/packages/twenty-server/src/database/commands/cron-register-all.command.ts
@@ -19,6 +19,7 @@ import { UserSessionCleanupCronCommand } from 'src/engine/core-modules/user-sess
import { CheckCustomDomainValidRecordsCronCommand } from 'src/engine/core-modules/workspace/crons/commands/check-custom-domain-valid-records.cron.command';
import { WebhookSubscriptionRenewalCronCommand } from 'src/modules/connected-account/webhook-subscription-manager/crons/commands/webhook-subscription-renewal.cron.command';
import { EmailingOngoingStaleCronCommand } from 'src/modules/emailing/crons/commands/emailing-ongoing-stale.cron.command';
+import { ReconcileCampaignStatsCronCommand } from 'src/modules/emailing/crons/commands/reconcile-campaign-stats.cron.command';
import { TrashCleanupCronCommand } from 'src/engine/trash-cleanup/commands/trash-cleanup.cron.command';
import { CleanOnboardingWorkspacesCronCommand } from 'src/engine/workspace-manager/workspace-cleaner/commands/clean-onboarding-workspaces.cron.command';
import { CleanSuspendedWorkspacesCronCommand } from 'src/engine/workspace-manager/workspace-cleaner/commands/clean-suspended-workspaces.cron.command';
@@ -57,6 +58,7 @@ export class CronRegisterAllCommand extends CommandRunner {
private readonly webhookSubscriptionRenewalCronCommand: WebhookSubscriptionRenewalCronCommand,
private readonly emailingOngoingStaleCronCommand: EmailingOngoingStaleCronCommand,
+ private readonly reconcileCampaignStatsCronCommand: ReconcileCampaignStatsCronCommand,
private readonly workflowCronTriggerCronCommand: WorkflowCronTriggerCronCommand,
private readonly workflowRunEnqueueCronCommand: WorkflowRunEnqueueCronCommand,
@@ -139,6 +141,10 @@ export class CronRegisterAllCommand extends CommandRunner {
name: 'EmailingOngoingStale',
command: this.emailingOngoingStaleCronCommand,
},
+ {
+ name: 'ReconcileCampaignStats',
+ command: this.reconcileCampaignStatsCronCommand,
+ },
{
name: 'CheckCustomDomainValidRecords',
command: this.checkCustomDomainValidRecordsCronCommand,
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788272351966-rename-emailing-domain-permanently-suspended-to-sandbox.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788272351966-rename-emailing-domain-permanently-suspended-to-sandbox.ts
new file mode 100644
index 00000000000..e29d7baf388
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788272351966-rename-emailing-domain-permanently-suspended-to-sandbox.ts
@@ -0,0 +1,48 @@
+import { QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';
+
+@RegisteredInstanceCommand('2.38.0', 1788272351966)
+export class RenameEmailingDomainPermanentlySuspendedToSandboxFastInstanceCommand
+ implements FastInstanceCommand
+{
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ if (!(await this.hasEnumLabel(queryRunner, 'PERMANENTLY_SUSPENDED'))) {
+ return;
+ }
+
+ await queryRunner.query(
+ `ALTER TYPE "core"."emailingDomain_tenantstatus_enum" RENAME VALUE 'PERMANENTLY_SUSPENDED' TO 'SANDBOX'`,
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ if (!(await this.hasEnumLabel(queryRunner, 'SANDBOX'))) {
+ return;
+ }
+
+ await queryRunner.query(
+ `ALTER TYPE "core"."emailingDomain_tenantstatus_enum" RENAME VALUE 'SANDBOX' TO 'PERMANENTLY_SUSPENDED'`,
+ );
+ }
+
+ private async hasEnumLabel(
+ queryRunner: QueryRunner,
+ enumLabel: string,
+ ): Promise<boolean> {
+ const [{ exists }] = await queryRunner.query(
+ `SELECT EXISTS (
+ SELECT 1 FROM pg_enum e
+ JOIN pg_type t ON t.oid = e.enumtypid
+ JOIN pg_namespace n ON n.oid = t.typnamespace
+ WHERE n.nspname = 'core'
+ AND t.typname = 'emailingDomain_tenantstatus_enum'
+ AND e.enumlabel = $1
+ ) AS exists`,
+ [enumLabel],
+ );
+
+ return exists;
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
index 80753482c93..dc166f24bec 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
@@ -168,6 +168,7 @@ import { AddTimelineActivityHappensAtFieldFastInstanceCommand } from 'src/databa
import { AddPageLayoutIsFirstTabPinnedFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1787929843737-add-page-layout-is-first-tab-pinned';
import { CreateCampaignDeliveryFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788200700000-create-campaign-delivery';
import { AddStateToApplicationFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788260646460-add-state-to-application';
+import { RenameEmailingDomainPermanentlySuspendedToSandboxFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788272351966-rename-emailing-domain-permanently-suspended-to-sandbox';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -338,4 +339,5 @@ export const INSTANCE_COMMANDS = [
AddPageLayoutIsFirstTabPinnedFastInstanceCommand,
CreateCampaignDeliveryFastInstanceCommand,
AddStateToApplicationFastInstanceCommand,
+ RenameEmailingDomainPermanentlySuspendedToSandboxFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.ts b/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.ts
index 31ec846e6d3..c45b46977ab 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.ts
@@ -62,9 +62,9 @@ export class BillingSubscriptionItemResolver {
}
const creditAvailability =
- await this.billingUsageService.getCreditAvailability(
- billingSubscription.workspaceId,
- );
+ await this.billingUsageService.getCreditAvailability({
+ workspaceId: billingSubscription.workspaceId,
+ });
return (
!creditAvailability.hasAvailableCredits &&
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts
index 0d337a35d63..e99c356383c 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts
@@ -22,6 +22,7 @@ import { BillingSubscriptionItemService } from 'src/engine/core-modules/billing/
import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';
import { buildBillingCreditStateLockKey } from 'src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util';
+import { type CurrentBillingSubscription } from 'src/engine/core-modules/billing/types/flat-billing-subscription.type';
import { getBillingSubscriptionPeriod } from 'src/engine/core-modules/billing/utils/get-billing-subscription-period.util';
import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
import {
@@ -243,14 +244,17 @@ export class BillingUsageService {
async decrementAvailableCreditsInCache({
workspaceId,
usedCredits,
+ currentBillingSubscription: providedCurrentBillingSubscription,
}: {
workspaceId: string;
usedCredits: number;
+ currentBillingSubscription?: CurrentBillingSubscription;
}): Promise<number> {
- const { currentBillingSubscription } =
- await this.workspaceCacheService.getOrRecompute(workspaceId, [
- 'currentBillingSubscription',
- ]);
+ const currentBillingSubscription =
+ await this.resolveCurrentBillingSubscription({
+ workspaceId,
+ providedCurrentBillingSubscription,
+ });
if (currentBillingSubscription === NO_BILLING_SUBSCRIPTION) {
return 0;
@@ -356,9 +360,13 @@ export class BillingUsageService {
return { availableCredits, isCounterWarm: true };
}
- async getCreditAvailability(
- workspaceId: string,
- ): Promise<CreditAvailability> {
+ async getCreditAvailability({
+ workspaceId,
+ currentBillingSubscription: providedCurrentBillingSubscription,
+ }: {
+ workspaceId: string;
+ currentBillingSubscription?: CurrentBillingSubscription;
+ }): Promise<CreditAvailability> {
if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {
return { hasAvailableCredits: true };
}
@@ -375,10 +383,11 @@ export class BillingUsageService {
return { hasAvailableCredits: false, reason: 'workspace-suspended' };
}
- const { currentBillingSubscription } =
- await this.workspaceCacheService.getOrRecompute(workspaceId, [
- 'currentBillingSubscription',
- ]);
+ const currentBillingSubscription =
+ await this.resolveCurrentBillingSubscription({
+ workspaceId,
+ providedCurrentBillingSubscription,
+ });
if (currentBillingSubscription === NO_BILLING_SUBSCRIPTION) {
return { hasAvailableCredits: false, reason: 'no-subscription' };
@@ -398,8 +407,9 @@ export class BillingUsageService {
}
async hasAvailableCredits(workspaceId: string): Promise<boolean> {
- const { hasAvailableCredits } =
- await this.getCreditAvailability(workspaceId);
+ const { hasAvailableCredits } = await this.getCreditAvailability({
+ workspaceId,
+ });
return hasAvailableCredits;
}
@@ -480,4 +490,21 @@ export class BillingUsageService {
return usedMicro ?? 0;
}
+
+ async resolveCurrentBillingSubscription({
+ workspaceId,
+ providedCurrentBillingSubscription,
+ }: {
+ workspaceId: string;
+ providedCurrentBillingSubscription?: CurrentBillingSubscription;
+ }): Promise<CurrentBillingSubscription> {
+ return (
+ providedCurrentBillingSubscription ??
+ (
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'currentBillingSubscription',
+ ])
+ ).currentBillingSubscription
+ );
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-delivery-state.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-delivery-state.constant.ts
index f2f52365a1f..e17c2202f17 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-delivery-state.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-delivery-state.constant.ts
@@ -4,5 +4,4 @@ export const CAMPAIGN_DELIVERY_STATE = {
SENT: 'SENT',
FAILED: 'FAILED',
SKIPPED: 'SKIPPED',
- UNCERTAIN: 'UNCERTAIN',
} as const;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-failure-reason.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-failure-reason.constant.ts
index 60b66437ed8..f3d327c12e8 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-failure-reason.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-failure-reason.constant.ts
@@ -6,9 +6,7 @@ export const CAMPAIGN_FAILURE_REASON = {
SENDING_SUSPENDED: 'SENDING_SUSPENDED',
UNSUBSCRIBE_NOT_READY: 'UNSUBSCRIBE_NOT_READY',
UNSUBSCRIBE_MULTIPLE_RECIPIENTS: 'UNSUBSCRIBE_MULTIPLE_RECIPIENTS',
- REJECTED: 'REJECTED',
- RENDERING_FAILED: 'RENDERING_FAILED',
- RETRY_EXHAUSTED: 'RETRY_EXHAUSTED',
CLAIM_EXPIRED: 'CLAIM_EXPIRED',
+ RATE_LIMITED: 'RATE_LIMITED',
UNKNOWN: 'UNKNOWN',
} as const;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-job-retry-limit.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-job-retry-limit.constant.ts
new file mode 100644
index 00000000000..9f4db05f152
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-job-retry-limit.constant.ts
@@ -0,0 +1 @@
+export const CAMPAIGN_JOB_RETRY_LIMIT = 3;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-skip-reason.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-skip-reason.constant.ts
index 06a686e687f..642f9b838d2 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-skip-reason.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-skip-reason.constant.ts
@@ -2,6 +2,4 @@ export const CAMPAIGN_SKIP_REASON = {
SUPPRESSED: 'SUPPRESSED',
OUT_OF_CREDITS: 'OUT_OF_CREDITS',
CAMPAIGN_CANCELED: 'CAMPAIGN_CANCELED',
- REPUTATION_BLOCKED: 'REPUTATION_BLOCKED',
- NO_EMAIL_ADDRESS: 'NO_EMAIL_ADDRESS',
} as const;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign.constant.ts
index 728cb4e23a3..5627be78a07 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign.constant.ts
@@ -1,20 +1,11 @@
-export const CAMPAIGN_MESSAGE_DELIVERY_STATUS = {
- QUEUED: 'QUEUED',
- SENT: 'SENT',
- FAILED: 'FAILED',
- BOUNCED: 'BOUNCED',
- COMPLAINED: 'COMPLAINED',
- SKIPPED: 'SKIPPED',
-} as const;
-
export const MATERIALIZE_CAMPAIGN_JOB = 'MaterializeCampaignJob';
export const MATERIALIZE_CAMPAIGN_CHUNK_JOB = 'MaterializeCampaignChunkJob';
export const SEND_CAMPAIGN_EMAIL_JOB = 'SendCampaignEmailJob';
export const REFRESH_CAMPAIGN_STATS_JOB = 'RefreshCampaignStatsJob';
+export const RECONCILE_WORKSPACE_CAMPAIGN_STATS_JOB =
+ 'ReconcileWorkspaceCampaignStatsJob';
export const CAMPAIGN_STATS_REFRESH_DEBOUNCE_MS = 10_000;
-export const CAMPAIGN_STATS_REFRESH_DELAY_MS =
- CAMPAIGN_STATS_REFRESH_DEBOUNCE_MS + 2_000;
export const MAX_CAMPAIGN_RECIPIENTS = 10000;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/hard-suppression-reasons.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/hard-suppression-reasons.constant.ts
index deff940c158..66aab9bd31e 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/hard-suppression-reasons.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/hard-suppression-reasons.constant.ts
@@ -4,8 +4,3 @@ export const HARD_SUPPRESSION_REASONS = [
MessageSuppressionReason.BOUNCE,
MessageSuppressionReason.COMPLAINT,
];
-
-export const GLOBAL_BLOCKING_SUPPRESSION_REASONS = [
- ...HARD_SUPPRESSION_REASONS,
- MessageSuppressionReason.UNSUBSCRIBE,
-];
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/unsubscribe-token-max-age-ms.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/unsubscribe-token-max-age-ms.constant.ts
new file mode 100644
index 00000000000..707afa71378
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/unsubscribe-token-max-age-ms.constant.ts
@@ -0,0 +1,5 @@
+const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;
+const UNSUBSCRIBE_TOKEN_MAX_AGE_DAYS = 730;
+
+export const UNSUBSCRIBE_TOKEN_MAX_AGE_MS =
+ UNSUBSCRIBE_TOKEN_MAX_AGE_DAYS * MILLISECONDS_PER_DAY;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-configuration-error-names.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-configuration-error-names.constant.ts
new file mode 100644
index 00000000000..111786be047
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-configuration-error-names.constant.ts
@@ -0,0 +1,8 @@
+export const AWS_SES_CONFIGURATION_ERROR_NAMES = [
+ 'InvalidParameterValue',
+ 'InvalidParameterCombination',
+ 'MissingParameter',
+ 'MessageRejected',
+ 'MailFromDomainNotVerifiedException',
+ 'FromEmailAddressNotVerifiedException',
+];
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-insufficient-permissions-error-names.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-insufficient-permissions-error-names.constant.ts
new file mode 100644
index 00000000000..c7f367bf48c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-insufficient-permissions-error-names.constant.ts
@@ -0,0 +1,4 @@
+export const AWS_SES_INSUFFICIENT_PERMISSIONS_ERROR_NAMES = [
+ 'AccessDeniedException',
+ 'AccountSuspendedException',
+];
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-throttling-and-transient-error-names.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-throttling-and-transient-error-names.constant.ts
new file mode 100644
index 00000000000..3484851a7f4
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-throttling-and-transient-error-names.constant.ts
@@ -0,0 +1,9 @@
+export const AWS_SES_THROTTLING_AND_TRANSIENT_ERROR_NAMES = [
+ 'ThrottlingException',
+ 'Throttling',
+ 'TooManyRequestsException',
+ 'LimitExceededException',
+ 'ServiceUnavailable',
+ 'InternalFailure',
+ 'RequestTimeout',
+];
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/get-aws-ses-driver-exception-code.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/get-aws-ses-driver-exception-code.util.ts
index 427f4db05c4..8aff5390847 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/get-aws-ses-driver-exception-code.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/aws-ses/utils/get-aws-ses-driver-exception-code.util.ts
@@ -1,39 +1,18 @@
import { isDefined } from 'twenty-shared/utils';
+import { AWS_SES_CONFIGURATION_ERROR_NAMES } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-configuration-error-names.constant';
+import { AWS_SES_INSUFFICIENT_PERMISSIONS_ERROR_NAMES } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-insufficient-permissions-error-names.constant';
+import { AWS_SES_THROTTLING_AND_TRANSIENT_ERROR_NAMES } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/constants/aws-ses-throttling-and-transient-error-names.constant';
import { type AwsSesError } from 'src/engine/core-modules/emailing-domain/drivers/aws-ses/types/aws-ses-error.type';
import { EmailingDomainDriverExceptionCode } from 'src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception';
-const THROTTLING_AND_TRANSIENT_ERROR_NAMES = [
- 'ThrottlingException',
- 'Throttling',
- 'TooManyRequestsException',
- 'LimitExceededException',
- 'ServiceUnavailable',
- 'InternalFailure',
- 'RequestTimeout',
-];
-
-const INSUFFICIENT_PERMISSIONS_ERROR_NAMES = [
- 'AccessDeniedException',
- 'AccountSuspendedException',
-];
-
-const CONFIGURATION_ERROR_NAMES = [
- 'InvalidParameterValue',
- 'InvalidParameterCombination',
- 'MissingParameter',
- 'MessageRejected',
- 'MailFromDomainNotVerifiedException',
- 'FromEmailAddressNotVerifiedException',
-];
-
export const getAwsSesDriverExceptionCode = (
error: AwsSesError,
): EmailingDomainDriverExceptionCode => {
const name = error?.name ?? 'UnknownError';
const httpStatus = error?.$metadata?.httpStatusCode;
- if (THROTTLING_AND_TRANSIENT_ERROR_NAMES.includes(name)) {
+ if (AWS_SES_THROTTLING_AND_TRANSIENT_ERROR_NAMES.includes(name)) {
return EmailingDomainDriverExceptionCode.TEMPORARY_ERROR;
}
@@ -43,12 +22,12 @@ export const getAwsSesDriverExceptionCode = (
if (
httpStatus === 403 ||
- INSUFFICIENT_PERMISSIONS_ERROR_NAMES.includes(name)
+ AWS_SES_INSUFFICIENT_PERMISSIONS_ERROR_NAMES.includes(name)
) {
return EmailingDomainDriverExceptionCode.INSUFFICIENT_PERMISSIONS;
}
- if (httpStatus === 400 || CONFIGURATION_ERROR_NAMES.includes(name)) {
+ if (httpStatus === 400 || AWS_SES_CONFIGURATION_ERROR_NAMES.includes(name)) {
return EmailingDomainDriverExceptionCode.CONFIGURATION_ERROR;
}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception.ts
index 7e0e34e34f6..625905ac799 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception.ts
@@ -14,6 +14,7 @@ export enum EmailingDomainDriverExceptionCode {
SANDBOX_ACCOUNT = 'SANDBOX_ACCOUNT',
ALL_RECIPIENTS_SUPPRESSED = 'ALL_RECIPIENTS_SUPPRESSED',
UNSUBSCRIBE_NOT_READY = 'UNSUBSCRIBE_NOT_READY',
+ UNSUBSCRIBE_MULTIPLE_RECIPIENTS = 'UNSUBSCRIBE_MULTIPLE_RECIPIENTS',
UNKNOWN = 'UNKNOWN',
}
@@ -35,6 +36,8 @@ const getEmailingDomainDriverExceptionUserFriendlyMessage = (
return msg`All recipients are suppressed for this email domain.`;
case EmailingDomainDriverExceptionCode.UNSUBSCRIBE_NOT_READY:
return msg`Marketing sending is on hold until the unsubscribe domain is verified.`;
+ case EmailingDomainDriverExceptionCode.UNSUBSCRIBE_MULTIPLE_RECIPIENTS:
+ return msg`A marketing email can only be sent to one recipient at a time, so each person gets their own unsubscribe link.`;
case EmailingDomainDriverExceptionCode.TEMPORARY_ERROR:
case EmailingDomainDriverExceptionCode.UNKNOWN:
return STANDARD_ERROR_MESSAGE;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-email-content.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-email-content.type.ts
index b4c7908030a..f15e4c97ccb 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-email-content.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-email-content.type.ts
@@ -1,7 +1,9 @@
import { type EmailingDomainAttachment } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-attachment.type';
import { type EmailingDomainHeader } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-header.type';
+import { type EmailingDomainSendKind } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-kind.type';
export type EmailingDomainEmailContent = {
+ sendKind: EmailingDomainSendKind;
from: string;
to: string[];
cc?: string[];
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-kind.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-kind.type.ts
new file mode 100644
index 00000000000..d8894f3d7c2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-kind.type.ts
@@ -0,0 +1 @@
+export type EmailingDomainSendKind = 'MARKETING' | 'TRANSACTIONAL';
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-tenant-status.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-tenant-status.type.ts
index 9eff96727df..22c6f10ee38 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-tenant-status.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-tenant-status.type.ts
@@ -1,5 +1,5 @@
export enum EmailingDomainTenantStatus {
ACTIVE = 'ACTIVE',
PAUSED = 'PAUSED',
- PERMANENTLY_SUSPENDED = 'PERMANENTLY_SUSPENDED',
+ SANDBOX = 'SANDBOX',
}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/campaign-audience-preview.dto.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/campaign-audience-preview.dto.ts
index d32166dfa51..3fbdb64ebbb 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/campaign-audience-preview.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/campaign-audience-preview.dto.ts
@@ -11,6 +11,9 @@ export class CampaignAudiencePreviewDTO {
@Field(() => Int)
duplicateEmails: number;
+ @Field(() => Int)
+ overCap: number;
+
@Field(() => Int)
globallyUnsubscribed: number;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/campaign-skipped-recipients.dto.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/campaign-skipped-recipients.dto.ts
deleted file mode 100644
index 8b238cc57ec..00000000000
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/campaign-skipped-recipients.dto.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { Field, Int, ObjectType } from '@nestjs/graphql';
-
-@ObjectType()
-export class CampaignSkippedRecipientsDTO {
- @Field(() => Int)
- noEmail: number;
-
- @Field(() => Int)
- deduped: number;
-
- @Field(() => Int)
- overCap: number;
-}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/create-message-suppression.input.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/create-message-suppression.input.ts
new file mode 100644
index 00000000000..17413b14b21
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/create-message-suppression.input.ts
@@ -0,0 +1,17 @@
+import { Field, InputType } from '@nestjs/graphql';
+
+import { IsEmail, IsOptional, IsUUID } from 'class-validator';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+
+@InputType()
+export class CreateMessageSuppressionInput {
+ @Field(() => String)
+ @IsEmail()
+ emailAddress: string;
+
+ @Field(() => UUIDScalarType, { nullable: true })
+ @IsOptional()
+ @IsUUID('4')
+ unsubscribeTopicId?: string;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/emailing-domain.dto.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/emailing-domain.dto.ts
index 201d6a30a81..fb4a78fbd00 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/emailing-domain.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/emailing-domain.dto.ts
@@ -2,12 +2,22 @@ import { Field, ObjectType, registerEnumType } from '@nestjs/graphql';
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
import { EmailingDomainStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-status.type';
+import { EmailingDomainTenantStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-tenant-status.type';
+import { UnsubscribeHostnameStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/unsubscribe-hostname-status.type';
import { VerificationRecordDTO } from 'src/engine/core-modules/emailing-domain/dtos/verification-record.dto';
registerEnumType(EmailingDomainStatus, {
name: 'EmailingDomainStatus',
});
+registerEnumType(EmailingDomainTenantStatus, {
+ name: 'EmailingDomainTenantStatus',
+});
+
+registerEnumType(UnsubscribeHostnameStatus, {
+ name: 'UnsubscribeHostnameStatus',
+});
+
@ObjectType('EmailingDomain')
export class EmailingDomainDTO {
@Field(() => UUIDScalarType)
@@ -25,6 +35,12 @@ export class EmailingDomainDTO {
@Field(() => EmailingDomainStatus)
status: EmailingDomainStatus;
+ @Field(() => EmailingDomainTenantStatus)
+ tenantStatus: EmailingDomainTenantStatus;
+
+ @Field(() => UnsubscribeHostnameStatus, { nullable: true })
+ unsubscribeHostnameStatus: UnsubscribeHostnameStatus | null;
+
@Field(() => [VerificationRecordDTO], { nullable: true })
verificationRecords: VerificationRecordDTO[] | null;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/send-email-via-domain.input.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/send-email-via-domain.input.ts
index 17033084dea..ea4d1b7c90c 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/send-email-via-domain.input.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/send-email-via-domain.input.ts
@@ -1,6 +1,7 @@
import { Field, InputType } from '@nestjs/graphql';
import {
+ ArrayMaxSize,
ArrayMinSize,
IsArray,
IsEmail,
@@ -9,6 +10,8 @@ import {
MinLength,
} from 'class-validator';
+const MAX_RECIPIENTS = 10;
+
@InputType()
export class SendEmailViaDomainInput {
@Field(() => String)
@@ -18,18 +21,21 @@ export class SendEmailViaDomainInput {
@Field(() => [String])
@IsArray()
@ArrayMinSize(1)
+ @ArrayMaxSize(MAX_RECIPIENTS)
@IsEmail({}, { each: true })
to: string[];
@Field(() => [String], { nullable: true })
@IsOptional()
@IsArray()
+ @ArrayMaxSize(MAX_RECIPIENTS)
@IsEmail({}, { each: true })
cc?: string[];
@Field(() => [String], { nullable: true })
@IsOptional()
@IsArray()
+ @ArrayMaxSize(MAX_RECIPIENTS)
@IsEmail({}, { each: true })
bcc?: string[];
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/send-message-campaign-output.dto.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/send-message-campaign-output.dto.ts
index 2a5473f8611..ebd28ed49fa 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/send-message-campaign-output.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/send-message-campaign-output.dto.ts
@@ -1,6 +1,6 @@
import { Field, Int, ObjectType } from '@nestjs/graphql';
-import { CampaignSkippedRecipientsDTO } from 'src/engine/core-modules/emailing-domain/dtos/campaign-skipped-recipients.dto';
+import { CampaignAudiencePreviewDTO } from 'src/engine/core-modules/emailing-domain/dtos/campaign-audience-preview.dto';
@ObjectType()
export class SendMessageCampaignOutputDTO {
@@ -10,6 +10,6 @@ export class SendMessageCampaignOutputDTO {
@Field(() => Int)
queuedCount: number;
- @Field(() => CampaignSkippedRecipientsDTO)
- skipped: CampaignSkippedRecipientsDTO;
+ @Field(() => CampaignAudiencePreviewDTO)
+ audience: CampaignAudiencePreviewDTO;
}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception.ts
index 9bf845d3c16..27a929bf1d2 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception.ts
@@ -14,7 +14,6 @@ export enum EmailingDomainExceptionCode {
MESSAGE_CAMPAIGN_NOT_SENDABLE = 'MESSAGE_CAMPAIGN_NOT_SENDABLE',
MESSAGE_CAMPAIGN_INSUFFICIENT_CREDITS = 'MESSAGE_CAMPAIGN_INSUFFICIENT_CREDITS',
MESSAGE_CAMPAIGN_NOT_CANCELABLE = 'MESSAGE_CAMPAIGN_NOT_CANCELABLE',
- MESSAGE_CAMPAIGN_SENDING_REPUTATION_TOO_LOW = 'MESSAGE_CAMPAIGN_SENDING_REPUTATION_TOO_LOW',
}
const getEmailingDomainExceptionUserFriendlyMessage = (
@@ -39,8 +38,6 @@ const getEmailingDomainExceptionUserFriendlyMessage = (
return msg`This campaign cannot be sent. It may be missing a sender, subject or recipient list, or it was already sent.`;
case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_CANCELABLE:
return msg`Only a campaign that is currently sending can be canceled.`;
- case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_SENDING_REPUTATION_TOO_LOW:
- return msg`Too many of your recent emails bounced or were marked as spam. Sending is paused so your domain keeps its reputation. Clean up your recipient lists before sending again.`;
default:
assertUnreachable(code);
}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/filters/emailing-domain-graphql-api-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/filters/emailing-domain-graphql-api-exception.filter.ts
index 512430876e8..800cf3682a5 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/filters/emailing-domain-graphql-api-exception.filter.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/filters/emailing-domain-graphql-api-exception.filter.ts
@@ -22,7 +22,6 @@ export class EmailingDomainGraphqlApiExceptionFilter implements ExceptionFilter
case EmailingDomainExceptionCode.MESSAGE_SUPPRESSION_NOT_FOUND:
throw new NotFoundError(exception);
case EmailingDomainExceptionCode.MESSAGE_SUPPRESSION_NOT_REMOVABLE:
- case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_SENDING_REPUTATION_TOO_LOW:
throw new ForbiddenError(exception);
case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_FOUND:
throw new NotFoundError(exception);
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/services/emailing-domain-tenant-status.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/services/emailing-domain-tenant-status.service.ts
index 6cd09e9c31b..6d862ff3222 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/services/emailing-domain-tenant-status.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/services/emailing-domain-tenant-status.service.ts
@@ -22,9 +22,7 @@ export class EmailingDomainTenantStatusService {
): Promise<void> {
const { affected } = await this.emailingDomainRepository.update(
workspaceId,
- {
- tenantStatus: Not(EmailingDomainTenantStatus.PERMANENTLY_SUSPENDED),
- },
+ { tenantStatus: Not(EmailingDomainTenantStatus.SANDBOX) },
{ tenantStatus },
);
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/services/unsubscribe-content.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/services/unsubscribe-content.service.ts
index 72375808c4f..4b3b3500555 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/services/unsubscribe-content.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/services/unsubscribe-content.service.ts
@@ -2,7 +2,12 @@ import { Injectable } from '@nestjs/common';
import { isNonEmptyString } from '@sniptt/guards';
+import {
+ EmailingDomainDriverException,
+ EmailingDomainDriverExceptionCode,
+} from 'src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception';
import { type EmailingDomainSendEmailInput } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-email-input.type';
+import { getSoleEnvelopeRecipient } from 'src/engine/core-modules/emailing-domain/utils/get-sole-envelope-recipient.util';
import { UnsubscribeTokenService } from 'src/engine/core-modules/emailing-domain/services/unsubscribe-token.service';
import { buildUnsubscribeHeaders } from 'src/engine/core-modules/emailing-domain/utils/build-unsubscribe-headers.util';
import { appendHtmlFooter } from 'src/engine/core-modules/emailing-domain/utils/append-html-footer.util';
@@ -20,16 +25,29 @@ export class UnsubscribeContentService {
email: EmailingDomainSendEmailInput,
unsubscribeBaseUrl: string | null,
): EmailingDomainSendEmailInput {
- if (!isNonEmptyString(unsubscribeBaseUrl)) {
+ if (email.sendKind === 'TRANSACTIONAL') {
return email;
}
+ if (!isNonEmptyString(unsubscribeBaseUrl)) {
+ throw new EmailingDomainDriverException(
+ 'A marketing email cannot be sent before the unsubscribe domain is active, because it would ship with no way to unsubscribe',
+ EmailingDomainDriverExceptionCode.UNSUBSCRIBE_NOT_READY,
+ );
+ }
+
+ const soleRecipient = getSoleEnvelopeRecipient(email);
+
+ if (soleRecipient === null) {
+ throw new EmailingDomainDriverException(
+ 'A marketing email must have exactly one envelope recipient so the unsubscribe token identifies who is unsubscribing',
+ EmailingDomainDriverExceptionCode.UNSUBSCRIBE_MULTIPLE_RECIPIENTS,
+ );
+ }
+
const token = this.unsubscribeTokenService.sign({
workspaceId: email.workspaceId,
- emailAddress: email.to[0],
- ...(isNonEmptyString(email.unsubscribeTopicId)
- ? { unsubscribeTopicId: email.unsubscribeTopicId }
- : {}),
+ emailAddress: soleRecipient,
});
const webUrl = buildUnsubscribeWebUrl({
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/services/unsubscribe-token.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/services/unsubscribe-token.service.ts
index 6660c87cdf9..8579ab203df 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/services/unsubscribe-token.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/services/unsubscribe-token.service.ts
@@ -1,9 +1,17 @@
import { Injectable } from '@nestjs/common';
+import { parseJson } from 'twenty-shared/utils';
+
import { type EncryptedString } from 'src/engine/core-modules/secret-encryption/branded-strings/encrypted-string.type';
import { type PlaintextString } from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';
+import { isEncryptedString } from 'src/engine/core-modules/secret-encryption/branded-strings/is-encrypted-string.util';
import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
import { type UnsubscribeTokenPayload } from 'src/engine/core-modules/emailing-domain/types/unsubscribe-token-payload.type';
+import { type UnsubscribeTokenVerification } from 'src/engine/core-modules/emailing-domain/types/unsubscribe-token-verification.type';
+import { isUnsubscribeTokenExpired } from 'src/engine/core-modules/emailing-domain/utils/is-unsubscribe-token-expired.util';
+import { unsubscribeTokenPayloadSchema } from 'src/engine/core-modules/emailing-domain/zod-schemas/unsubscribe-token-payload.zod-schema';
+
+const WORKSPACE_ID_SEPARATOR = '.';
@Injectable()
export class UnsubscribeTokenService {
@@ -17,37 +25,72 @@ export class UnsubscribeTokenService {
issuedAt: Date.now(),
};
+ const envelope = this.secretEncryptionService.encryptVersioned(
+ JSON.stringify(stampedPayload) as PlaintextString,
+ { workspaceId: payload.workspaceId },
+ );
+
return Buffer.from(
- this.secretEncryptionService.encryptVersioned(
- JSON.stringify(stampedPayload) as PlaintextString,
- ),
+ `${payload.workspaceId}${WORKSPACE_ID_SEPARATOR}${envelope}`,
).toString('base64url');
}
- verify(token: string): UnsubscribeTokenPayload | null {
+ verify(token: string): UnsubscribeTokenVerification | null {
+ const decodedToken = Buffer.from(token, 'base64url').toString('utf8');
+ const separatorIndex = decodedToken.indexOf(WORKSPACE_ID_SEPARATOR);
+
+ if (separatorIndex === -1) {
+ return null;
+ }
+
+ const workspaceId = decodedToken.slice(0, separatorIndex);
+ const envelope = decodedToken.slice(separatorIndex + 1);
+
+ if (!isEncryptedString(envelope)) {
+ return null;
+ }
+
+ const payload = this.decryptPayload({ envelope, workspaceId });
+
+ if (payload === null) {
+ return null;
+ }
+
+ return {
+ payload,
+ isExpired: isUnsubscribeTokenExpired({
+ issuedAt: payload.issuedAt,
+ now: Date.now(),
+ }),
+ };
+ }
+
+ private decryptPayload({
+ envelope,
+ workspaceId,
+ }: {
+ envelope: EncryptedString;
+ workspaceId: string;
+ }): UnsubscribeTokenPayload | null {
try {
const decrypted = this.secretEncryptionService.decryptVersionedOrThrow(
- Buffer.from(token, 'base64url').toString('utf8') as EncryptedString,
+ envelope,
+ { workspaceId },
+ );
+
+ const parsedPayload = unsubscribeTokenPayloadSchema.safeParse(
+ parseJson<unknown>(decrypted),
);
- const decoded = JSON.parse(decrypted);
+ if (!parsedPayload.success) {
+ return null;
+ }
- if (
- typeof decoded?.workspaceId !== 'string' ||
- typeof decoded?.emailAddress !== 'string'
- ) {
+ if (parsedPayload.data.workspaceId !== workspaceId) {
return null;
}
- return {
- workspaceId: decoded.workspaceId,
- emailAddress: decoded.emailAddress,
- issuedAt: typeof decoded?.issuedAt === 'number' ? decoded.issuedAt : 0,
- ...(typeof decoded?.unsubscribeTopicId === 'string'
- ? { unsubscribeTopicId: decoded.unsubscribeTopicId }
- : {}),
- ...(decoded?.preview === true ? { preview: true } : {}),
- };
+ return parsedPayload.data;
} catch {
return null;
}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-audience-resolution.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-audience-resolution.type.ts
new file mode 100644
index 00000000000..60f02a6ad29
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-audience-resolution.type.ts
@@ -0,0 +1,15 @@
+import { type CampaignRecipient } from 'src/engine/core-modules/emailing-domain/types/campaign-recipient.type';
+
+export type CampaignAudienceResolution = {
+ sendableRecipients: CampaignRecipient[];
+ audience: {
+ totalMembers: number;
+ withoutEmail: number;
+ duplicateEmails: number;
+ overCap: number;
+ hardSuppressed: number;
+ globallyUnsubscribed: number;
+ topicUnsubscribed: number;
+ sendable: number;
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-count-group.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-count-group.type.ts
index f007314bf5a..01f42444fe1 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-count-group.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-count-group.type.ts
@@ -6,4 +6,5 @@ export type CampaignCountGroup = {
deliveredCount: string;
bouncedCount: string;
complainedCount: string;
+ providerFailedCount: string;
};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-skipped-breakdown.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-skipped-breakdown.type.ts
index 7c8290e34d8..c460b926bbc 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-skipped-breakdown.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-skipped-breakdown.type.ts
@@ -1,5 +1,4 @@
export type CampaignSkippedBreakdown = {
noEmail: number;
deduped: number;
- overCap: number;
};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/materialize-campaign-chunk-job-data.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/materialize-campaign-chunk-job-data.type.ts
index 8cb98427a8c..48a65b7371b 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/materialize-campaign-chunk-job-data.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/materialize-campaign-chunk-job-data.type.ts
@@ -5,6 +5,7 @@ export type MaterializeCampaignChunkJobData = {
campaignId: string;
messageChannelId: string;
emailingDomainId: string;
+ userWorkspaceId: string;
// Stamped once by the planning job so every chunk shares one receivedAt,
// the way a single looping job used to.
receivedAtIso: string;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/materialize-campaign-job-data.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/materialize-campaign-job-data.type.ts
index 74517b2942a..6d0a76957b1 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/materialize-campaign-job-data.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/materialize-campaign-job-data.type.ts
@@ -6,4 +6,5 @@ export type MaterializeCampaignJobData = {
messageChannelId: string;
emailingDomainId: string;
recipients: CampaignRecipient[];
+ userWorkspaceId: string;
};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/reconcile-workspace-campaign-stats-job-data.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/reconcile-workspace-campaign-stats-job-data.type.ts
new file mode 100644
index 00000000000..2ea7018e559
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/reconcile-workspace-campaign-stats-job-data.type.ts
@@ -0,0 +1,3 @@
+export type ReconcileWorkspaceCampaignStatsJobData = {
+ workspaceId: string;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/send-campaign-email-job-data.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/send-campaign-email-job-data.type.ts
index 56283acf10c..5f46a7dd85a 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/send-campaign-email-job-data.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/send-campaign-email-job-data.type.ts
@@ -5,4 +5,6 @@ export type SendCampaignEmailJobData = {
personId: string;
recipientEmail: string;
emailingDomainId: string;
+ userWorkspaceId: string;
+ rateLimitedAttemptCount?: number;
};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-token-payload.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-token-payload.type.ts
index 9dd4c009d85..1467df702ac 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-token-payload.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-token-payload.type.ts
@@ -1,7 +1,6 @@
export type UnsubscribeTokenPayload = {
workspaceId: string;
emailAddress: string;
- unsubscribeTopicId?: string;
- preview?: boolean;
+ preview?: true;
issuedAt: number;
};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-token-verification.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-token-verification.type.ts
new file mode 100644
index 00000000000..3100998dfa1
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-token-verification.type.ts
@@ -0,0 +1,6 @@
+import { type UnsubscribeTokenPayload } from 'src/engine/core-modules/emailing-domain/types/unsubscribe-token-payload.type';
+
+export type UnsubscribeTokenVerification = {
+ payload: UnsubscribeTokenPayload;
+ isExpired: boolean;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/build-campaign-delivery-outcome-update.util.spec.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/build-campaign-delivery-outcome-update.util.spec.ts
new file mode 100644
index 00000000000..8832e243248
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/build-campaign-delivery-outcome-update.util.spec.ts
@@ -0,0 +1,41 @@
+import { CAMPAIGN_PROVIDER_OUTCOME } from 'src/engine/core-modules/emailing-domain/constants/campaign-provider-outcome.constant';
+import { buildCampaignDeliveryOutcomeUpdate } from 'src/engine/core-modules/emailing-domain/utils/build-campaign-delivery-outcome-update.util';
+
+const occurredAt = new Date('2026-01-01T00:00:00Z');
+
+describe('buildCampaignDeliveryOutcomeUpdate', () => {
+ it.each([
+ [CAMPAIGN_PROVIDER_OUTCOME.DELIVERED, 'deliveredAt'],
+ [CAMPAIGN_PROVIDER_OUTCOME.BOUNCED, 'bouncedAt'],
+ [CAMPAIGN_PROVIDER_OUTCOME.COMPLAINED, 'complainedAt'],
+ [CAMPAIGN_PROVIDER_OUTCOME.REJECTED, 'rejectedAt'],
+ [CAMPAIGN_PROVIDER_OUTCOME.RENDERING_FAILED, 'renderingFailedAt'],
+ ] as const)('stamps %s on its own column', (outcome, column) => {
+ expect(buildCampaignDeliveryOutcomeUpdate({ outcome, occurredAt })).toEqual(
+ {
+ [column]: occurredAt,
+ },
+ );
+ });
+
+ it('leaves the row alone for a soft bounce, which the provider will retry itself', () => {
+ expect(
+ buildCampaignDeliveryOutcomeUpdate({
+ outcome: CAMPAIGN_PROVIDER_OUTCOME.SOFT_BOUNCED,
+ occurredAt,
+ }),
+ ).toEqual({});
+ });
+
+ it('never writes the state or reason the send pipeline owns', () => {
+ const updates = Object.values(CAMPAIGN_PROVIDER_OUTCOME).map((outcome) =>
+ buildCampaignDeliveryOutcomeUpdate({ outcome, occurredAt }),
+ );
+
+ for (const update of updates) {
+ expect(update).not.toHaveProperty('state');
+ expect(update).not.toHaveProperty('skipReason');
+ expect(update).not.toHaveProperty('failureReason');
+ }
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/compute-campaign-counts.util.spec.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/compute-campaign-counts.util.spec.ts
index 45c73f159e8..47b2e6dfa1b 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/compute-campaign-counts.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/compute-campaign-counts.util.spec.ts
@@ -10,6 +10,7 @@ const buildGroup = (
deliveredCount: '0',
bouncedCount: '0',
complainedCount: '0',
+ providerFailedCount: '0',
...overrides,
});
@@ -83,6 +84,29 @@ describe('computeCampaignCounts', () => {
expect(counts.sentCount).toBe(600);
});
+ it('counts a rejected send as failed while still counting it as sent', () => {
+ const counts = computeCampaignCounts({
+ groups: [buildGroup({ total: '10', providerFailedCount: '2' })],
+ });
+
+ expect(counts.sentCount).toBe(10);
+ expect(counts.failedCount).toBe(2);
+ });
+
+ it('counts a failed row once even when the provider also refused it', () => {
+ const counts = computeCampaignCounts({
+ groups: [
+ buildGroup({
+ state: CAMPAIGN_DELIVERY_STATE.FAILED,
+ total: '3',
+ providerFailedCount: '3',
+ }),
+ ],
+ });
+
+ expect(counts.failedCount).toBe(3);
+ });
+
it('reads an empty campaign as all zeroes', () => {
expect(computeCampaignCounts({ groups: [] })).toEqual({
totalCount: 0,
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/get-sole-envelope-recipient.util.spec.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/get-sole-envelope-recipient.util.spec.ts
new file mode 100644
index 00000000000..a0d7db6929e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/get-sole-envelope-recipient.util.spec.ts
@@ -0,0 +1,39 @@
+import { getSoleEnvelopeRecipient } from 'src/engine/core-modules/emailing-domain/utils/get-sole-envelope-recipient.util';
+
+describe('getSoleEnvelopeRecipient', () => {
+ it('should return the single primary recipient', () => {
+ expect(getSoleEnvelopeRecipient({ to: ['[email protected]'] })).toBe(
+ );
+ });
+
+ it('should return null when the envelope carries several primary recipients', () => {
+ expect(
+ getSoleEnvelopeRecipient({
+ }),
+ ).toBeNull();
+ });
+
+ it('should return null when a copied recipient would receive the same body', () => {
+ expect(
+ getSoleEnvelopeRecipient({
+ }),
+ ).toBeNull();
+ });
+
+ it('should count blind-copied recipients', () => {
+ expect(
+ getSoleEnvelopeRecipient({
+ bcc: ['[email protected]'],
+ }),
+ ).toBeNull();
+ });
+
+ it('should return null when there is no recipient at all', () => {
+ expect(getSoleEnvelopeRecipient({ to: [] })).toBeNull();
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/is-suppression-blocking-send.util.spec.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/is-suppression-blocking-send.util.spec.ts
new file mode 100644
index 00000000000..4af70f10f41
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/is-suppression-blocking-send.util.spec.ts
@@ -0,0 +1,99 @@
+import { MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
+import { isSuppressionBlockingSend } from 'src/engine/core-modules/emailing-domain/utils/is-suppression-blocking-send.util';
+
+const NEWSLETTER_TOPIC_ID = '11111111-1111-4111-8111-111111111111';
+const PRODUCT_TOPIC_ID = '22222222-2222-4222-8222-222222222222';
+
+describe('isSuppressionBlockingSend', () => {
+ describe.each([
+ MessageSuppressionReason.BOUNCE,
+ MessageSuppressionReason.COMPLAINT,
+ ])('hard suppression (%s)', (reason) => {
+ it('should block a marketing send', () => {
+ expect(
+ isSuppressionBlockingSend({
+ sendKind: 'MARKETING',
+ suppression: { reason, unsubscribeTopicId: null },
+ unsubscribeTopicId: NEWSLETTER_TOPIC_ID,
+ }),
+ ).toBe(true);
+ });
+
+ it('should block a transactional send, because a dead or hostile address is dead for all mail', () => {
+ expect(
+ isSuppressionBlockingSend({
+ sendKind: 'TRANSACTIONAL',
+ suppression: { reason, unsubscribeTopicId: null },
+ }),
+ ).toBe(true);
+ });
+ });
+
+ describe('unsubscribe from all', () => {
+ const suppression = {
+ reason: MessageSuppressionReason.UNSUBSCRIBE,
+ unsubscribeTopicId: null,
+ };
+
+ it('should block a marketing send carrying no topic', () => {
+ expect(
+ isSuppressionBlockingSend({ sendKind: 'MARKETING', suppression }),
+ ).toBe(true);
+ });
+
+ it('should block a marketing send carrying any topic', () => {
+ expect(
+ isSuppressionBlockingSend({
+ sendKind: 'MARKETING',
+ suppression,
+ unsubscribeTopicId: NEWSLETTER_TOPIC_ID,
+ }),
+ ).toBe(true);
+ });
+
+ it('should let a transactional reply through', () => {
+ expect(
+ isSuppressionBlockingSend({ sendKind: 'TRANSACTIONAL', suppression }),
+ ).toBe(false);
+ });
+ });
+
+ describe('topic opt-out', () => {
+ const suppression = {
+ reason: MessageSuppressionReason.UNSUBSCRIBE,
+ unsubscribeTopicId: NEWSLETTER_TOPIC_ID,
+ };
+
+ it('should block a marketing send on the same topic', () => {
+ expect(
+ isSuppressionBlockingSend({
+ sendKind: 'MARKETING',
+ suppression,
+ unsubscribeTopicId: NEWSLETTER_TOPIC_ID,
+ }),
+ ).toBe(true);
+ });
+
+ it('should let a marketing send on another topic through', () => {
+ expect(
+ isSuppressionBlockingSend({
+ sendKind: 'MARKETING',
+ suppression,
+ unsubscribeTopicId: PRODUCT_TOPIC_ID,
+ }),
+ ).toBe(false);
+ });
+
+ it('should let a marketing send carrying no topic through', () => {
+ expect(
+ isSuppressionBlockingSend({ sendKind: 'MARKETING', suppression }),
+ ).toBe(false);
+ });
+
+ it('should let a transactional reply through', () => {
+ expect(
+ isSuppressionBlockingSend({ sendKind: 'TRANSACTIONAL', suppression }),
+ ).toBe(false);
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/is-unsubscribe-token-expired.util.spec.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/is-unsubscribe-token-expired.util.spec.ts
new file mode 100644
index 00000000000..0dcec69af14
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/is-unsubscribe-token-expired.util.spec.ts
@@ -0,0 +1,42 @@
+import { UNSUBSCRIBE_TOKEN_MAX_AGE_MS } from 'src/engine/core-modules/emailing-domain/constants/unsubscribe-token-max-age-ms.constant';
+import { isUnsubscribeTokenExpired } from 'src/engine/core-modules/emailing-domain/utils/is-unsubscribe-token-expired.util';
+
+describe('isUnsubscribeTokenExpired', () => {
+ const now = Date.UTC(2026, 0, 1);
+
+ it('should not expire a token issued now', () => {
+ expect(isUnsubscribeTokenExpired({ issuedAt: now, now })).toBe(false);
+ });
+
+ it('should not expire a token issued exactly at the maximum age', () => {
+ expect(
+ isUnsubscribeTokenExpired({
+ issuedAt: now - UNSUBSCRIBE_TOKEN_MAX_AGE_MS,
+ now,
+ }),
+ ).toBe(false);
+ });
+
+ it('should expire a token issued one millisecond past the maximum age', () => {
+ expect(
+ isUnsubscribeTokenExpired({
+ issuedAt: now - UNSUBSCRIBE_TOKEN_MAX_AGE_MS - 1,
+ now,
+ }),
+ ).toBe(true);
+ });
+
+ it('should keep an unsubscribe link alive a year after it was sent', () => {
+ const oneYearInMilliseconds = 365 * 24 * 60 * 60 * 1000;
+
+ expect(
+ isUnsubscribeTokenExpired({ issuedAt: now - oneYearInMilliseconds, now }),
+ ).toBe(false);
+ });
+
+ it('should treat a token stamped in the future as fresh', () => {
+ expect(isUnsubscribeTokenExpired({ issuedAt: now + 60_000, now })).toBe(
+ false,
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/normalize-campaign-recipients.util.spec.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/normalize-campaign-recipients.util.spec.ts
index 581ecfcda4e..bacb2429149 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/normalize-campaign-recipients.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/normalize-campaign-recipients.util.spec.ts
@@ -9,10 +9,10 @@ describe('normalizeCampaignRecipients', () => {
{ personId: 'p3', email: ' ' },
];
- const { recipients, skipped } = normalizeCampaignRecipients(raw, 100);
+ const { recipients, skipped } = normalizeCampaignRecipients(raw);
expect(recipients).toEqual([{ personId: 'p1', email: '[email protected]' }]);
- expect(skipped).toEqual({ noEmail: 2, deduped: 0, overCap: 0 });
+ expect(skipped).toEqual({ noEmail: 2, deduped: 0 });
});
it('dedupes by lowercased email, keeping the first occurrence', () => {
@@ -21,29 +21,16 @@ describe('normalizeCampaignRecipients', () => {
{ personId: 'p2', email: '[email protected]' },
];
- const { recipients, skipped } = normalizeCampaignRecipients(raw, 100);
+ const { recipients, skipped } = normalizeCampaignRecipients(raw);
expect(recipients).toEqual([{ personId: 'p1', email: '[email protected]' }]);
expect(skipped.deduped).toBe(1);
});
- it('caps the recipient count and reports the overflow', () => {
- const raw: RawCampaignRecipient[] = [
- { personId: 'p1', email: '[email protected]' },
- { personId: 'p2', email: '[email protected]' },
- { personId: 'p3', email: '[email protected]' },
- ];
-
- const { recipients, skipped } = normalizeCampaignRecipients(raw, 2);
-
- expect(recipients).toHaveLength(2);
- expect(skipped.overCap).toBe(1);
- });
-
it('returns an empty result for no input', () => {
- expect(normalizeCampaignRecipients([], 100)).toEqual({
+ expect(normalizeCampaignRecipients([])).toEqual({
recipients: [],
- skipped: { noEmail: 0, deduped: 0, overCap: 0 },
+ skipped: { noEmail: 0, deduped: 0 },
});
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/resolve-campaign-audience.util.spec.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/resolve-campaign-audience.util.spec.ts
new file mode 100644
index 00000000000..10a672c5ae2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/resolve-campaign-audience.util.spec.ts
@@ -0,0 +1,143 @@
+import { type RawCampaignRecipient } from 'src/engine/core-modules/emailing-domain/types/raw-campaign-recipient.type';
+import { resolveCampaignAudience } from 'src/engine/core-modules/emailing-domain/utils/resolve-campaign-audience.util';
+
+const buildRawRecipients = (
+ emails: (string | null)[],
+): RawCampaignRecipient[] =>
+ emails.map((email, index) => ({ personId: `person-${index}`, email }));
+
+describe('resolveCampaignAudience', () => {
+ it('should report the sendable count as the number of recipients it returns', () => {
+ const { sendableRecipients, audience } = resolveCampaignAudience({
+ rawRecipients: buildRawRecipients([
+ null,
+ ]),
+ totalMemberCount: 5,
+ maxRecipients: 100,
+ hardSuppressedEmails: new Set(),
+ globallySuppressedEmails: new Set(['[email protected]']),
+ topicSuppressedEmails: new Set(['[email protected]']),
+ });
+
+ expect(sendableRecipients).toEqual([
+ { email: '[email protected]', personId: 'person-0' },
+ ]);
+ expect(audience).toEqual({
+ totalMembers: 5,
+ withoutEmail: 1,
+ duplicateEmails: 1,
+ overCap: 0,
+ hardSuppressed: 0,
+ globallyUnsubscribed: 1,
+ topicUnsubscribed: 1,
+ sendable: 1,
+ });
+ });
+
+ it('should surface how many recipients were dropped for exceeding the cap', () => {
+ const { sendableRecipients, audience } = resolveCampaignAudience({
+ rawRecipients: buildRawRecipients([
+ ]),
+ totalMemberCount: 3,
+ maxRecipients: 2,
+ hardSuppressedEmails: new Set(),
+ globallySuppressedEmails: new Set(),
+ topicSuppressedEmails: new Set(),
+ });
+
+ expect(audience.overCap).toBe(1);
+ expect(audience.sendable).toBe(2);
+ expect(sendableRecipients).toHaveLength(2);
+ });
+
+ it('should fill the cap with eligible recipients instead of letting suppressed ones consume slots', () => {
+ const { sendableRecipients, audience } = resolveCampaignAudience({
+ rawRecipients: buildRawRecipients([
+ ]),
+ totalMemberCount: 4,
+ maxRecipients: 2,
+ hardSuppressedEmails: new Set(['[email protected]']),
+ globallySuppressedEmails: new Set(),
+ topicSuppressedEmails: new Set(),
+ });
+
+ expect(sendableRecipients.map((recipient) => recipient.email)).toEqual([
+ ]);
+ expect(audience.overCap).toBe(1);
+ });
+
+ it('should report a bounced recipient as hard suppressed rather than unsubscribed', () => {
+ const { audience } = resolveCampaignAudience({
+ rawRecipients: buildRawRecipients([
+ ]),
+ totalMemberCount: 2,
+ maxRecipients: 100,
+ hardSuppressedEmails: new Set(['[email protected]']),
+ globallySuppressedEmails: new Set(['[email protected]']),
+ topicSuppressedEmails: new Set(),
+ });
+
+ expect(audience.hardSuppressed).toBe(1);
+ expect(audience.globallyUnsubscribed).toBe(1);
+ expect(audience.sendable).toBe(0);
+ });
+
+ it('should count a globally suppressed recipient once even when the topic also suppresses it', () => {
+ const { audience } = resolveCampaignAudience({
+ rawRecipients: buildRawRecipients(['[email protected]']),
+ totalMemberCount: 1,
+ maxRecipients: 100,
+ hardSuppressedEmails: new Set(),
+ globallySuppressedEmails: new Set(['[email protected]']),
+ topicSuppressedEmails: new Set(['[email protected]']),
+ });
+
+ expect(audience.globallyUnsubscribed).toBe(1);
+ expect(audience.topicUnsubscribed).toBe(0);
+ expect(audience.sendable).toBe(0);
+ });
+
+ it('should count list members the role cannot read as skipped rather than dropping them', () => {
+ const { audience } = resolveCampaignAudience({
+ rawRecipients: buildRawRecipients(['[email protected]']),
+ totalMemberCount: 4,
+ maxRecipients: 100,
+ hardSuppressedEmails: new Set(),
+ globallySuppressedEmails: new Set(),
+ topicSuppressedEmails: new Set(),
+ });
+
+ expect(audience.totalMembers).toBe(4);
+ expect(audience.sendable).toBe(1);
+ });
+
+ it('should return an empty audience when the list has no members', () => {
+ const { sendableRecipients, audience } = resolveCampaignAudience({
+ rawRecipients: [],
+ totalMemberCount: 0,
+ maxRecipients: 100,
+ hardSuppressedEmails: new Set(),
+ globallySuppressedEmails: new Set(),
+ topicSuppressedEmails: new Set(),
+ });
+
+ expect(sendableRecipients).toEqual([]);
+ expect(audience.totalMembers).toBe(0);
+ expect(audience.sendable).toBe(0);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-campaign-delivery-outcome-update.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-campaign-delivery-outcome-update.util.ts
new file mode 100644
index 00000000000..2344d72cc0c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-campaign-delivery-outcome-update.util.ts
@@ -0,0 +1,41 @@
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import { type CampaignDeliveryEntity } from 'src/engine/core-modules/emailing-domain/campaign-delivery.entity';
+import { CAMPAIGN_PROVIDER_OUTCOME } from 'src/engine/core-modules/emailing-domain/constants/campaign-provider-outcome.constant';
+import { type CampaignProviderOutcome } from 'src/engine/core-modules/emailing-domain/types/campaign-provider-outcome.type';
+
+type CampaignDeliveryOutcomeUpdate = Partial<
+ Pick<
+ CampaignDeliveryEntity,
+ | 'deliveredAt'
+ | 'bouncedAt'
+ | 'complainedAt'
+ | 'rejectedAt'
+ | 'renderingFailedAt'
+ >
+>;
+
+export const buildCampaignDeliveryOutcomeUpdate = ({
+ outcome,
+ occurredAt,
+}: {
+ outcome: CampaignProviderOutcome;
+ occurredAt: Date;
+}): CampaignDeliveryOutcomeUpdate => {
+ switch (outcome) {
+ case CAMPAIGN_PROVIDER_OUTCOME.DELIVERED:
+ return { deliveredAt: occurredAt };
+ case CAMPAIGN_PROVIDER_OUTCOME.BOUNCED:
+ return { bouncedAt: occurredAt };
+ case CAMPAIGN_PROVIDER_OUTCOME.COMPLAINED:
+ return { complainedAt: occurredAt };
+ case CAMPAIGN_PROVIDER_OUTCOME.REJECTED:
+ return { rejectedAt: occurredAt };
+ case CAMPAIGN_PROVIDER_OUTCOME.RENDERING_FAILED:
+ return { renderingFailedAt: occurredAt };
+ case CAMPAIGN_PROVIDER_OUTCOME.SOFT_BOUNCED:
+ return {};
+ default:
+ return assertUnreachable(outcome);
+ }
+};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/compute-campaign-counts.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/compute-campaign-counts.util.ts
index 7163f223a9c..6a38b7824da 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/compute-campaign-counts.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/compute-campaign-counts.util.ts
@@ -14,7 +14,9 @@ const EMPTY_CAMPAIGN_COUNTS: CampaignCounts = {
};
const countFailedInGroup = (group: CampaignCountGroup): number =>
- group.state === CAMPAIGN_DELIVERY_STATE.FAILED ? Number(group.total) : 0;
+ group.state === CAMPAIGN_DELIVERY_STATE.FAILED
+ ? Number(group.total)
+ : Number(group.providerFailedCount);
export const computeCampaignCounts = ({
groups,
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/count-delivered-recipients.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/count-delivered-recipients.util.ts
new file mode 100644
index 00000000000..0becc1a472f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/count-delivered-recipients.util.ts
@@ -0,0 +1,8 @@
+import { type EmailingDomainSendEmailResult } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-email-result.type';
+
+export const countDeliveredRecipients = ({
+ to,
+ cc,
+ bcc,
+}: EmailingDomainSendEmailResult['deliveredRecipients']): number =>
+ to.length + cc.length + bcc.length;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/get-sole-envelope-recipient.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/get-sole-envelope-recipient.util.ts
new file mode 100644
index 00000000000..057bc47a81a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/get-sole-envelope-recipient.util.ts
@@ -0,0 +1,16 @@
+import { type EmailingDomainEmailContent } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-email-content.type';
+
+type GetSoleEnvelopeRecipientArgs = Pick<
+ EmailingDomainEmailContent,
+ 'to' | 'cc' | 'bcc'
+>;
+
+export const getSoleEnvelopeRecipient = ({
+ to,
+ cc,
+ bcc,
+}: GetSoleEnvelopeRecipientArgs): string | null => {
+ const recipients = [...to, ...(cc ?? []), ...(bcc ?? [])];
+
+ return recipients.length === 1 ? recipients[0] : null;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/is-suppression-blocking-send.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/is-suppression-blocking-send.util.ts
new file mode 100644
index 00000000000..c75f0d56851
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/is-suppression-blocking-send.util.ts
@@ -0,0 +1,31 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { HARD_SUPPRESSION_REASONS } from 'src/engine/core-modules/emailing-domain/constants/hard-suppression-reasons.constant';
+import { type EmailingDomainSendKind } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-kind.type';
+import { type MessageSuppressionEntity } from 'src/engine/core-modules/emailing-domain/message-suppression.entity';
+
+type IsSuppressionBlockingSendArgs = {
+ sendKind: EmailingDomainSendKind;
+ suppression: Pick<MessageSuppressionEntity, 'reason' | 'unsubscribeTopicId'>;
+ unsubscribeTopicId?: string;
+};
+
+export const isSuppressionBlockingSend = ({
+ sendKind,
+ suppression,
+ unsubscribeTopicId,
+}: IsSuppressionBlockingSendArgs): boolean => {
+ if (HARD_SUPPRESSION_REASONS.includes(suppression.reason)) {
+ return true;
+ }
+
+ if (sendKind === 'TRANSACTIONAL') {
+ return false;
+ }
+
+ if (!isDefined(suppression.unsubscribeTopicId)) {
+ return true;
+ }
+
+ return suppression.unsubscribeTopicId === unsubscribeTopicId;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/is-unsubscribe-token-expired.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/is-unsubscribe-token-expired.util.ts
new file mode 100644
index 00000000000..16f8e225f2d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/is-unsubscribe-token-expired.util.ts
@@ -0,0 +1,13 @@
+import { UNSUBSCRIBE_TOKEN_MAX_AGE_MS } from 'src/engine/core-modules/emailing-domain/constants/unsubscribe-token-max-age-ms.constant';
+
+type IsUnsubscribeTokenExpiredArgs = {
+ issuedAt: number;
+ now: number;
+ maxAgeMs?: number;
+};
+
+export const isUnsubscribeTokenExpired = ({
+ issuedAt,
+ now,
+ maxAgeMs = UNSUBSCRIBE_TOKEN_MAX_AGE_MS,
+}: IsUnsubscribeTokenExpiredArgs): boolean => now - issuedAt > maxAgeMs;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/normalize-campaign-recipients.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/normalize-campaign-recipients.util.ts
index 580c76c805c..d8977299150 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/normalize-campaign-recipients.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/normalize-campaign-recipients.util.ts
@@ -6,12 +6,10 @@ import { type RawCampaignRecipient } from 'src/engine/core-modules/emailing-doma
export const normalizeCampaignRecipients = (
rawRecipients: RawCampaignRecipient[],
- maxRecipients: number,
): { recipients: CampaignRecipient[]; skipped: CampaignSkippedBreakdown } => {
const skipped: CampaignSkippedBreakdown = {
noEmail: 0,
deduped: 0,
- overCap: 0,
};
const seenEmails = new Set<string>();
const recipients: CampaignRecipient[] = [];
@@ -30,12 +28,6 @@ export const normalizeCampaignRecipients = (
}
seenEmails.add(normalizedEmail);
-
- if (recipients.length >= maxRecipients) {
- skipped.overCap += 1;
- continue;
- }
-
recipients.push({ email: normalizedEmail, personId: candidate.personId });
}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/resolve-campaign-audience.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/resolve-campaign-audience.util.ts
new file mode 100644
index 00000000000..625110e1684
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/resolve-campaign-audience.util.ts
@@ -0,0 +1,64 @@
+import { type CampaignAudienceResolution } from 'src/engine/core-modules/emailing-domain/types/campaign-audience-resolution.type';
+import { type CampaignRecipient } from 'src/engine/core-modules/emailing-domain/types/campaign-recipient.type';
+import { type RawCampaignRecipient } from 'src/engine/core-modules/emailing-domain/types/raw-campaign-recipient.type';
+import { normalizeCampaignRecipients } from 'src/engine/core-modules/emailing-domain/utils/normalize-campaign-recipients.util';
+
+export const resolveCampaignAudience = ({
+ rawRecipients,
+ totalMemberCount,
+ maxRecipients,
+ hardSuppressedEmails,
+ globallySuppressedEmails,
+ topicSuppressedEmails,
+}: {
+ rawRecipients: RawCampaignRecipient[];
+ totalMemberCount: number;
+ maxRecipients: number;
+ hardSuppressedEmails: Set<string>;
+ globallySuppressedEmails: Set<string>;
+ topicSuppressedEmails: Set<string>;
+}): CampaignAudienceResolution => {
+ const { recipients, skipped } = normalizeCampaignRecipients(rawRecipients);
+
+ const sendableRecipients: CampaignRecipient[] = [];
+ const excluded = { hardSuppressed: 0, globally: 0, byTopic: 0 };
+ let overCap = 0;
+
+ for (const recipient of recipients) {
+ if (hardSuppressedEmails.has(recipient.email)) {
+ excluded.hardSuppressed += 1;
+ continue;
+ }
+
+ if (globallySuppressedEmails.has(recipient.email)) {
+ excluded.globally += 1;
+ continue;
+ }
+
+ if (topicSuppressedEmails.has(recipient.email)) {
+ excluded.byTopic += 1;
+ continue;
+ }
+
+ if (sendableRecipients.length >= maxRecipients) {
+ overCap += 1;
+ continue;
+ }
+
+ sendableRecipients.push(recipient);
+ }
+
+ return {
+ sendableRecipients,
+ audience: {
+ totalMembers: totalMemberCount,
+ withoutEmail: skipped.noEmail,
+ duplicateEmails: skipped.deduped,
+ overCap,
+ hardSuppressed: excluded.hardSuppressed,
+ globallyUnsubscribed: excluded.globally,
+ topicUnsubscribed: excluded.byTopic,
+ sendable: sendableRecipients.length,
+ },
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/zod-schemas/unsubscribe-token-payload.zod-schema.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/zod-schemas/unsubscribe-token-payload.zod-schema.ts
new file mode 100644
index 00000000000..905c35cd620
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/zod-schemas/unsubscribe-token-payload.zod-schema.ts
@@ -0,0 +1,8 @@
+import { z } from 'zod';
+
+export const unsubscribeTokenPayloadSchema = z.object({
+ workspaceId: z.string().min(1),
+ emailAddress: z.string().min(1),
+ preview: z.literal(true).optional(),
+ issuedAt: z.number(),
+});
diff --git a/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts b/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts
index 16630933ea3..d70edec35b9 100644
--- a/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts
@@ -26,6 +26,7 @@ import { EmailModule } from 'src/engine/core-modules/email/email.module';
import { EmailingModule } from 'src/modules/emailing/emailing.module';
import { MaterializeCampaignChunkJob } from 'src/modules/emailing/jobs/materialize-campaign-chunk.job';
import { MaterializeCampaignJob } from 'src/modules/emailing/jobs/materialize-campaign.job';
+import { ReconcileWorkspaceCampaignStatsJob } from 'src/modules/emailing/jobs/reconcile-workspace-campaign-stats.job';
import { RefreshCampaignStatsJob } from 'src/modules/emailing/jobs/refresh-campaign-stats.job';
import { SendCampaignEmailJob } from 'src/modules/emailing/jobs/send-campaign-email.job';
import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';
@@ -114,6 +115,7 @@ import { WorkflowModule } from 'src/modules/workflow/workflow.module';
MaterializeCampaignJob,
MaterializeCampaignChunkJob,
RefreshCampaignStatsJob,
+ ReconcileWorkspaceCampaignStatsJob,
UpdateSubscriptionQuantityJob,
HandleWorkspaceMemberDeletedJob,
WorkspaceDeletionApplicationUninstallJob,
diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
index ba0be739a86..b1d74e9282e 100644
--- a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
@@ -1657,6 +1657,24 @@ export class ConfigVariables {
@CastToPositiveNumber()
APPLICATION_API_RATE_LIMITING_LIMIT = 500;
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.RATE_LIMITING,
+ description:
+ 'Time-to-live for outbound email send rate limiting in milliseconds',
+ type: ConfigVariableType.NUMBER,
+ })
+ @CastToPositiveNumber()
+ EMAIL_SEND_RATE_LIMITING_TTL_IN_MS = 10_000;
+
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.RATE_LIMITING,
+ description:
+ 'Maximum number of emails sent across all workspaces in the rate limiting window. Set it below the send rate the email provider publishes for the account, so transactional mail sharing that account keeps headroom during a campaign',
+ type: ConfigVariableType.NUMBER,
+ })
+ @CastToPositiveNumber()
+ EMAIL_SEND_RATE_LIMITING_LIMIT = 100;
+
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.RATE_LIMITING,
description:
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
index 328776c2cfb..50dbf5c98c0 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
@@ -41,5 +41,19 @@ export const USAGE_LIMIT_DEFINITIONS: Record<
[UsageResourceType.APP]: {},
[UsageResourceType.STORAGE]: {},
[UsageResourceType.LOGIC_FUNCTION]: {},
- [UsageResourceType.EMAIL]: {},
+ [UsageResourceType.EMAIL]: {
+ speed: {
+ allowedOperationTypes: [UsageOperationType.EMAIL_SEND],
+ allowedSpenderTypes: ['workspace'],
+ fallbacks: [
+ {
+ spenderType: 'workspace',
+ counterScope: 'crossWorkspace',
+ limitValueConfigVariable: 'EMAIL_SEND_RATE_LIMITING_LIMIT',
+ windowMsConfigVariable: 'EMAIL_SEND_RATE_LIMITING_TTL_IN_MS',
+ isOverridable: false,
+ },
+ ],
+ },
+ },
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-speed-buckets.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-speed-buckets.util.spec.ts
index b18bd2f726d..5cd2ebf377c 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-speed-buckets.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-speed-buckets.util.spec.ts
@@ -50,12 +50,14 @@ const buildRule = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
const buildBuckets = ({
authContext,
rules = [],
+ defaultUsageLimitFallbacks = DEFAULT_USAGE_LIMIT_FALLBACKS,
}: {
authContext: WorkspaceAuthContext;
rules?: FlatUsageLimit[];
+ defaultUsageLimitFallbacks?: DefaultUsageLimitFallback[];
}) =>
buildSpeedBuckets({
- defaultUsageLimitFallbacks: DEFAULT_USAGE_LIMIT_FALLBACKS,
+ defaultUsageLimitFallbacks,
rules,
authContext,
resourceType: UsageResourceType.API,
@@ -133,6 +135,66 @@ describe('buildSpeedBuckets with no rules configured', () => {
});
});
+describe('buildSpeedBuckets for a spender no application identifies', () => {
+ const WORKSPACE_FALLBACKS: DefaultUsageLimitFallback[] = [
+ {
+ spenderType: 'workspace',
+ counterScope: 'crossWorkspace',
+ maxTokens: 14,
+ windowMs: 10_000,
+ isOverridable: true,
+ },
+ ];
+
+ it('meters a system sender against one counter across every workspace', () => {
+ expect(
+ buildBuckets({
+ authContext: systemContext,
+ defaultUsageLimitFallbacks: WORKSPACE_FALLBACKS,
+ }),
+ ).toEqual([
+ expect.objectContaining({
+ key: '{server}:speed:API:API_REQUEST:workspace:-:10',
+ refillPerWindow: 14,
+ spenderType: 'workspace',
+ spenderId: null,
+ }),
+ ]);
+ });
+
+ it('meters a user request against that same counter', () => {
+ const [bucket] = buildBuckets({
+ authContext: userContext,
+ defaultUsageLimitFallbacks: WORKSPACE_FALLBACKS,
+ });
+
+ expect(bucket.key).toBe('{server}:speed:API:API_REQUEST:workspace:-:10');
+ });
+
+ it('still drops an application bucket when no application identifies the caller', () => {
+ const unidentifiedApplicationContext = {
+ type: 'application',
+ workspace,
+ application: { id: 'app-1' },
+ } as WorkspaceAuthContext;
+
+ expect(
+ buildBuckets({
+ authContext: unidentifiedApplicationContext,
+ defaultUsageLimitFallbacks: [
+ {
+ spenderType: 'application',
+ counterScope: 'crossWorkspace',
+ maxTokens: 500,
+ windowMs: 60_000,
+ isOverridable: false,
+ },
+ ],
+ }),
+ ).toEqual([]);
+ });
+});
+
describe('buildSpeedBuckets with rules configured', () => {
it('shares one counter between every api key when the rule names none', () => {
const [bucket] = buildBuckets({
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-fallback-speed-bucket.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-fallback-speed-bucket.util.ts
index 2d5fcef5bcc..325eb50eb03 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-fallback-speed-bucket.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-fallback-speed-bucket.util.ts
@@ -23,13 +23,21 @@ export const buildFallbackSpeedBucket = ({
operationType: UsageOperationType;
}): SpeedBucketRequest | null => {
const isCrossWorkspace = fallback.counterScope === 'crossWorkspace';
+ const isIdentifiedAcrossWorkspaces = spender.spenderType === 'application';
const universalIdentifier = getApplicationUniversalIdentifier(authContext);
- if (isCrossWorkspace && !isDefined(universalIdentifier)) {
+ if (
+ isCrossWorkspace &&
+ isIdentifiedAcrossWorkspaces &&
+ !isDefined(universalIdentifier)
+ ) {
return null;
}
- const spenderId = isCrossWorkspace ? universalIdentifier : null;
+ const spenderId =
+ isCrossWorkspace && isIdentifiedAcrossWorkspaces
+ ? universalIdentifier
+ : null;
return {
key: buildSpeedBucketKey({
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/message-channel-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/message-channel-graphql-api-exception-handler.util.ts
index ac468a847f4..2c8686d58d3 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/message-channel-graphql-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/message-channel-graphql-api-exception-handler.util.ts
@@ -44,7 +44,6 @@ export const messageChannelGraphqlApiExceptionHandler = (error: Error) => {
case EmailingDomainExceptionCode.MESSAGE_SUPPRESSION_NOT_FOUND:
throw new NotFoundError(error);
case EmailingDomainExceptionCode.MESSAGE_SUPPRESSION_NOT_REMOVABLE:
- case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_SENDING_REPUTATION_TOO_LOW:
throw new ForbiddenError(error);
case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_FOUND:
throw new NotFoundError(error);
diff --git a/packages/twenty-server/src/modules/emailing/constants/reconcile-campaign-stats-cron-pattern.constant.ts b/packages/twenty-server/src/modules/emailing/constants/reconcile-campaign-stats-cron-pattern.constant.ts
new file mode 100644
index 00000000000..c1d15c607dd
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/constants/reconcile-campaign-stats-cron-pattern.constant.ts
@@ -0,0 +1 @@
+export const RECONCILE_CAMPAIGN_STATS_CRON_PATTERN = '15 * * * *';
diff --git a/packages/twenty-server/src/modules/emailing/controllers/unsubscribe.controller.ts b/packages/twenty-server/src/modules/emailing/controllers/unsubscribe.controller.ts
index e3e26971120..45bc19dd476 100644
--- a/packages/twenty-server/src/modules/emailing/controllers/unsubscribe.controller.ts
+++ b/packages/twenty-server/src/modules/emailing/controllers/unsubscribe.controller.ts
@@ -1,3 +1,4 @@
+import { isUnsubscribeTokenExpired } from 'src/engine/core-modules/emailing-domain/utils/is-unsubscribe-token-expired.util';
import {
BadRequestException,
Body,
@@ -7,20 +8,23 @@ import {
HttpCode,
Post,
Query,
+ Req,
UseGuards,
} from '@nestjs/common';
import { isNonEmptyString } from '@sniptt/guards';
+import { type Request } from 'express';
import { ApiPath } from 'twenty-shared/types';
import { UnsubscribeTokenService } from 'src/engine/core-modules/emailing-domain/services/unsubscribe-token.service';
-import { MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
-import { MessageSuppressionSource } from 'src/engine/core-modules/emailing-domain/types/message-suppression-source.type';
-import { type UnsubscribeTokenPayload } from 'src/engine/core-modules/emailing-domain/types/unsubscribe-token-payload.type';
+import { type UnsubscribeTokenVerification } from 'src/engine/core-modules/emailing-domain/types/unsubscribe-token-verification.type';
import { buildUnsubscribePreferencesPage } from 'src/engine/core-modules/emailing-domain/utils/build-unsubscribe-preferences-page.util';
import { buildUnsubscribeResultPage } from 'src/engine/core-modules/emailing-domain/utils/build-unsubscribe-result-page.util';
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
import { PublicEndpointGuard } from 'src/engine/guards/public-endpoint.guard';
+import { ThrottlerException } from 'src/engine/core-modules/throttler/throttler.exception';
+import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';
+import { throttlerToRestApiExceptionHandler } from 'src/engine/core-modules/throttler/utils/throttler-to-rest-api-exception-handler.util';
import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';
const UNSUBSCRIBE_TOKEN_FORMAT = /^[A-Za-z0-9_-]{1,1024}$/;
@@ -40,41 +44,83 @@ type UnsubscribeFormBody = {
unsubscribeTopicId?: string | string[];
};
+const RATE_LIMIT = { maxRequests: 120, windowMs: 60_000 };
+const RESUBSCRIBE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
+
@Controller(`${ApiPath.Emailing}/unsubscribe`)
@UseGuards(PublicEndpointGuard, NoPermissionGuard)
export class UnsubscribeController {
constructor(
private readonly unsubscribeTokenService: UnsubscribeTokenService,
private readonly messageSuppressionService: MessageSuppressionService,
+ private readonly throttlerService: ThrottlerService,
) {}
+ private async throttleOrThrow(bucketKey: string): Promise<void> {
+ try {
+ await this.throttlerService.tokenBucketThrottleOrThrow(
+ bucketKey,
+ 1,
+ RATE_LIMIT.maxRequests,
+ RATE_LIMIT.windowMs,
+ );
+ } catch (error) {
+ if (error instanceof ThrottlerException) {
+ throttlerToRestApiExceptionHandler(error);
+ }
+
+ throw error;
+ }
+ }
+
+ private async throttleByRequesterOrThrow(request: Request): Promise<void> {
+ await this.throttleOrThrow(
+ `unsubscribe:requester:${request.ip ?? 'unknown-requester'}`,
+ );
+ }
+
+ private async throttleByTokenOrThrow(token: string): Promise<void> {
+ await this.throttleOrThrow(`unsubscribe:token:${token}`);
+ }
+
@Post()
@HttpCode(200)
- async handleOneClickUnsubscribe(@Query('t') token: string): Promise<void> {
- const payload = this.verifyTokenOrThrow(token);
+ async handleOneClickUnsubscribe(
+ @Query('t') token: string,
+ @Req() request: Request,
+ ): Promise<void> {
+ await this.throttleByRequesterOrThrow(request);
+
+ const { payload } = this.verifyTokenOrThrow(token);
+
+ await this.throttleByTokenOrThrow(token);
if (payload.preview === true) {
return;
}
- await this.messageSuppressionService.suppress({
+ await this.messageSuppressionService.unsubscribeFromEverything({
workspaceId: payload.workspaceId,
emailAddress: payload.emailAddress,
- reason: MessageSuppressionReason.UNSUBSCRIBE,
- source: MessageSuppressionSource.SYSTEM,
- unsubscribeTopicId: payload.unsubscribeTopicId ?? null,
});
}
@Get()
@Header('Content-Type', HTML_CONTENT_TYPE)
- async handlePreferencesPage(@Query('t') token: string): Promise<string> {
- const payload = this.verifyTokenOrThrow(token);
+ async handlePreferencesPage(
+ @Query('t') token: string,
+ @Req() request: Request,
+ ): Promise<string> {
+ await this.throttleByRequesterOrThrow(request);
- const topics = await this.messageSuppressionService.getTopicOptOutState({
- workspaceId: payload.workspaceId,
- emailAddress: payload.emailAddress,
- });
+ const { payload, isExpired } = this.verifyTokenOrThrow(token);
+
+ const topics = isExpired
+ ? []
+ : await this.messageSuppressionService.getTopicOptOutState({
+ workspaceId: payload.workspaceId,
+ emailAddress: payload.emailAddress,
+ });
return buildUnsubscribePreferencesPage({
token,
@@ -88,8 +134,15 @@ export class UnsubscribeController {
@Header('Content-Type', HTML_CONTENT_TYPE)
async handleUpdatePreferences(
@Body() body: UnsubscribeFormBody,
+ @Req() request: Request,
): Promise<string> {
- const payload = this.verifyTokenOrThrow(body.t);
+ await this.throttleByRequesterOrThrow(request);
+
+ const { payload, isExpired } = this.verifyTokenOrThrow(body.t);
+
+ if (isExpired) {
+ throw new BadRequestException('Expired unsubscribe token');
+ }
if (payload.preview === true) {
return PREVIEW_RESULT_PAGE;
@@ -99,6 +152,11 @@ export class UnsubscribeController {
workspaceId: payload.workspaceId,
emailAddress: payload.emailAddress,
keptTopicIds: this.normalizeTopicIds(body.unsubscribeTopicId),
+ canResubscribe: !isUnsubscribeTokenExpired({
+ issuedAt: payload.issuedAt,
+ now: Date.now(),
+ maxAgeMs: RESUBSCRIBE_MAX_AGE_MS,
+ }),
});
return buildUnsubscribeResultPage(
@@ -111,18 +169,19 @@ export class UnsubscribeController {
@Header('Content-Type', HTML_CONTENT_TYPE)
async handleUnsubscribeAll(
@Body() body: UnsubscribeFormBody,
+ @Req() request: Request,
): Promise<string> {
- const payload = this.verifyTokenOrThrow(body.t);
+ await this.throttleByRequesterOrThrow(request);
+
+ const { payload } = this.verifyTokenOrThrow(body.t);
if (payload.preview === true) {
return PREVIEW_RESULT_PAGE;
}
- await this.messageSuppressionService.suppress({
+ await this.messageSuppressionService.unsubscribeFromEverything({
workspaceId: payload.workspaceId,
emailAddress: payload.emailAddress,
- reason: MessageSuppressionReason.UNSUBSCRIBE,
- source: MessageSuppressionSource.SYSTEM,
});
return buildUnsubscribeResultPage(
@@ -143,17 +202,17 @@ export class UnsubscribeController {
private verifyTokenOrThrow(
token: string | undefined,
- ): UnsubscribeTokenPayload {
+ ): UnsubscribeTokenVerification {
if (!isNonEmptyString(token) || !UNSUBSCRIBE_TOKEN_FORMAT.test(token)) {
throw new BadRequestException('Malformed unsubscribe token');
}
- const payload = this.unsubscribeTokenService.verify(token);
+ const verification = this.unsubscribeTokenService.verify(token);
- if (payload === null) {
+ if (verification === null) {
throw new BadRequestException('Invalid unsubscribe token');
}
- return payload;
+ return verification;
}
}
diff --git a/packages/twenty-server/src/modules/emailing/crons/commands/reconcile-campaign-stats.cron.command.ts b/packages/twenty-server/src/modules/emailing/crons/commands/reconcile-campaign-stats.cron.command.ts
new file mode 100644
index 00000000000..c774af6cf6a
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/crons/commands/reconcile-campaign-stats.cron.command.ts
@@ -0,0 +1,31 @@
+import { RECONCILE_CAMPAIGN_STATS_CRON_PATTERN } from 'src/modules/emailing/constants/reconcile-campaign-stats-cron-pattern.constant';
+import { Command, CommandRunner } from 'nest-commander';
+
+import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+import { ReconcileCampaignStatsCronJob } from 'src/modules/emailing/crons/jobs/reconcile-campaign-stats.cron.job';
+
+@Command({
+ name: 'cron:emailing:reconcile-campaign-stats',
+ description:
+ 'Starts a cron job to recompute message campaign counters that a dropped stats refresh left stale',
+})
+export class ReconcileCampaignStatsCronCommand extends CommandRunner {
+ constructor(
+ @InjectMessageQueue(MessageQueue.cronQueue)
+ private readonly messageQueueService: MessageQueueService,
+ ) {
+ super();
+ }
+
+ async run(): Promise<void> {
+ await this.messageQueueService.addCron<undefined>({
+ jobName: ReconcileCampaignStatsCronJob.name,
+ data: undefined,
+ options: {
+ repeat: { pattern: RECONCILE_CAMPAIGN_STATS_CRON_PATTERN },
+ },
+ });
+ }
+}
diff --git a/packages/twenty-server/src/modules/emailing/crons/jobs/reconcile-campaign-stats.cron.job.ts b/packages/twenty-server/src/modules/emailing/crons/jobs/reconcile-campaign-stats.cron.job.ts
new file mode 100644
index 00000000000..e3c0f4b0332
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/crons/jobs/reconcile-campaign-stats.cron.job.ts
@@ -0,0 +1,66 @@
+import { RECONCILE_CAMPAIGN_STATS_CRON_PATTERN } from 'src/modules/emailing/constants/reconcile-campaign-stats-cron-pattern.constant';
+import { CAMPAIGN_JOB_RETRY_LIMIT } from 'src/engine/core-modules/emailing-domain/constants/campaign-job-retry-limit.constant';
+import { RECONCILE_WORKSPACE_CAMPAIGN_STATS_JOB } from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import chunk from 'lodash.chunk';
+import { WorkspaceActivationStatus } from 'twenty-shared/workspace';
+import { IsNull, Repository } from 'typeorm';
+
+import { SentryCronMonitor } from 'src/engine/core-modules/cron/sentry-cron-monitor.decorator';
+import { EmailingDomainEntity } from 'src/engine/core-modules/emailing-domain/emailing-domain.entity';
+import { type ReconcileWorkspaceCampaignStatsJobData } from 'src/engine/core-modules/emailing-domain/types/reconcile-workspace-campaign-stats-job-data.type';
+import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
+import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
+import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';
+import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+
+const ENQUEUE_BATCH_SIZE = 500;
+
+@Processor(MessageQueue.cronQueue)
+export class ReconcileCampaignStatsCronJob {
+ constructor(
+ @InjectRepository(EmailingDomainEntity)
+ private readonly emailingDomainRepository: Repository<EmailingDomainEntity>,
+ @InjectMessageQueue(MessageQueue.campaignQueue)
+ private readonly messageQueueService: MessageQueueService,
+ private readonly exceptionHandlerService: ExceptionHandlerService,
+ ) {}
+
+ @Process(ReconcileCampaignStatsCronJob.name)
+ @SentryCronMonitor(
+ ReconcileCampaignStatsCronJob.name,
+ RECONCILE_CAMPAIGN_STATS_CRON_PATTERN,
+ )
+ async handle(): Promise<void> {
+ const workspaceIds = await this.findSendingWorkspaceIds();
+
+ for (const workspaceIdsBatch of chunk(workspaceIds, ENQUEUE_BATCH_SIZE)) {
+ await this.messageQueueService
+ .bulkAdd<ReconcileWorkspaceCampaignStatsJobData>(
+ RECONCILE_WORKSPACE_CAMPAIGN_STATS_JOB,
+ workspaceIdsBatch.map((workspaceId) => ({ workspaceId })),
+ { retryLimit: CAMPAIGN_JOB_RETRY_LIMIT },
+ )
+ .catch((error) => {
+ this.exceptionHandlerService.captureExceptions([error]);
+ });
+ }
+ }
+
+ private async findSendingWorkspaceIds(): Promise<string[]> {
+ const emailingDomains = await this.emailingDomainRepository.find({
+ select: { workspaceId: true },
+ where: {
+ workspace: {
+ deletedAt: IsNull(),
+ activationStatus: WorkspaceActivationStatus.ACTIVE,
+ },
+ },
+ });
+
+ return [...new Set(emailingDomains.map(({ workspaceId }) => workspaceId))];
+ }
+}
diff --git a/packages/twenty-server/src/modules/emailing/emailing.module.ts b/packages/twenty-server/src/modules/emailing/emailing.module.ts
index a1f0f0153a7..2c0ef21e61f 100644
--- a/packages/twenty-server/src/modules/emailing/emailing.module.ts
+++ b/packages/twenty-server/src/modules/emailing/emailing.module.ts
@@ -18,13 +18,17 @@ import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkspaceEventEmitterModule } from 'src/engine/workspace-event-emitter/workspace-event-emitter.module';
+import { UsageLimitModule } from 'src/engine/core-modules/usage-limit/usage-limit.module';
import { UnsubscribeController } from 'src/modules/emailing/controllers/unsubscribe.controller';
import { EmailingOngoingStaleCronCommand } from 'src/modules/emailing/crons/commands/emailing-ongoing-stale.cron.command';
import { EmailingOngoingStaleCronJob } from 'src/modules/emailing/crons/jobs/emailing-ongoing-stale.cron.job';
+import { ReconcileCampaignStatsCronCommand } from 'src/modules/emailing/crons/commands/reconcile-campaign-stats.cron.command';
+import { ReconcileCampaignStatsCronJob } from 'src/modules/emailing/crons/jobs/reconcile-campaign-stats.cron.job';
import { EmailingSendResolver } from 'src/modules/emailing/resolvers/emailing-send.resolver';
import { MessageSuppressionResolver } from 'src/modules/emailing/resolvers/message-suppression.resolver';
import { UnsubscribeTopicResolver } from 'src/modules/emailing/resolvers/unsubscribe-topic.resolver';
import { CampaignVariableService } from 'src/modules/emailing/services/campaign-variable.service';
+import { ThrottlerModule } from 'src/engine/core-modules/throttler/throttler.module';
import { EmailBillingService } from 'src/modules/emailing/services/email-billing.service';
import { EmailingDomainSenderService } from 'src/modules/emailing/services/emailing-domain-sender.service';
import { MessageCampaignDraftService } from 'src/modules/emailing/services/message-campaign-draft.service';
@@ -43,6 +47,7 @@ import { SaveCampaignTool } from 'src/modules/emailing/tools/save-campaign-tool'
@Module({
imports: [
EmailingDomainModule,
+ ThrottlerModule,
MessageChannelMetadataModule,
FeatureFlagModule,
PermissionsModule,
@@ -52,6 +57,7 @@ import { SaveCampaignTool } from 'src/modules/emailing/tools/save-campaign-tool'
WorkspaceEventEmitterModule,
WorkspaceCacheModule,
WorkspaceManyOrAllFlatEntityMapsCacheModule,
+ UsageLimitModule,
TypeOrmModule.forFeature([
MessageChannelEntity,
EmailingDomainEntity,
@@ -87,9 +93,12 @@ import { SaveCampaignTool } from 'src/modules/emailing/tools/save-campaign-tool'
provideWorkspaceScopedRepository(CampaignDeliveryEntity),
EmailingOngoingStaleCronCommand,
EmailingOngoingStaleCronJob,
+ ReconcileCampaignStatsCronCommand,
+ ReconcileCampaignStatsCronJob,
],
exports: [
EmailingDomainSenderService,
+ EmailBillingService,
MessageCampaignService,
MessageCampaignDeliveryService,
MessageCampaignDeliveryFeedbackService,
@@ -100,6 +109,7 @@ import { SaveCampaignTool } from 'src/modules/emailing/tools/save-campaign-tool'
UnsubscribeTopicService,
SaveCampaignTool,
EmailingOngoingStaleCronCommand,
+ ReconcileCampaignStatsCronCommand,
],
})
export class EmailingModule {}
diff --git a/packages/twenty-server/src/modules/emailing/jobs/materialize-campaign-chunk.job.ts b/packages/twenty-server/src/modules/emailing/jobs/materialize-campaign-chunk.job.ts
index 62824861b2c..ca37a1e384a 100644
--- a/packages/twenty-server/src/modules/emailing/jobs/materialize-campaign-chunk.job.ts
+++ b/packages/twenty-server/src/modules/emailing/jobs/materialize-campaign-chunk.job.ts
@@ -5,7 +5,7 @@ import { Processor } from 'src/engine/core-modules/message-queue/decorators/proc
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { MessageCampaignMaterializationService } from 'src/modules/emailing/services/message-campaign-materialization.service';
-@Processor(MessageQueue.emailQueue)
+@Processor(MessageQueue.campaignQueue)
export class MaterializeCampaignChunkJob {
constructor(
private readonly messageCampaignMaterializationService: MessageCampaignMaterializationService,
diff --git a/packages/twenty-server/src/modules/emailing/jobs/reconcile-workspace-campaign-stats.job.ts b/packages/twenty-server/src/modules/emailing/jobs/reconcile-workspace-campaign-stats.job.ts
new file mode 100644
index 00000000000..5a87bd45624
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/jobs/reconcile-workspace-campaign-stats.job.ts
@@ -0,0 +1,20 @@
+import { RECONCILE_WORKSPACE_CAMPAIGN_STATS_JOB } from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
+import { type ReconcileWorkspaceCampaignStatsJobData } from 'src/engine/core-modules/emailing-domain/types/reconcile-workspace-campaign-stats-job-data.type';
+import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';
+import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageCampaignStatisticsService } from 'src/modules/emailing/services/message-campaign-statistics.service';
+
+@Processor(MessageQueue.campaignQueue)
+export class ReconcileWorkspaceCampaignStatsJob {
+ constructor(
+ private readonly messageCampaignStatisticsService: MessageCampaignStatisticsService,
+ ) {}
+
+ @Process(RECONCILE_WORKSPACE_CAMPAIGN_STATS_JOB)
+ async handle(data: ReconcileWorkspaceCampaignStatsJobData): Promise<void> {
+ await this.messageCampaignStatisticsService.reconcileWorkspaceCampaignCounts(
+ { workspaceId: data.workspaceId },
+ );
+ }
+}
diff --git a/packages/twenty-server/src/modules/emailing/resolvers/emailing-send.resolver.ts b/packages/twenty-server/src/modules/emailing/resolvers/emailing-send.resolver.ts
index 7613c2a80dc..ab236825045 100644
--- a/packages/twenty-server/src/modules/emailing/resolvers/emailing-send.resolver.ts
+++ b/packages/twenty-server/src/modules/emailing/resolvers/emailing-send.resolver.ts
@@ -1,4 +1,4 @@
-import { UseFilters, UseGuards, UsePipes } from '@nestjs/common';
+import { Logger, UseFilters, UseGuards, UsePipes } from '@nestjs/common';
import { Args, Mutation, Query } from '@nestjs/graphql';
import { PermissionFlagType } from 'twenty-shared/constants';
@@ -27,11 +27,14 @@ import {
} from 'src/engine/guards/feature-flag.guard';
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
+import { ThrottlerGraphqlApiExceptionFilter } from 'src/engine/core-modules/throttler/filters/throttler-graphql-api-exception.filter';
import { EmailBillingService } from 'src/modules/emailing/services/email-billing.service';
import { EmailingDomainSenderService } from 'src/modules/emailing/services/emailing-domain-sender.service';
import { MessageCampaignAudienceService } from 'src/modules/emailing/services/message-campaign-audience.service';
import { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';
import { MessageCampaignService } from 'src/modules/emailing/services/message-campaign.service';
+import { countDeliveredRecipients } from 'src/engine/core-modules/emailing-domain/utils/count-delivered-recipients.util';
+import { type EmailingDomainSendEmailResult } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-email-result.type';
@UseGuards(
WorkspaceAuthGuard,
@@ -41,10 +44,13 @@ import { MessageCampaignService } from 'src/modules/emailing/services/message-ca
@UseFilters(
EmailGroupAccessGraphqlApiExceptionFilter,
EmailingDomainGraphqlApiExceptionFilter,
+ ThrottlerGraphqlApiExceptionFilter,
)
@UsePipes(ResolverValidationPipe)
@MetadataResolver()
export class EmailingSendResolver {
+ private readonly logger = new Logger(EmailingSendResolver.name);
+
constructor(
private readonly emailingDomainSenderService: EmailingDomainSenderService,
private readonly messageCampaignService: MessageCampaignService,
@@ -59,6 +65,8 @@ export class EmailingSendResolver {
async sendEmailViaEmailingDomain(
@Args('input') input: SendEmailViaDomainInput,
@AuthWorkspace() currentWorkspace: WorkspaceEntity,
+ @AuthUserWorkspaceId({ allowUndefined: true })
+ userWorkspaceId: string | undefined,
): Promise<SendEmailViaDomainOutputDTO> {
this.emailGroupAccessService.validateEmailGroupAccessOrThrow();
await this.emailBillingService.validateEmailCreditsOrThrow(
@@ -69,12 +77,13 @@ export class EmailingSendResolver {
const result = await this.emailingDomainSenderService.sendEmail(
currentWorkspace.id,
emailingDomainId,
- content,
+ { ...content, sendKind: 'TRANSACTIONAL' },
);
- await this.emailBillingService.billSentEmails({
+ await this.billAcceptedSend({
workspaceId: currentWorkspace.id,
- sentEmailCount: 1,
+ userWorkspaceId,
+ result,
});
return { messageId: result.messageId };
@@ -135,6 +144,8 @@ export class EmailingSendResolver {
fromAddress: input.fromAddress,
});
+ await this.billAcceptedSend({ workspaceId: currentWorkspace.id, result });
+
return { messageId: result.messageId };
}
@@ -154,4 +165,30 @@ export class EmailingSendResolver {
unsubscribeTopicId: input.unsubscribeTopicId,
});
}
+
+ // The provider has already accepted the mail, so surfacing a billing failure
+ // would invite a retry that sends it a second time.
+ private async billAcceptedSend({
+ workspaceId,
+ userWorkspaceId,
+ result,
+ }: {
+ workspaceId: string;
+ userWorkspaceId?: string;
+ result: EmailingDomainSendEmailResult;
+ }): Promise<void> {
+ await this.emailBillingService
+ .billSentEmails({
+ workspaceId,
+ userWorkspaceId,
+ sentEmailCount: countDeliveredRecipients(result.deliveredRecipients),
+ })
+ .catch((error) => {
+ this.logger.error(
+ `Workspace ${workspaceId} sent email ${result.messageId} but failed to bill it, so this send is unbilled: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ });
+ }
}
diff --git a/packages/twenty-server/src/modules/emailing/resolvers/message-suppression.resolver.ts b/packages/twenty-server/src/modules/emailing/resolvers/message-suppression.resolver.ts
index 0ddf62d1a3c..420e604cce4 100644
--- a/packages/twenty-server/src/modules/emailing/resolvers/message-suppression.resolver.ts
+++ b/packages/twenty-server/src/modules/emailing/resolvers/message-suppression.resolver.ts
@@ -1,12 +1,17 @@
import { UseFilters, UseGuards, UsePipes } from '@nestjs/common';
-import { Args, Query } from '@nestjs/graphql';
+import { Args, Mutation, Query } from '@nestjs/graphql';
import { PermissionFlagType } from 'twenty-shared/constants';
import { FeatureFlagKey } from 'twenty-shared/types';
import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { CreateMessageSuppressionInput } from 'src/engine/core-modules/emailing-domain/dtos/create-message-suppression.input';
import { FindMessageSuppressionsInput } from 'src/engine/core-modules/emailing-domain/dtos/find-message-suppressions.input';
-import { MessageSuppressionListDTO } from 'src/engine/core-modules/emailing-domain/dtos/message-suppression.dto';
+import {
+ MessageSuppressionDTO,
+ MessageSuppressionListDTO,
+} from 'src/engine/core-modules/emailing-domain/dtos/message-suppression.dto';
import { EmailGroupAccessGraphqlApiExceptionFilter } from 'src/engine/core-modules/emailing-domain/filters/email-group-access-graphql-api-exception.filter';
import { EmailingDomainGraphqlApiExceptionFilter } from 'src/engine/core-modules/emailing-domain/filters/emailing-domain-graphql-api-exception.filter';
import { EmailGroupAccessService } from 'src/engine/core-modules/emailing-domain/services/email-group-access.service';
@@ -55,4 +60,35 @@ export class MessageSuppressionResolver {
offset: input.offset,
});
}
+
+ @Mutation(() => MessageSuppressionDTO)
+ @RequireFeatureFlag(FeatureFlagKey.IS_EMAIL_GROUP_ENABLED)
+ async createMessageSuppression(
+ @Args('input') input: CreateMessageSuppressionInput,
+ @AuthWorkspace() currentWorkspace: WorkspaceEntity,
+ ): Promise<MessageSuppressionDTO> {
+ this.emailGroupAccessService.validateEmailGroupAccessOrThrow();
+
+ return this.messageSuppressionService.suppressManually({
+ workspaceId: currentWorkspace.id,
+ emailAddress: input.emailAddress,
+ unsubscribeTopicId: input.unsubscribeTopicId,
+ });
+ }
+
+ @Mutation(() => Boolean)
+ @RequireFeatureFlag(FeatureFlagKey.IS_EMAIL_GROUP_ENABLED)
+ async deleteMessageSuppression(
+ @Args('id', { type: () => UUIDScalarType }) suppressionId: string,
+ @AuthWorkspace() currentWorkspace: WorkspaceEntity,
+ ): Promise<boolean> {
+ this.emailGroupAccessService.validateEmailGroupAccessOrThrow();
+
+ await this.messageSuppressionService.removeSuppression({
+ workspaceId: currentWorkspace.id,
+ suppressionId,
+ });
+
+ return true;
+ }
}
diff --git a/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts b/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts
index 16f8445fe7a..dfa95e21639 100644
--- a/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts
@@ -3,11 +3,14 @@ import { Injectable } from '@nestjs/common';
import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
+import { type CurrentBillingSubscription } from 'src/engine/core-modules/billing/types/flat-billing-subscription.type';
+import { USAGE_RECORDED } from 'src/engine/core-modules/usage/constants/usage-recorded.constant';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
import { convertDollarsToBillingCredits } from 'src/engine/metadata-modules/ai/ai-billing/utils/convert-dollars-to-billing-credits.util';
+import { type EmailCreditContext } from 'src/modules/emailing/types/email-credit-context.type';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { EMAIL_MARGIN_MULTIPLIER } from 'src/modules/emailing/constants/email-margin-multiplier';
import { SES_EMAIL_COST_PER_THOUSAND_DOLLARS } from 'src/modules/emailing/constants/ses-email-cost-per-thousand-dollars';
@@ -21,22 +24,44 @@ export class EmailBillingService {
private readonly workspaceCacheService: WorkspaceCacheService,
) {}
- async hasEmailCredits(workspaceId: string): Promise<boolean> {
- return this.billingUsageService.hasAvailableCredits(workspaceId);
- }
-
async validateEmailCreditsOrThrow(workspaceId: string): Promise<void> {
await this.billingUsageService.hasAvailableCreditsOrThrow(workspaceId);
}
+ async resolveEmailCreditContext(
+ workspaceId: string,
+ ): Promise<EmailCreditContext> {
+ if (!this.billingService.isBillingEnabled()) {
+ return {
+ hasCredits: true,
+ currentBillingSubscription: NO_BILLING_SUBSCRIPTION,
+ };
+ }
+
+ const { currentBillingSubscription } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'currentBillingSubscription',
+ ]);
+
+ const { hasAvailableCredits } =
+ await this.billingUsageService.getCreditAvailability({
+ workspaceId,
+ currentBillingSubscription,
+ });
+
+ return { hasCredits: hasAvailableCredits, currentBillingSubscription };
+ }
+
async billSentEmails({
workspaceId,
sentEmailCount,
userWorkspaceId,
+ currentBillingSubscription: providedCurrentBillingSubscription,
}: {
workspaceId: string;
sentEmailCount: number;
userWorkspaceId?: string | null;
+ currentBillingSubscription?: CurrentBillingSubscription;
}): Promise<void> {
if (sentEmailCount <= 0) {
return;
@@ -50,15 +75,17 @@ export class EmailBillingService {
);
if (this.billingService.isBillingEnabled()) {
- const { currentBillingSubscription } =
- await this.workspaceCacheService.getOrRecompute(workspaceId, [
- 'currentBillingSubscription',
- ]);
+ const currentBillingSubscription =
+ await this.billingUsageService.resolveCurrentBillingSubscription({
+ workspaceId,
+ providedCurrentBillingSubscription,
+ });
if (currentBillingSubscription !== NO_BILLING_SUBSCRIPTION) {
await this.billingUsageService.decrementAvailableCreditsInCache({
workspaceId,
usedCredits: creditsUsedMicro,
+ currentBillingSubscription,
});
}
}
diff --git a/packages/twenty-server/src/modules/emailing/services/emailing-domain-sender.service.ts b/packages/twenty-server/src/modules/emailing/services/emailing-domain-sender.service.ts
index 66a8a5ab374..c5d136bfe7a 100644
--- a/packages/twenty-server/src/modules/emailing/services/emailing-domain-sender.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/emailing-domain-sender.service.ts
@@ -20,6 +20,7 @@ import { formatMessageFromHeader } from 'src/modules/messaging/message-outbound-
import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';
import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import { type DeliverableRecipients } from 'src/engine/core-modules/emailing-domain/types/deliverable-recipients.type';
+import { isSuppressionBlockingSend } from 'src/engine/core-modules/emailing-domain/utils/is-suppression-blocking-send.util';
import { getDomainFromEmail } from 'src/utils/get-domain-from-email';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
@@ -168,26 +169,27 @@ export class EmailingDomainSenderService {
...(emailContent.bcc ?? []),
];
- const suppressedAddresses =
- await this.messageSuppressionService.getSuppressedAddresses(
+ const suppressions =
+ await this.messageSuppressionService.findApplicableSuppressions({
workspaceId,
- allRecipients,
- );
-
- const listUnsubscribedAddresses = await this.getListUnsubscribedAddresses(
- workspaceId,
- allRecipients,
- emailContent.unsubscribeTopicId,
+ emailAddresses: allRecipients,
+ unsubscribeTopicId: emailContent.unsubscribeTopicId,
+ });
+
+ const blockedAddresses = new Set(
+ suppressions
+ .filter((suppression) =>
+ isSuppressionBlockingSend({
+ sendKind: emailContent.sendKind,
+ suppression,
+ unsubscribeTopicId: emailContent.unsubscribeTopicId,
+ }),
+ )
+ .map((suppression) => suppression.emailAddress),
);
- const isDeliverable = (address: string): boolean => {
- const normalizedAddress = address.trim().toLowerCase();
-
- return (
- !suppressedAddresses.has(normalizedAddress) &&
- !listUnsubscribedAddresses.has(normalizedAddress)
- );
- };
+ const isDeliverable = (address: string): boolean =>
+ !blockedAddresses.has(address.trim().toLowerCase());
const to = emailContent.to.filter(isDeliverable);
@@ -204,20 +206,4 @@ export class EmailingDomainSenderService {
bcc: emailContent.bcc?.filter(isDeliverable),
};
}
-
- private async getListUnsubscribedAddresses(
- workspaceId: string,
- recipients: string[],
- unsubscribeTopicId: string | undefined,
- ): Promise<Set<string>> {
- if (!isNonEmptyString(unsubscribeTopicId)) {
- return new Set();
- }
-
- return this.messageSuppressionService.getTopicSuppressedAddresses(
- workspaceId,
- recipients,
- unsubscribeTopicId,
- );
- }
}
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-audience.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-audience.service.ts
index c3b14fd7953..0e20e11f881 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign-audience.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-audience.service.ts
@@ -1,41 +1,20 @@
import { Injectable } from '@nestjs/common';
import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
import { In } from 'typeorm';
+import { type CampaignAudienceResolution } from 'src/engine/core-modules/emailing-domain/types/campaign-audience-resolution.type';
+import { resolveCampaignAudience } from 'src/engine/core-modules/emailing-domain/utils/resolve-campaign-audience.util';
+import { HARD_SUPPRESSION_REASONS } from 'src/engine/core-modules/emailing-domain/constants/hard-suppression-reasons.constant';
import { MAX_CAMPAIGN_RECIPIENTS } from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
-import { type CampaignSkippedBreakdown } from 'src/engine/core-modules/emailing-domain/types/campaign-skipped-breakdown.type';
-import { type CampaignRecipient } from 'src/engine/core-modules/emailing-domain/types/campaign-recipient.type';
import { type RawCampaignRecipient } from 'src/engine/core-modules/emailing-domain/types/raw-campaign-recipient.type';
-import { normalizeCampaignRecipients } from 'src/engine/core-modules/emailing-domain/utils/normalize-campaign-recipients.util';
import { UserRoleService } from 'src/engine/metadata-modules/user-role/user-role.service';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';
import { MessageListMemberWorkspaceEntity } from 'src/modules/emailing/standard-objects/message-list-member.workspace-entity';
import { PersonWorkspaceEntity } from 'src/modules/person/standard-objects/person.workspace-entity';
-type CampaignAudiencePreview = {
- totalMembers: number;
- withoutEmail: number;
- duplicateEmails: number;
- globallyUnsubscribed: number;
- topicUnsubscribed: number;
- sendable: number;
-};
-
-type NormalizedAudience = {
- recipients: CampaignRecipient[];
- skipped: CampaignSkippedBreakdown;
-};
-
-const toRawRecipient = (person: {
- id: string;
- emails?: { primaryEmail?: string | null } | null;
-}): RawCampaignRecipient => ({
- personId: person.id,
- email: person.emails?.primaryEmail ?? null,
-});
-
@Injectable()
export class MessageCampaignAudienceService {
constructor(
@@ -48,21 +27,76 @@ export class MessageCampaignAudienceService {
workspaceId,
listId,
roleId,
+ unsubscribeTopicId,
}: {
workspaceId: string;
listId: string;
roleId: string;
- }): Promise<NormalizedAudience> {
- return this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const rawRecipients = await this.resolveRecipientsFromList({
+ unsubscribeTopicId?: string;
+ }): Promise<CampaignAudienceResolution> {
+ return this.workspaceOrmManager.executeInWorkspaceContext(() =>
+ this.resolveAudience({
+ workspaceId,
+ listId,
+ roleId,
+ unsubscribeTopicId,
+ }),
+ );
+ }
+
+ private async resolveAudience({
+ workspaceId,
+ listId,
+ roleId,
+ unsubscribeTopicId,
+ }: {
+ workspaceId: string;
+ listId: string;
+ roleId: string;
+ unsubscribeTopicId?: string;
+ }): Promise<CampaignAudienceResolution> {
+ const { rawRecipients, totalMemberCount } =
+ await this.resolveRecipientsFromList({
listId,
roleId,
});
- return normalizeCampaignRecipients(
- rawRecipients,
- MAX_CAMPAIGN_RECIPIENTS,
- );
+ const emailAddresses = rawRecipients
+ .map((rawRecipient) => rawRecipient.email)
+ .filter(isNonEmptyString);
+
+ const suppressions =
+ await this.messageSuppressionService.findApplicableSuppressions({
+ workspaceId,
+ emailAddresses,
+ unsubscribeTopicId,
+ });
+
+ const hardSuppressedEmails = new Set<string>();
+ const globallySuppressedEmails = new Set<string>();
+ const topicSuppressedEmails = new Set<string>();
+
+ for (const suppression of suppressions) {
+ if (isDefined(suppression.unsubscribeTopicId)) {
+ topicSuppressedEmails.add(suppression.emailAddress);
+ continue;
+ }
+
+ if (HARD_SUPPRESSION_REASONS.includes(suppression.reason)) {
+ hardSuppressedEmails.add(suppression.emailAddress);
+ continue;
+ }
+
+ globallySuppressedEmails.add(suppression.emailAddress);
+ }
+
+ return resolveCampaignAudience({
+ rawRecipients,
+ totalMemberCount,
+ maxRecipients: MAX_CAMPAIGN_RECIPIENTS,
+ hardSuppressedEmails,
+ globallySuppressedEmails,
+ topicSuppressedEmails,
});
}
@@ -76,69 +110,23 @@ export class MessageCampaignAudienceService {
userWorkspaceId: string;
listId: string;
unsubscribeTopicId?: string;
- }): Promise<CampaignAudiencePreview> {
+ }): Promise<CampaignAudienceResolution['audience']> {
const roleId = await this.userRoleService.getRoleIdForUserWorkspace({
workspaceId,
userWorkspaceId,
});
- return this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const rawRecipients = await this.resolveRecipientsFromList({
- listId,
- roleId,
- });
-
- const { recipients, skipped } = normalizeCampaignRecipients(
- rawRecipients,
- MAX_CAMPAIGN_RECIPIENTS,
+ const { audience } =
+ await this.workspaceOrmManager.executeInWorkspaceContext(() =>
+ this.resolveAudience({
+ workspaceId,
+ listId,
+ roleId,
+ unsubscribeTopicId,
+ }),
);
- const emails = recipients.map((recipient) => recipient.email);
-
- const globallySuppressed =
- await this.messageSuppressionService.getSuppressedAddresses(
- workspaceId,
- emails,
- );
- const topicSuppressed = isNonEmptyString(unsubscribeTopicId)
- ? await this.messageSuppressionService.getTopicSuppressedAddresses(
- workspaceId,
- emails,
- unsubscribeTopicId,
- )
- : new Set<string>();
-
- const resolveSuppressionOutcome = (recipient: CampaignRecipient) => {
- const normalizedEmail = recipient.email.trim().toLowerCase();
-
- if (globallySuppressed.has(normalizedEmail)) {
- return 'GLOBALLY_UNSUBSCRIBED';
- }
-
- if (topicSuppressed.has(normalizedEmail)) {
- return 'TOPIC_UNSUBSCRIBED';
- }
-
- return 'SENDABLE';
- };
-
- const suppressionOutcomes = recipients.map(resolveSuppressionOutcome);
-
- return {
- totalMembers: rawRecipients.length,
- withoutEmail: skipped.noEmail,
- duplicateEmails: skipped.deduped,
- globallyUnsubscribed: suppressionOutcomes.filter(
- (outcome) => outcome === 'GLOBALLY_UNSUBSCRIBED',
- ).length,
- topicUnsubscribed: suppressionOutcomes.filter(
- (outcome) => outcome === 'TOPIC_UNSUBSCRIBED',
- ).length,
- sendable: suppressionOutcomes.filter(
- (outcome) => outcome === 'SENDABLE',
- ).length,
- };
- });
+ return audience;
}
private async resolveRecipientsFromList({
@@ -147,7 +135,10 @@ export class MessageCampaignAudienceService {
}: {
listId: string;
roleId: string;
- }): Promise<RawCampaignRecipient[]> {
+ }): Promise<{
+ rawRecipients: RawCampaignRecipient[];
+ totalMemberCount: number;
+ }> {
const listMemberRepository = this.workspaceOrmManager.getRepository(
MessageListMemberWorkspaceEntity,
{ unionOf: [roleId] },
@@ -157,7 +148,7 @@ export class MessageCampaignAudienceService {
const personIds = members.map((member) => member.personId);
if (personIds.length === 0) {
- return [];
+ return { rawRecipients: [], totalMemberCount: members.length };
}
const personRepository = this.workspaceOrmManager.getRepository(
@@ -169,6 +160,12 @@ export class MessageCampaignAudienceService {
where: { id: In(personIds) },
});
- return people.map(toRawRecipient);
+ return {
+ rawRecipients: people.map((person) => ({
+ personId: person.id,
+ email: person.emails?.primaryEmail ?? null,
+ })),
+ totalMemberCount: members.length,
+ };
}
}
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery-feedback.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery-feedback.service.ts
index 4302a627832..239dba8f98e 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery-feedback.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery-feedback.service.ts
@@ -3,28 +3,19 @@ import { Injectable } from '@nestjs/common';
import { type QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import { CampaignDeliveryEntity } from 'src/engine/core-modules/emailing-domain/campaign-delivery.entity';
-import { CAMPAIGN_DELIVERY_STATE } from 'src/engine/core-modules/emailing-domain/constants/campaign-delivery-state.constant';
-import { CAMPAIGN_FAILURE_REASON } from 'src/engine/core-modules/emailing-domain/constants/campaign-failure-reason.constant';
-import { CAMPAIGN_PROVIDER_OUTCOME } from 'src/engine/core-modules/emailing-domain/constants/campaign-provider-outcome.constant';
import { type CampaignProviderOutcome } from 'src/engine/core-modules/emailing-domain/types/campaign-provider-outcome.type';
+import { buildCampaignDeliveryOutcomeUpdate } from 'src/engine/core-modules/emailing-domain/utils/build-campaign-delivery-outcome-update.util';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
-import { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';
-import { assertUnreachable, isDefined } from 'twenty-shared/utils';
-
-type CampaignDeliveryOutcomeUpdate = Partial<
- Pick<
- CampaignDeliveryEntity,
- 'deliveredAt' | 'bouncedAt' | 'complainedAt' | 'state' | 'failureReason'
- >
->;
+import { MessageCampaignStatisticsService } from 'src/modules/emailing/services/message-campaign-statistics.service';
+import { isDefined } from 'twenty-shared/utils';
@Injectable()
export class MessageCampaignDeliveryFeedbackService {
constructor(
@InjectWorkspaceScopedRepository(CampaignDeliveryEntity)
private readonly campaignDeliveryRepository: WorkspaceScopedRepository<CampaignDeliveryEntity>,
- private readonly messageCampaignLifecycleService: MessageCampaignLifecycleService,
+ private readonly messageCampaignStatisticsService: MessageCampaignStatisticsService,
) {}
async recordProviderOutcomeByProviderMessageId({
@@ -36,7 +27,10 @@ export class MessageCampaignDeliveryFeedbackService {
providerMessageId: string;
outcome: CampaignProviderOutcome;
}): Promise<void> {
- const update = this.buildOutcomeUpdate(outcome);
+ const update = buildCampaignDeliveryOutcomeUpdate({
+ outcome,
+ occurredAt: new Date(),
+ });
if (Object.keys(update).length === 0) {
return;
@@ -63,38 +57,9 @@ export class MessageCampaignDeliveryFeedbackService {
return;
}
- await this.messageCampaignLifecycleService.scheduleStatsRefresh({
+ await this.messageCampaignStatisticsService.scheduleRefresh({
workspaceId,
campaignId: updatedDelivery.campaignId,
});
}
-
- private buildOutcomeUpdate(
- outcome: CampaignProviderOutcome,
- ): CampaignDeliveryOutcomeUpdate {
- const occurredAt = new Date();
-
- switch (outcome) {
- case CAMPAIGN_PROVIDER_OUTCOME.DELIVERED:
- return { deliveredAt: occurredAt };
- case CAMPAIGN_PROVIDER_OUTCOME.BOUNCED:
- return { bouncedAt: occurredAt };
- case CAMPAIGN_PROVIDER_OUTCOME.COMPLAINED:
- return { complainedAt: occurredAt };
- case CAMPAIGN_PROVIDER_OUTCOME.REJECTED:
- return {
- state: CAMPAIGN_DELIVERY_STATE.FAILED,
- failureReason: CAMPAIGN_FAILURE_REASON.REJECTED,
- };
- case CAMPAIGN_PROVIDER_OUTCOME.RENDERING_FAILED:
- return {
- state: CAMPAIGN_DELIVERY_STATE.FAILED,
- failureReason: CAMPAIGN_FAILURE_REASON.RENDERING_FAILED,
- };
- case CAMPAIGN_PROVIDER_OUTCOME.SOFT_BOUNCED:
- return {};
- default:
- return assertUnreachable(outcome);
- }
- }
}
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery.service.ts
index 7b149edaf19..4991de8a37a 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery.service.ts
@@ -3,8 +3,22 @@ import { Injectable, Logger } from '@nestjs/common';
import { In } from 'typeorm';
import { CampaignDeliveryEntity } from 'src/engine/core-modules/emailing-domain/campaign-delivery.entity';
+import { SEND_CAMPAIGN_EMAIL_JOB } from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
+import { CAMPAIGN_SEND_RETRY_BACKOFF } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant';
+import { CAMPAIGN_SEND_RETRY_LIMIT } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-limit.constant';
import { CAMPAIGN_DELIVERY_CLAIM_TTL_MS } from 'src/engine/core-modules/emailing-domain/constants/campaign-delivery-claim-ttl-ms.constant';
+import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+import {
+ UsageLimitException,
+ UsageLimitExceptionCode,
+} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { UsageLimitSpeedService } from 'src/engine/core-modules/usage-limit/services/usage-limit-speed.service';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { CAMPAIGN_DELIVERY_STATE } from 'src/engine/core-modules/emailing-domain/constants/campaign-delivery-state.constant';
+import { CAMPAIGN_FAILURE_REASON } from 'src/engine/core-modules/emailing-domain/constants/campaign-failure-reason.constant';
import { CAMPAIGN_SKIP_REASON } from 'src/engine/core-modules/emailing-domain/constants/campaign-skip-reason.constant';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
@@ -17,6 +31,7 @@ import { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/works
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { CampaignVariableService } from 'src/modules/emailing/services/campaign-variable.service';
import { EmailBillingService } from 'src/modules/emailing/services/email-billing.service';
+import { type EmailCreditContext } from 'src/modules/emailing/types/email-credit-context.type';
import { EmailingDomainSenderService } from 'src/modules/emailing/services/emailing-domain-sender.service';
import { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';
import { MessageCampaignWorkspaceEntity } from 'src/modules/emailing/standard-objects/message-campaign.workspace-entity';
@@ -28,14 +43,22 @@ import { PersonWorkspaceEntity } from 'src/modules/person/standard-objects/perso
import { MessageCampaignStatus } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
-type MessageRepository = WorkspaceRepository<MessageWorkspaceEntity>;
-
type SendContext = {
campaign: MessageCampaignWorkspaceEntity;
person: PersonWorkspaceEntity | null;
claimToken: string;
};
+const SEND_SLOT_RETRY = {
+ attemptLimit: 60,
+ jitterRatio: 0.5,
+ maxWindows: 3,
+ minDelayMs: 1_000,
+ maxDelayMs: 60_000,
+};
+
+type SendSlotRefusal = { retryDelayMs: number; windowMs: number };
+
@Injectable()
export class MessageCampaignDeliveryService {
private readonly logger = new Logger(MessageCampaignDeliveryService.name);
@@ -48,24 +71,68 @@ export class MessageCampaignDeliveryService {
private readonly emailBillingService: EmailBillingService,
private readonly campaignVariableService: CampaignVariableService,
private readonly messageCampaignLifecycleService: MessageCampaignLifecycleService,
+ private readonly usageLimitSpeedService: UsageLimitSpeedService,
+ @InjectMessageQueue(MessageQueue.campaignQueue)
+ private readonly messageQueueService: MessageQueueService,
) {}
async processSendJob(data: SendCampaignEmailJobData): Promise<void> {
const { workspaceId, campaignId } = data;
await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ const campaign = await this.findRunningCampaign(campaignId);
+
+ if (!isDefined(campaign)) {
+ return;
+ }
+
+ const claimableCount = await this.campaignDeliveryRepository.count(
+ workspaceId,
+ {
+ where: {
+ id: data.messageId,
+ state: In([
+ CAMPAIGN_DELIVERY_STATE.QUEUED,
+ CAMPAIGN_DELIVERY_STATE.FAILED,
+ ]),
+ },
+ },
+ );
+
+ if (claimableCount === 0) {
+ return;
+ }
+
+ const creditContext =
+ await this.emailBillingService.resolveEmailCreditContext(workspaceId);
+
+ if (creditContext.hasCredits) {
+ const refusal = await this.findSendSlotRefusal(workspaceId);
+
+ if (isDefined(refusal)) {
+ await this.requeueRateLimitedSendJob({ data, refusal });
+
+ return;
+ }
+ }
+
const messageRepository = this.workspaceOrmManager.getRepository(
MessageWorkspaceEntity,
{ shouldBypassPermissionChecks: true },
);
- const sendContext = await this.loadSendContext({ data });
+ const sendContext = await this.loadSendContext({ data, campaign });
if (!isDefined(sendContext)) {
return;
}
- await this.deliverMessage({ data, messageRepository, sendContext });
+ await this.deliverMessage({
+ data,
+ messageRepository,
+ sendContext,
+ creditContext,
+ });
await this.messageCampaignLifecycleService.finalizeCampaignIfComplete({
workspaceId,
@@ -74,13 +141,9 @@ export class MessageCampaignDeliveryService {
}, buildSystemAuthContext(workspaceId));
}
- private async loadSendContext({
- data,
- }: {
- data: SendCampaignEmailJobData;
- }): Promise<SendContext | null> {
- const { workspaceId, campaignId, messageId, personId } = data;
-
+ private async findRunningCampaign(
+ campaignId: string,
+ ): Promise<MessageCampaignWorkspaceEntity | null> {
const campaignRepository = this.workspaceOrmManager.getRepository(
MessageCampaignWorkspaceEntity,
{ shouldBypassPermissionChecks: true },
@@ -97,6 +160,130 @@ export class MessageCampaignDeliveryService {
return null;
}
+ return campaign;
+ }
+
+ private async findSendSlotRefusal(
+ workspaceId: string,
+ ): Promise<SendSlotRefusal | null> {
+ try {
+ await this.usageLimitSpeedService.consumeOrThrow({
+ resourceType: UsageResourceType.EMAIL,
+ operationType: UsageOperationType.EMAIL_SEND,
+ authContext: buildSystemAuthContext(workspaceId),
+ });
+
+ return null;
+ } catch (error) {
+ if (
+ !(error instanceof UsageLimitException) ||
+ error.code !== UsageLimitExceptionCode.RATE_LIMITED
+ ) {
+ throw error;
+ }
+
+ return {
+ retryDelayMs: Math.max(
+ error.exhaustedScope?.retryAfterMs ?? 0,
+ SEND_SLOT_RETRY.minDelayMs,
+ ),
+ windowMs: (error.exhaustedScope?.windowSeconds ?? 0) * 1000,
+ };
+ }
+ }
+
+ private async requeueRateLimitedSendJob({
+ data,
+ refusal: { retryDelayMs, windowMs },
+ }: {
+ data: SendCampaignEmailJobData;
+ refusal: SendSlotRefusal;
+ }): Promise<void> {
+ const attemptCount = (data.rateLimitedAttemptCount ?? 0) + 1;
+
+ if (attemptCount > SEND_SLOT_RETRY.attemptLimit) {
+ await this.failRateLimitedDelivery({
+ workspaceId: data.workspaceId,
+ campaignId: data.campaignId,
+ messageId: data.messageId,
+ });
+
+ return;
+ }
+
+ const backoffCeilingMs = Math.min(
+ windowMs * SEND_SLOT_RETRY.maxWindows,
+ SEND_SLOT_RETRY.maxDelayMs,
+ );
+
+ const backoffMs = Math.min(
+ retryDelayMs * 2 ** (attemptCount - 1),
+ Math.max(backoffCeilingMs, SEND_SLOT_RETRY.minDelayMs),
+ );
+
+ await this.messageQueueService.add<SendCampaignEmailJobData>(
+ SEND_CAMPAIGN_EMAIL_JOB,
+ { ...data, rateLimitedAttemptCount: attemptCount },
+ {
+ delay: Math.ceil(
+ backoffMs * (1 + Math.random() * SEND_SLOT_RETRY.jitterRatio),
+ ),
+ retryLimit: CAMPAIGN_SEND_RETRY_LIMIT,
+ backoff: CAMPAIGN_SEND_RETRY_BACKOFF,
+ },
+ );
+ }
+
+ private async failRateLimitedDelivery({
+ workspaceId,
+ campaignId,
+ messageId,
+ }: {
+ workspaceId: string;
+ campaignId: string;
+ messageId: string;
+ }): Promise<void> {
+ const { affected } = await this.campaignDeliveryRepository.update(
+ workspaceId,
+ {
+ id: messageId,
+ state: In([
+ CAMPAIGN_DELIVERY_STATE.QUEUED,
+ CAMPAIGN_DELIVERY_STATE.FAILED,
+ ]),
+ },
+ {
+ state: CAMPAIGN_DELIVERY_STATE.FAILED,
+ failureReason: CAMPAIGN_FAILURE_REASON.RATE_LIMITED,
+ },
+ );
+
+ if (affected === 1) {
+ this.logger.warn(
+ `Campaign ${campaignId} of workspace ${workspaceId} gave up on message ${messageId} after ${SEND_SLOT_RETRY.attemptLimit} refused send slots`,
+ );
+ }
+
+ await this.messageCampaignLifecycleService.finalizeCampaignIfComplete({
+ workspaceId,
+ campaignId,
+ });
+ }
+
+ private async loadSendContext({
+ data,
+ campaign,
+ }: {
+ data: SendCampaignEmailJobData;
+ campaign: MessageCampaignWorkspaceEntity;
+ }): Promise<SendContext | null> {
+ const { workspaceId, campaignId, messageId, personId } = data;
+
+ const campaignRepository = this.workspaceOrmManager.getRepository(
+ MessageCampaignWorkspaceEntity,
+ { shouldBypassPermissionChecks: true },
+ );
+
const claimToken = await this.claimDeliveryForSending({
workspaceId,
messageId,
@@ -141,10 +328,12 @@ export class MessageCampaignDeliveryService {
data,
messageRepository,
sendContext: { campaign, person, claimToken },
+ creditContext: { hasCredits, currentBillingSubscription },
}: {
data: SendCampaignEmailJobData;
- messageRepository: MessageRepository;
+ messageRepository: WorkspaceRepository<MessageWorkspaceEntity>;
sendContext: SendContext;
+ creditContext: EmailCreditContext;
}): Promise<void> {
const {
workspaceId,
@@ -152,23 +341,10 @@ export class MessageCampaignDeliveryService {
messageId,
recipientEmail,
emailingDomainId,
+ userWorkspaceId,
} = data;
- const variables =
- await this.campaignVariableService.buildVariablesForPerson(
- workspaceId,
- person,
- );
- const { subject, html, plainText } = await renderCampaignEmail({
- subjectTemplate: campaign.subject ?? '',
- bodyTemplate: campaign.bodyTemplate ?? '',
- variables,
- });
-
- const hasEmailCredits =
- await this.emailBillingService.hasEmailCredits(workspaceId);
-
- if (!hasEmailCredits) {
+ if (!hasCredits) {
await this.settleClaimedDelivery({
workspaceId,
messageId,
@@ -182,6 +358,17 @@ export class MessageCampaignDeliveryService {
return;
}
+ const variables =
+ await this.campaignVariableService.buildVariablesForPerson(
+ workspaceId,
+ person,
+ );
+ const { subject, html, plainText } = await renderCampaignEmail({
+ subjectTemplate: campaign.subject ?? '',
+ bodyTemplate: campaign.bodyTemplate ?? '',
+ variables,
+ });
+
const result = await this.sendOrRecordFailure({
messageId,
claimToken,
@@ -194,6 +381,7 @@ export class MessageCampaignDeliveryService {
subject,
text: plainText,
html,
+ sendKind: 'MARKETING',
unsubscribeTopicId: campaign.unsubscribeTopicId ?? undefined,
},
});
@@ -202,12 +390,6 @@ export class MessageCampaignDeliveryService {
return;
}
- await messageRepository.update(messageId, {
- headerMessageId: result.messageId,
- subject,
- text: plainText,
- });
-
const affected = await this.settleClaimedDelivery({
workspaceId,
messageId,
@@ -216,6 +398,8 @@ export class MessageCampaignDeliveryService {
state: CAMPAIGN_DELIVERY_STATE.SENT,
providerMessageId: result.messageId,
sentAt: new Date(),
+ failureReason: null,
+ skipReason: null,
},
});
@@ -227,11 +411,27 @@ export class MessageCampaignDeliveryService {
return;
}
- await this.emailBillingService.billSentEmails({
- workspaceId,
- sentEmailCount: 1,
+ await messageRepository.update(messageId, {
+ headerMessageId: result.messageId,
+ subject,
+ text: plainText,
});
+ await this.emailBillingService
+ .billSentEmails({
+ workspaceId,
+ sentEmailCount: 1,
+ userWorkspaceId,
+ currentBillingSubscription,
+ })
+ .catch((error) => {
+ this.logger.error(
+ `Campaign ${campaignId} delivered message ${messageId} but failed to bill it, so this send is unbilled: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ });
+
await this.linkMessageToProviderThread({
messageId,
providerMessageId: result.messageId,
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-lifecycle.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-lifecycle.service.ts
index 75b669bef6f..9fc865da98f 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign-lifecycle.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-lifecycle.service.ts
@@ -1,7 +1,5 @@
import { Injectable } from '@nestjs/common';
-import { type QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
-
import { CampaignDeliveryEntity } from 'src/engine/core-modules/emailing-domain/campaign-delivery.entity';
import { CAMPAIGN_DELIVERY_STATE } from 'src/engine/core-modules/emailing-domain/constants/campaign-delivery-state.constant';
import { CAMPAIGN_FAILURE_REASON } from 'src/engine/core-modules/emailing-domain/constants/campaign-failure-reason.constant';
@@ -11,21 +9,10 @@ import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scope
import { type FindOptionsWhere, In, LessThan } from 'typeorm';
-import {
- CAMPAIGN_STATS_REFRESH_DELAY_MS,
- REFRESH_CAMPAIGN_STATS_JOB,
-} from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
import {
EmailingDomainException,
EmailingDomainExceptionCode,
} from 'src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception';
-import { type RefreshCampaignStatsJobData } from 'src/engine/core-modules/emailing-domain/types/refresh-campaign-stats-job-data.type';
-import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decorators/cache-storage.decorator';
-import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
-import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
-import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
-import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
-import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
import { UserRoleService } from 'src/engine/metadata-modules/user-role/user-role.service';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
@@ -51,10 +38,6 @@ export class MessageCampaignLifecycleService {
private readonly workspaceOrmManager: WorkspaceOrmManager,
private readonly userRoleService: UserRoleService,
private readonly messageCampaignStatisticsService: MessageCampaignStatisticsService,
- @InjectMessageQueue(MessageQueue.campaignQueue)
- private readonly messageQueueService: MessageQueueService,
- @InjectCacheStorage(CacheStorageNamespace.ModuleEmailing)
- private readonly cacheStorageService: CacheStorageService,
) {}
async transitionCampaignStatus({
@@ -125,7 +108,10 @@ export class MessageCampaignLifecycleService {
},
});
- await this.scheduleStatsRefresh({ workspaceId, campaignId });
+ await this.messageCampaignStatisticsService.scheduleRefresh({
+ workspaceId,
+ campaignId,
+ });
return { campaignId, canceledMessageCount };
}
@@ -160,7 +146,16 @@ export class MessageCampaignLifecycleService {
}: {
workspaceId: string;
criteria: FindOptionsWhere<CampaignDeliveryEntity>;
- update: QueryDeepPartialEntity<CampaignDeliveryEntity>;
+ update: Partial<
+ Pick<
+ CampaignDeliveryEntity,
+ | 'state'
+ | 'skipReason'
+ | 'failureReason'
+ | 'claimToken'
+ | 'claimExpiresAt'
+ >
+ >;
}): Promise<number> {
const { affected } = await this.campaignDeliveryRepository.update(
workspaceId,
@@ -178,6 +173,22 @@ export class MessageCampaignLifecycleService {
workspaceId: string;
campaignId: string;
}): Promise<void> {
+ // Every settled delivery calls this, so the check must not scale with the
+ // campaign. Counting reads every unfinished row only to compare it against
+ // zero; the probe stops at the first row the partial index yields.
+ const hasUnfinishedDelivery =
+ await this.campaignDeliveryRepository.existsBy(workspaceId, {
+ campaignId,
+ state: In([
+ CAMPAIGN_DELIVERY_STATE.QUEUED,
+ CAMPAIGN_DELIVERY_STATE.SENDING,
+ ]),
+ });
+
+ if (hasUnfinishedDelivery) {
+ return;
+ }
+
const counts =
await this.messageCampaignStatisticsService.countDeliveriesByState({
workspaceId,
@@ -210,29 +221,10 @@ export class MessageCampaignLifecycleService {
);
}, buildSystemAuthContext(workspaceId));
- await this.scheduleStatsRefresh({ workspaceId, campaignId });
- }
-
- async scheduleStatsRefresh({
- workspaceId,
- campaignId,
- }: {
- workspaceId: string;
- campaignId: string;
- }): Promise<void> {
- const acquired = await this.cacheStorageService.acquireLock(
- `campaign-stats-refresh:${workspaceId}:${campaignId}`,
- CAMPAIGN_STATS_REFRESH_DELAY_MS,
- );
-
- if (!acquired) {
- return;
- }
-
- await this.messageQueueService.add<RefreshCampaignStatsJobData>(
- REFRESH_CAMPAIGN_STATS_JOB,
- { workspaceId, campaignId },
- { delay: CAMPAIGN_STATS_REFRESH_DELAY_MS },
- );
+ await this.messageCampaignStatisticsService.persistCampaignCounts({
+ workspaceId,
+ campaignId,
+ counts,
+ });
}
}
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-materialization.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-materialization.service.ts
index bbd6a5e6301..c54d7f5b0f4 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign-materialization.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-materialization.service.ts
@@ -8,7 +8,7 @@ import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import chunk from 'lodash.chunk';
-import { In } from 'typeorm';
+import { In, type ObjectLiteral } from 'typeorm';
import { v4 } from 'uuid';
import {
@@ -70,6 +70,7 @@ export class MessageCampaignMaterializationService {
campaignId,
messageChannelId,
emailingDomainId,
+ userWorkspaceId,
recipients,
}: MaterializeCampaignJobData): Promise<void> {
await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
@@ -122,6 +123,7 @@ export class MessageCampaignMaterializationService {
campaignId,
messageChannelId,
emailingDomainId,
+ userWorkspaceId,
recipientsToCreate,
recipientsStrandedByAnEarlierAttempt,
});
@@ -143,6 +145,7 @@ export class MessageCampaignMaterializationService {
campaignId,
messageChannelId,
emailingDomainId,
+ userWorkspaceId,
recipientsToCreate,
recipientsStrandedByAnEarlierAttempt,
}: {
@@ -150,6 +153,7 @@ export class MessageCampaignMaterializationService {
campaignId: string;
messageChannelId: string;
emailingDomainId: string;
+ userWorkspaceId: string;
recipientsToCreate: CampaignMessageRecipient[];
recipientsStrandedByAnEarlierAttempt: CampaignMessageRecipient[];
}): Promise<number> {
@@ -168,6 +172,7 @@ export class MessageCampaignMaterializationService {
campaignId,
messageChannelId,
emailingDomainId,
+ userWorkspaceId,
receivedAtIso,
shouldCreateMessages,
recipients,
@@ -191,6 +196,7 @@ export class MessageCampaignMaterializationService {
campaignId,
messageChannelId,
emailingDomainId,
+ userWorkspaceId,
receivedAtIso,
shouldCreateMessages,
recipients,
@@ -238,6 +244,7 @@ export class MessageCampaignMaterializationService {
workspaceId,
campaignId,
emailingDomainId,
+ userWorkspaceId,
recipients,
});
@@ -315,11 +322,13 @@ export class MessageCampaignMaterializationService {
workspaceId,
campaignId,
emailingDomainId,
+ userWorkspaceId,
recipients,
}: {
workspaceId: string;
campaignId: string;
emailingDomainId: string;
+ userWorkspaceId: string;
recipients: CampaignMessageRecipient[];
}): Promise<void> {
if (recipients.length === 0) {
@@ -335,6 +344,7 @@ export class MessageCampaignMaterializationService {
personId: recipient.personId,
recipientEmail: recipient.email,
emailingDomainId,
+ userWorkspaceId,
})),
{
retryLimit: CAMPAIGN_SEND_RETRY_LIMIT,
@@ -409,75 +419,64 @@ export class MessageCampaignMaterializationService {
}): Promise<void> {
await this.workspaceOrmManager.runInWorkspaceTransaction(
async (transactionScope) => {
- await transactionScope
- .getRepository<MessageThreadWorkspaceEntity>(
- 'messageThread',
+ const repositoryFor = <T extends ObjectLiteral>(objectName: string) =>
+ transactionScope.getRepository<T>(
+ objectName,
{ shouldBypassPermissionChecks: true },
SKIP_EVENT_EMISSION,
- )
- .insert(rows.map((row) => ({ id: row.threadId })));
-
- await transactionScope
- .getRepository<MessageWorkspaceEntity>(
- 'message',
- { shouldBypassPermissionChecks: true },
- SKIP_EVENT_EMISSION,
- )
- .insert(
- rows.map((row) => ({
- id: row.messageId,
- headerMessageId: row.temporaryExternalId,
- subject: subjectTemplate,
- text,
- receivedAt: now,
- messageThreadId: row.threadId,
- messageCampaignId: campaignId,
- })),
);
- await transactionScope
- .getRepository<MessageChannelMessageAssociationWorkspaceEntity>(
- 'messageChannelMessageAssociation',
- { shouldBypassPermissionChecks: true },
- SKIP_EVENT_EMISSION,
- )
- .insert(
- rows.map((row) => ({
+ await repositoryFor<MessageThreadWorkspaceEntity>(
+ 'messageThread',
+ ).insert(rows.map((row) => ({ id: row.threadId })));
+
+ await repositoryFor<MessageWorkspaceEntity>('message').insert(
+ rows.map((row) => ({
+ id: row.messageId,
+ headerMessageId: row.temporaryExternalId,
+ subject: subjectTemplate,
+ text,
+ receivedAt: now,
+ messageThreadId: row.threadId,
+ messageCampaignId: campaignId,
+ })),
+ );
+
+ await repositoryFor<MessageChannelMessageAssociationWorkspaceEntity>(
+ 'messageChannelMessageAssociation',
+ ).insert(
+ rows.map((row) => ({
+ id: v4(),
+ messageId: row.messageId,
+ messageChannelId,
+ messageExternalId: row.temporaryExternalId,
+ messageThreadExternalId: row.temporaryExternalId,
+ direction: MessageDirection.OUTGOING,
+ })),
+ );
+
+ await repositoryFor<MessageParticipantWorkspaceEntity>(
+ 'messageParticipant',
+ ).insert(
+ rows.flatMap((row) => [
+ {
id: v4(),
messageId: row.messageId,
- messageChannelId,
- messageExternalId: row.temporaryExternalId,
- messageThreadExternalId: row.temporaryExternalId,
- direction: MessageDirection.OUTGOING,
- })),
- );
-
- await transactionScope
- .getRepository<MessageParticipantWorkspaceEntity>(
- 'messageParticipant',
- { shouldBypassPermissionChecks: true },
- SKIP_EVENT_EMISSION,
- )
- .insert(
- rows.flatMap((row) => [
- {
- id: v4(),
- messageId: row.messageId,
- role: MessageParticipantRole.FROM,
- handle: fromAddress,
- displayName: fromAddress,
- },
- {
- id: v4(),
- messageId: row.messageId,
- role: MessageParticipantRole.TO,
- handle: row.recipient.email,
- displayName: row.recipient.email,
- personId: row.recipient.personId,
- messageCampaignId: campaignId,
- },
- ]),
- );
+ role: MessageParticipantRole.FROM,
+ handle: fromAddress,
+ displayName: fromAddress,
+ },
+ {
+ id: v4(),
+ messageId: row.messageId,
+ role: MessageParticipantRole.TO,
+ handle: row.recipient.email,
+ displayName: row.recipient.email,
+ personId: row.recipient.personId,
+ messageCampaignId: campaignId,
+ },
+ ]),
+ );
},
);
}
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-statistics.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-statistics.service.ts
index 941025386a3..e4123f6b5ae 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign-statistics.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-statistics.service.ts
@@ -1,23 +1,81 @@
+import { CAMPAIGN_JOB_RETRY_LIMIT } from 'src/engine/core-modules/emailing-domain/constants/campaign-job-retry-limit.constant';
import { Injectable } from '@nestjs/common';
+import { fastDeepEqual, isDefined } from 'twenty-shared/utils';
+
+import { MoreThanOrEqual } from 'typeorm';
+import { MessageCampaignStatus } from 'twenty-shared/types';
+
+import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decorators/cache-storage.decorator';
+import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
+import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
+import {
+ CAMPAIGN_STATS_REFRESH_DEBOUNCE_MS,
+ REFRESH_CAMPAIGN_STATS_JOB,
+} from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
+import { type RefreshCampaignStatsJobData } from 'src/engine/core-modules/emailing-domain/types/refresh-campaign-stats-job-data.type';
import { CampaignDeliveryEntity } from 'src/engine/core-modules/emailing-domain/campaign-delivery.entity';
import { type CampaignCountGroup } from 'src/engine/core-modules/emailing-domain/types/campaign-count-group.type';
import { type CampaignCounts } from 'src/engine/core-modules/emailing-domain/types/campaign-counts.type';
import { computeCampaignCounts } from 'src/engine/core-modules/emailing-domain/utils/compute-campaign-counts.util';
-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { MessageCampaignWorkspaceEntity } from 'src/modules/emailing/standard-objects/message-campaign.workspace-entity';
+const RECONCILIATION_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
+const REFRESH_LOCK_TTL_MS = CAMPAIGN_STATS_REFRESH_DEBOUNCE_MS + 2_000;
+
@Injectable()
export class MessageCampaignStatisticsService {
constructor(
@InjectWorkspaceScopedRepository(CampaignDeliveryEntity)
private readonly campaignDeliveryRepository: WorkspaceScopedRepository<CampaignDeliveryEntity>,
private readonly workspaceOrmManager: WorkspaceOrmManager,
+ @InjectMessageQueue(MessageQueue.campaignQueue)
+ private readonly messageQueueService: MessageQueueService,
+ @InjectCacheStorage(CacheStorageNamespace.ModuleEmailing)
+ private readonly cacheStorageService: CacheStorageService,
) {}
+ async scheduleRefresh({
+ workspaceId,
+ campaignId,
+ }: {
+ workspaceId: string;
+ campaignId: string;
+ }): Promise<void> {
+ const lockKey = `campaign-stats-refresh:${workspaceId}:${campaignId}`;
+
+ const acquired = await this.cacheStorageService.acquireLock(
+ lockKey,
+ REFRESH_LOCK_TTL_MS,
+ );
+
+ if (!acquired) {
+ return;
+ }
+
+ await this.messageQueueService
+ .add<RefreshCampaignStatsJobData>(
+ REFRESH_CAMPAIGN_STATS_JOB,
+ { workspaceId, campaignId },
+ {
+ delay: CAMPAIGN_STATS_REFRESH_DEBOUNCE_MS,
+ retryLimit: CAMPAIGN_JOB_RETRY_LIMIT,
+ },
+ )
+ .catch(async (error) => {
+ await this.cacheStorageService.releaseLock(lockKey);
+
+ throw error;
+ });
+ }
+
async countDeliveriesByState({
workspaceId,
campaignId,
@@ -32,6 +90,10 @@ export class MessageCampaignStatisticsService {
.addSelect('COUNT(delivery."deliveredAt")', 'deliveredCount')
.addSelect('COUNT(delivery."bouncedAt")', 'bouncedCount')
.addSelect('COUNT(delivery."complainedAt")', 'complainedCount')
+ .addSelect(
+ `COUNT(*) FILTER (WHERE delivery."rejectedAt" IS NOT NULL OR delivery."renderingFailedAt" IS NOT NULL)`,
+ 'providerFailedCount',
+ )
.where('delivery."workspaceId" = :workspaceId', { workspaceId })
.andWhere('delivery."campaignId" = :campaignId', { campaignId })
.groupBy('delivery.state')
@@ -40,6 +102,9 @@ export class MessageCampaignStatisticsService {
return computeCampaignCounts({ groups });
}
+ // The refresh lock is left to expire instead of being released here: a
+ // backed-up queue can start this job after the lock TTL, and deleting the key
+ // then would drop the lock a newer schedule already owns.
async refreshCampaignCounts({
workspaceId,
campaignId,
@@ -52,23 +117,96 @@ export class MessageCampaignStatisticsService {
campaignId,
});
+ await this.persistCampaignCounts({ workspaceId, campaignId, counts });
+ }
+
+ async reconcileWorkspaceCampaignCounts({
+ workspaceId,
+ }: {
+ workspaceId: string;
+ }): Promise<void> {
+ const campaignIds =
+ await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ const campaignRepository = this.workspaceOrmManager.getRepository(
+ MessageCampaignWorkspaceEntity,
+ { shouldBypassPermissionChecks: true },
+ );
+
+ const campaigns = await campaignRepository.find({
+ where: [
+ { status: MessageCampaignStatus.SENDING },
+ {
+ sentAt: MoreThanOrEqual(
+ new Date(Date.now() - RECONCILIATION_WINDOW_MS),
+ ),
+ },
+ ],
+ select: { id: true },
+ });
+
+ return campaigns.map((campaign) => campaign.id);
+ }, buildSystemAuthContext(workspaceId));
+
+ for (const campaignId of campaignIds) {
+ await this.refreshCampaignCounts({ workspaceId, campaignId });
+ }
+ }
+
+ async persistCampaignCounts({
+ workspaceId,
+ campaignId,
+ counts,
+ }: {
+ workspaceId: string;
+ campaignId: string;
+ counts: CampaignCounts;
+ }): Promise<void> {
await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
const campaignRepository = this.workspaceOrmManager.getRepository(
MessageCampaignWorkspaceEntity,
{ shouldBypassPermissionChecks: true },
);
- await campaignRepository.update(
- { id: campaignId },
- {
- sentCount: counts.sentCount,
- deliveredCount: counts.deliveredCount,
- failedCount: counts.failedCount,
- skippedCount: counts.skippedCount,
- bouncedCount: counts.bouncedCount,
- complainedCount: counts.complainedCount,
+ const campaign = await campaignRepository.findOne({
+ where: { id: campaignId },
+ select: {
+ id: true,
+ sentCount: true,
+ deliveredCount: true,
+ failedCount: true,
+ skippedCount: true,
+ bouncedCount: true,
+ complainedCount: true,
},
- );
+ });
+
+ if (!isDefined(campaign)) {
+ return;
+ }
+
+ const nextCounts = {
+ sentCount: counts.sentCount,
+ deliveredCount: counts.deliveredCount,
+ failedCount: counts.failedCount,
+ skippedCount: counts.skippedCount,
+ bouncedCount: counts.bouncedCount,
+ complainedCount: counts.complainedCount,
+ };
+
+ const storedCounts = {
+ sentCount: campaign.sentCount,
+ deliveredCount: campaign.deliveredCount,
+ failedCount: campaign.failedCount,
+ skippedCount: campaign.skippedCount,
+ bouncedCount: campaign.bouncedCount,
+ complainedCount: campaign.complainedCount,
+ };
+
+ if (fastDeepEqual(storedCounts, nextCounts)) {
+ return;
+ }
+
+ await campaignRepository.update({ id: campaignId }, nextCounts);
}, buildSystemAuthContext(workspaceId));
}
}
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts
index 4dc13704f14..2740811e1a8 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts
@@ -1,5 +1,6 @@
import { CAMPAIGN_SEND_RETRY_LIMIT } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-limit.constant';
import { CAMPAIGN_SEND_RETRY_BACKOFF } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant';
+import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';
import { Injectable } from '@nestjs/common';
import { isNonEmptyString } from '@sniptt/guards';
@@ -13,9 +14,8 @@ import {
EmailingDomainExceptionCode,
} from 'src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception';
import { type EmailingDomainSendEmailResult } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-email-result.type';
-import { CampaignDeliveryEntity } from 'src/engine/core-modules/emailing-domain/campaign-delivery.entity';
import { EmailingDomainEntity } from 'src/engine/core-modules/emailing-domain/emailing-domain.entity';
-import { type CampaignSkippedBreakdown } from 'src/engine/core-modules/emailing-domain/types/campaign-skipped-breakdown.type';
+import { type CampaignAudienceResolution } from 'src/engine/core-modules/emailing-domain/types/campaign-audience-resolution.type';
import { type MaterializeCampaignJobData } from 'src/engine/core-modules/emailing-domain/types/materialize-campaign-job-data.type';
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
@@ -26,6 +26,7 @@ import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { CampaignVariableService } from 'src/modules/emailing/services/campaign-variable.service';
+import { EmailBillingService } from 'src/modules/emailing/services/email-billing.service';
import { EmailingDomainSenderService } from 'src/modules/emailing/services/emailing-domain-sender.service';
import { MessageCampaignAudienceService } from 'src/modules/emailing/services/message-campaign-audience.service';
import { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';
@@ -40,18 +41,18 @@ import { getDomainFromEmail } from 'src/utils/get-domain-from-email';
type SendCampaignResult = {
campaignId: string;
queuedCount: number;
- skipped: CampaignSkippedBreakdown;
+ audience: CampaignAudienceResolution['audience'];
};
type SendableDraftCampaign = z.infer<typeof sendableDraftCampaignSchema>;
+const TEST_SEND_THROTTLE = { maxRequests: 3, windowMs: 24 * 60 * 60 * 1000 };
+
@Injectable()
export class MessageCampaignService {
constructor(
@InjectWorkspaceScopedRepository(EmailingDomainEntity)
private readonly emailingDomainRepository: WorkspaceScopedRepository<EmailingDomainEntity>,
- @InjectWorkspaceScopedRepository(CampaignDeliveryEntity)
- private readonly campaignDeliveryRepository: WorkspaceScopedRepository<CampaignDeliveryEntity>,
private readonly emailingDomainSenderService: EmailingDomainSenderService,
private readonly workspaceOrmManager: WorkspaceOrmManager,
@InjectMessageQueue(MessageQueue.campaignQueue)
@@ -61,6 +62,8 @@ export class MessageCampaignService {
private readonly campaignVariableService: CampaignVariableService,
private readonly messageCampaignAudienceService: MessageCampaignAudienceService,
private readonly messageCampaignLifecycleService: MessageCampaignLifecycleService,
+ private readonly throttlerService: ThrottlerService,
+ private readonly emailBillingService: EmailBillingService,
) {}
async send({
@@ -77,16 +80,20 @@ export class MessageCampaignService {
userWorkspaceId,
});
- const { fromAddress, listId } =
+ const { fromAddress, listId, unsubscribeTopicId } =
await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const { fromAddress, listId } =
+ const { fromAddress, listId, unsubscribeTopicId } =
await this.findSendableDraftCampaignOrThrow({
workspaceId,
campaignId,
roleId,
});
- return { fromAddress: fromAddress.primaryEmail, listId };
+ return {
+ fromAddress: fromAddress.primaryEmail,
+ listId,
+ unsubscribeTopicId,
+ };
});
const emailingDomain = await this.findSendReadyEmailingDomainOrThrow({
@@ -94,13 +101,24 @@ export class MessageCampaignService {
fromAddress,
});
- const { recipients, skipped } =
+ const { sendableRecipients, audience } =
await this.messageCampaignAudienceService.resolveNormalizedAudience({
workspaceId,
listId,
roleId,
+ unsubscribeTopicId: unsubscribeTopicId ?? undefined,
});
+ const { hasCredits } =
+ await this.emailBillingService.resolveEmailCreditContext(workspaceId);
+
+ if (sendableRecipients.length > 0 && !hasCredits) {
+ throw new EmailingDomainException(
+ `Campaign ${campaignId} cannot be sent to ${sendableRecipients.length} recipient(s) because the workspace has no email credits left`,
+ EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_INSUFFICIENT_CREDITS,
+ );
+ }
+
const messageChannel =
await this.messageChannelMetadataService.getOrCreateEmailGroupChannel({
fromAddress,
@@ -132,7 +150,8 @@ export class MessageCampaignService {
campaignId,
messageChannelId: messageChannel.id,
emailingDomainId: emailingDomain.id,
- recipients,
+ userWorkspaceId,
+ recipients: sendableRecipients,
},
{
retryLimit: CAMPAIGN_SEND_RETRY_LIMIT,
@@ -151,7 +170,11 @@ export class MessageCampaignService {
throw error;
});
- return { campaignId, queuedCount: recipients.length, skipped };
+ return {
+ campaignId,
+ queuedCount: sendableRecipients.length,
+ audience,
+ };
}
async sendTest({
@@ -185,6 +208,13 @@ export class MessageCampaignService {
variables,
});
+ await this.throttlerService.tokenBucketThrottleOrThrow(
+ `message-campaign-test-send:throttler:${workspaceId}`,
+ 1,
+ TEST_SEND_THROTTLE.maxRequests,
+ TEST_SEND_THROTTLE.windowMs,
+ );
+
return this.emailingDomainSenderService.sendEmail(
workspaceId,
emailingDomain.id,
@@ -194,6 +224,7 @@ export class MessageCampaignService {
subject: rendered.subject,
text: rendered.plainText,
html: rendered.html,
+ sendKind: 'MARKETING',
unsubscribeTopicId,
},
);
diff --git a/packages/twenty-server/src/modules/emailing/services/message-suppression.service.ts b/packages/twenty-server/src/modules/emailing/services/message-suppression.service.ts
index c411bf8a577..a3d6d1b0e7a 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-suppression.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-suppression.service.ts
@@ -6,18 +6,20 @@ import {
isDefined,
isNonEmptyArray,
} from 'twenty-shared/utils';
-import { ILike, In, IsNull, QueryFailedError } from 'typeorm';
+import { ILike, In, IsNull, Not, QueryFailedError } from 'typeorm';
import { POSTGRESQL_ERROR_CODES } from 'src/engine/api/graphql/workspace-query-runner/constants/postgres-error-codes.constants';
import { type QueryFailedErrorWithCode } from 'src/engine/api/graphql/workspace-query-runner/utils/workspace-query-runner-graphql-api-exception-handler.util';
+import { HARD_SUPPRESSION_REASONS } from 'src/engine/core-modules/emailing-domain/constants/hard-suppression-reasons.constant';
import {
- GLOBAL_BLOCKING_SUPPRESSION_REASONS,
- HARD_SUPPRESSION_REASONS,
-} from 'src/engine/core-modules/emailing-domain/constants/hard-suppression-reasons.constant';
+ EmailingDomainException,
+ EmailingDomainExceptionCode,
+} from 'src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception';
import { MessageSuppressionEntity } from 'src/engine/core-modules/emailing-domain/message-suppression.entity';
import { MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
import { MessageSuppressionSource } from 'src/engine/core-modules/emailing-domain/types/message-suppression-source.type';
import { type TopicOptOutState } from 'src/engine/core-modules/emailing-domain/types/topic-opt-out-state.type';
+import { type UnsubscribeTopicEntity } from 'src/engine/core-modules/emailing-domain/unsubscribe-topic.entity';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { UnsubscribeTopicService } from 'src/modules/emailing/services/unsubscribe-topic.service';
@@ -31,6 +33,12 @@ type FindSuppressionsArgs = {
offset: number;
};
+type FindApplicableSuppressionsArgs = {
+ workspaceId: string;
+ emailAddresses: string[];
+ unsubscribeTopicId?: string;
+};
+
type SuppressArgs = {
workspaceId: string;
emailAddress: string;
@@ -40,6 +48,17 @@ type SuppressArgs = {
unsubscribeTopicId?: string | null;
};
+type SuppressManuallyArgs = {
+ workspaceId: string;
+ emailAddress: string;
+ unsubscribeTopicId?: string;
+};
+
+type RemoveSuppressionArgs = {
+ workspaceId: string;
+ suppressionId: string;
+};
+
type TopicOptOutStateArgs = {
workspaceId: string;
emailAddress: string;
@@ -49,6 +68,7 @@ type SetTopicOptOutsArgs = {
workspaceId: string;
emailAddress: string;
keptTopicIds: string[];
+ canResubscribe: boolean;
};
@Injectable()
@@ -91,50 +111,28 @@ export class MessageSuppressionService {
return { records, totalCount };
}
- async getSuppressedAddresses(
- workspaceId: string,
- emailAddresses: string[],
- ): Promise<Set<string>> {
+ async findApplicableSuppressions({
+ workspaceId,
+ emailAddresses,
+ unsubscribeTopicId,
+ }: FindApplicableSuppressionsArgs): Promise<MessageSuppressionEntity[]> {
const normalizedAddresses = this.normalizeAddresses(emailAddresses);
if (!isNonEmptyArray(normalizedAddresses)) {
- return new Set();
- }
-
- const suppressions = await this.suppressionRepository.find(workspaceId, {
- where: {
- emailAddress: In(normalizedAddresses),
- reason: In(GLOBAL_BLOCKING_SUPPRESSION_REASONS),
- unsubscribeTopicId: IsNull(),
- },
- });
-
- return new Set(suppressions.map((suppression) => suppression.emailAddress));
- }
-
- async getTopicSuppressedAddresses(
- workspaceId: string,
- emailAddresses: string[],
- unsubscribeTopicId: string,
- ): Promise<Set<string>> {
- const normalizedAddresses = this.normalizeAddresses(emailAddresses);
-
- if (
- !isNonEmptyArray(normalizedAddresses) ||
- !isNonEmptyString(unsubscribeTopicId)
- ) {
- return new Set();
+ return [];
}
- const suppressions = await this.suppressionRepository.find(workspaceId, {
- where: {
- emailAddress: In(normalizedAddresses),
- reason: MessageSuppressionReason.UNSUBSCRIBE,
- unsubscribeTopicId,
- },
+ return this.suppressionRepository.find(workspaceId, {
+ where: [
+ {
+ emailAddress: In(normalizedAddresses),
+ unsubscribeTopicId: IsNull(),
+ },
+ ...(isNonEmptyString(unsubscribeTopicId)
+ ? [{ emailAddress: In(normalizedAddresses), unsubscribeTopicId }]
+ : []),
+ ],
});
-
- return new Set(suppressions.map((suppression) => suppression.emailAddress));
}
async suppress({
@@ -151,9 +149,6 @@ export class MessageSuppressionService {
return;
}
- // Hard suppressions (delivery failures) are inherently address-level: a
- // topic-scoped BOUNCE/COMPLAINT row would block nothing (reads filter
- // per-topic rows to UNSUBSCRIBE) while occupying the (address, topic) slot.
const effectiveTopicId = HARD_SUPPRESSION_REASONS.includes(reason)
? null
: unsubscribeTopicId;
@@ -210,6 +205,66 @@ export class MessageSuppressionService {
}
}
+ async suppressManually({
+ workspaceId,
+ emailAddress,
+ unsubscribeTopicId,
+ }: SuppressManuallyArgs): Promise<MessageSuppressionEntity> {
+ await this.recordUnsubscribe({
+ workspaceId,
+ emailAddress,
+ unsubscribeTopicId,
+ });
+
+ const suppression = await this.suppressionRepository.findOneBy(
+ workspaceId,
+ {
+ emailAddress: this.normalizeEmailAddress(emailAddress),
+ unsubscribeTopicId: isNonEmptyString(unsubscribeTopicId)
+ ? unsubscribeTopicId
+ : IsNull(),
+ },
+ );
+
+ if (!isDefined(suppression)) {
+ throw new EmailingDomainException(
+ `Suppression for ${emailAddress} was not persisted`,
+ EmailingDomainExceptionCode.MESSAGE_SUPPRESSION_NOT_FOUND,
+ );
+ }
+
+ return suppression;
+ }
+
+ async removeSuppression({
+ workspaceId,
+ suppressionId,
+ }: RemoveSuppressionArgs): Promise<void> {
+ const suppression = await this.suppressionRepository.findOneBy(
+ workspaceId,
+ { id: suppressionId },
+ );
+
+ if (!isDefined(suppression)) {
+ throw new EmailingDomainException(
+ `Suppression ${suppressionId} not found`,
+ EmailingDomainExceptionCode.MESSAGE_SUPPRESSION_NOT_FOUND,
+ );
+ }
+
+ const { affected } = await this.suppressionRepository.delete(workspaceId, {
+ id: suppressionId,
+ reason: Not(In(HARD_SUPPRESSION_REASONS)),
+ });
+
+ if (affected === 0) {
+ throw new EmailingDomainException(
+ `Suppression ${suppressionId} records a ${suppression.reason} and cannot be removed`,
+ EmailingDomainExceptionCode.MESSAGE_SUPPRESSION_NOT_REMOVABLE,
+ );
+ }
+ }
+
async getTopicOptOutState({
workspaceId,
emailAddress,
@@ -228,21 +283,34 @@ export class MessageSuppressionService {
}
const optOuts = await this.suppressionRepository.find(workspaceId, {
- where: {
- emailAddress: normalizedEmailAddress,
- reason: MessageSuppressionReason.UNSUBSCRIBE,
- unsubscribeTopicId: In(visibleTopics.map((topic) => topic.id)),
- },
+ where: [
+ {
+ emailAddress: normalizedEmailAddress,
+ reason: MessageSuppressionReason.UNSUBSCRIBE,
+ unsubscribeTopicId: In(visibleTopics.map((topic) => topic.id)),
+ },
+ {
+ emailAddress: normalizedEmailAddress,
+ reason: MessageSuppressionReason.UNSUBSCRIBE,
+ unsubscribeTopicId: IsNull(),
+ },
+ ],
});
const optedOutTopicIds = new Set(
- optOuts.map((suppression) => suppression.unsubscribeTopicId),
+ optOuts
+ .filter((suppression) => isDefined(suppression.unsubscribeTopicId))
+ .map((suppression) => suppression.unsubscribeTopicId),
+ );
+
+ const globalOptOut = optOuts.find(
+ (suppression) => !isDefined(suppression.unsubscribeTopicId),
);
return visibleTopics.map((topic) => ({
unsubscribeTopicId: topic.id,
topicName: topic.name,
- optedOut: optedOutTopicIds.has(topic.id),
+ optedOut: isDefined(globalOptOut) || optedOutTopicIds.has(topic.id),
}));
}
@@ -250,48 +318,112 @@ export class MessageSuppressionService {
workspaceId,
emailAddress,
keptTopicIds,
+ canResubscribe,
}: SetTopicOptOutsArgs): Promise<void> {
- const topicStates = await this.getTopicOptOutState({
+ const visibleTopics =
+ await this.unsubscribeTopicService.findPublicTopics(workspaceId);
+
+ if (!isNonEmptyArray(visibleTopics)) {
+ return;
+ }
+
+ const visibleTopicIds = new Set(visibleTopics.map((topic) => topic.id));
+ const keptTopicIdSet = new Set(
+ keptTopicIds.filter((topicId) => visibleTopicIds.has(topicId)),
+ );
+
+ if (keptTopicIdSet.size === 0) {
+ await this.unsubscribeFromEverything({ workspaceId, emailAddress });
+
+ return;
+ }
+
+ await this.suppressTopicsNotKept({
workspaceId,
emailAddress,
+ visibleTopics,
+ keptTopicIdSet,
});
- const keptTopicIdSet = new Set(keptTopicIds);
- for (const topicState of topicStates) {
- const shouldReceive = keptTopicIdSet.has(topicState.unsubscribeTopicId);
+ if (!canResubscribe) {
+ return;
+ }
+
+ await this.liftOptOut(workspaceId, emailAddress, null);
+
+ for (const topicId of keptTopicIdSet) {
+ await this.liftOptOut(workspaceId, emailAddress, topicId);
+ }
+ }
- if (shouldReceive === !topicState.optedOut) {
+ async unsubscribeFromEverything({
+ workspaceId,
+ emailAddress,
+ }: {
+ workspaceId: string;
+ emailAddress: string;
+ }): Promise<void> {
+ await this.recordUnsubscribe({
+ workspaceId,
+ emailAddress,
+ unsubscribeTopicId: null,
+ });
+ }
+
+ private async recordUnsubscribe({
+ workspaceId,
+ emailAddress,
+ unsubscribeTopicId,
+ }: {
+ workspaceId: string;
+ emailAddress: string;
+ unsubscribeTopicId?: string | null;
+ }): Promise<void> {
+ await this.suppress({
+ workspaceId,
+ emailAddress,
+ reason: MessageSuppressionReason.UNSUBSCRIBE,
+ source: MessageSuppressionSource.SYSTEM,
+ unsubscribeTopicId,
+ });
+ }
+
+ private async suppressTopicsNotKept({
+ workspaceId,
+ emailAddress,
+ visibleTopics,
+ keptTopicIdSet,
+ }: {
+ workspaceId: string;
+ emailAddress: string;
+ visibleTopics: UnsubscribeTopicEntity[];
+ keptTopicIdSet: Set<string>;
+ }): Promise<void> {
+ for (const topic of visibleTopics) {
+ if (keptTopicIdSet.has(topic.id)) {
continue;
}
- if (shouldReceive) {
- await this.liftTopicOptOut(
- workspaceId,
- emailAddress,
- topicState.unsubscribeTopicId,
- );
- } else {
- await this.suppress({
- workspaceId,
- emailAddress,
- reason: MessageSuppressionReason.UNSUBSCRIBE,
- source: MessageSuppressionSource.SYSTEM,
- unsubscribeTopicId: topicState.unsubscribeTopicId,
- });
- }
+ await this.recordUnsubscribe({
+ workspaceId,
+ emailAddress,
+ unsubscribeTopicId: topic.id,
+ });
}
}
- private async liftTopicOptOut(
+ private async liftOptOut(
workspaceId: string,
emailAddress: string,
- unsubscribeTopicId: string,
+ unsubscribeTopicId: string | null,
): Promise<void> {
const normalizedEmailAddress = this.normalizeEmailAddress(emailAddress);
await this.suppressionRepository.delete(workspaceId, {
emailAddress: normalizedEmailAddress,
- unsubscribeTopicId,
+ unsubscribeTopicId: isNonEmptyString(unsubscribeTopicId)
+ ? unsubscribeTopicId
+ : IsNull(),
reason: MessageSuppressionReason.UNSUBSCRIBE,
});
}
diff --git a/packages/twenty-server/src/modules/emailing/types/email-credit-context.type.ts b/packages/twenty-server/src/modules/emailing/types/email-credit-context.type.ts
new file mode 100644
index 00000000000..fc44a88e1d1
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/types/email-credit-context.type.ts
@@ -0,0 +1,6 @@
+import { type CurrentBillingSubscription } from 'src/engine/core-modules/billing/types/flat-billing-subscription.type';
+
+export type EmailCreditContext = {
+ hasCredits: boolean;
+ currentBillingSubscription: CurrentBillingSubscription;
+};
diff --git a/packages/twenty-server/src/modules/emailing/utils/resolve-campaign-send-failure.util.ts b/packages/twenty-server/src/modules/emailing/utils/resolve-campaign-send-failure.util.ts
index cb02474b468..668ab227d91 100644
--- a/packages/twenty-server/src/modules/emailing/utils/resolve-campaign-send-failure.util.ts
+++ b/packages/twenty-server/src/modules/emailing/utils/resolve-campaign-send-failure.util.ts
@@ -17,21 +17,16 @@ type CampaignSendFailure = {
shouldRetry: boolean;
};
-const failed = (
- failureReason: CampaignFailureReason,
- shouldRetry: boolean,
-): CampaignSendFailure => ({
- state: CAMPAIGN_DELIVERY_STATE.FAILED,
- skipReason: null,
- failureReason,
- shouldRetry,
-});
-
export const resolveCampaignSendFailure = (
error: unknown,
): CampaignSendFailure => {
if (!(error instanceof EmailingDomainDriverException)) {
- return failed(CAMPAIGN_FAILURE_REASON.UNKNOWN, true);
+ return {
+ state: CAMPAIGN_DELIVERY_STATE.FAILED,
+ skipReason: null,
+ failureReason: CAMPAIGN_FAILURE_REASON.UNKNOWN,
+ shouldRetry: true,
+ };
}
switch (error.code) {
@@ -43,22 +38,64 @@ export const resolveCampaignSendFailure = (
shouldRetry: false,
};
case EmailingDomainDriverExceptionCode.TEMPORARY_ERROR:
- return failed(CAMPAIGN_FAILURE_REASON.TEMPORARY_ERROR, true);
+ return {
+ state: CAMPAIGN_DELIVERY_STATE.FAILED,
+ skipReason: null,
+ failureReason: CAMPAIGN_FAILURE_REASON.TEMPORARY_ERROR,
+ shouldRetry: true,
+ };
case EmailingDomainDriverExceptionCode.UNKNOWN:
- return failed(CAMPAIGN_FAILURE_REASON.UNKNOWN, true);
+ return {
+ state: CAMPAIGN_DELIVERY_STATE.FAILED,
+ skipReason: null,
+ failureReason: CAMPAIGN_FAILURE_REASON.UNKNOWN,
+ shouldRetry: true,
+ };
case EmailingDomainDriverExceptionCode.SENDING_SUSPENDED:
- return failed(CAMPAIGN_FAILURE_REASON.SENDING_SUSPENDED, true);
+ return {
+ state: CAMPAIGN_DELIVERY_STATE.FAILED,
+ skipReason: null,
+ failureReason: CAMPAIGN_FAILURE_REASON.SENDING_SUSPENDED,
+ shouldRetry: true,
+ };
case EmailingDomainDriverExceptionCode.UNSUBSCRIBE_NOT_READY:
- return failed(CAMPAIGN_FAILURE_REASON.UNSUBSCRIBE_NOT_READY, true);
+ return {
+ state: CAMPAIGN_DELIVERY_STATE.FAILED,
+ skipReason: null,
+ failureReason: CAMPAIGN_FAILURE_REASON.UNSUBSCRIBE_NOT_READY,
+ shouldRetry: true,
+ };
case EmailingDomainDriverExceptionCode.NOT_FOUND:
- return failed(CAMPAIGN_FAILURE_REASON.CONFIGURATION_ERROR, false);
- case EmailingDomainDriverExceptionCode.INSUFFICIENT_PERMISSIONS:
- return failed(CAMPAIGN_FAILURE_REASON.INSUFFICIENT_PERMISSIONS, false);
case EmailingDomainDriverExceptionCode.CONFIGURATION_ERROR:
- return failed(CAMPAIGN_FAILURE_REASON.CONFIGURATION_ERROR, false);
+ return {
+ state: CAMPAIGN_DELIVERY_STATE.FAILED,
+ skipReason: null,
+ failureReason: CAMPAIGN_FAILURE_REASON.CONFIGURATION_ERROR,
+ shouldRetry: false,
+ };
+ case EmailingDomainDriverExceptionCode.INSUFFICIENT_PERMISSIONS:
+ return {
+ state: CAMPAIGN_DELIVERY_STATE.FAILED,
+ skipReason: null,
+ failureReason: CAMPAIGN_FAILURE_REASON.INSUFFICIENT_PERMISSIONS,
+ shouldRetry: false,
+ };
case EmailingDomainDriverExceptionCode.SANDBOX_ACCOUNT:
- return failed(CAMPAIGN_FAILURE_REASON.SANDBOX_ACCOUNT, false);
- default:
+ return {
+ state: CAMPAIGN_DELIVERY_STATE.FAILED,
+ skipReason: null,
+ failureReason: CAMPAIGN_FAILURE_REASON.SANDBOX_ACCOUNT,
+ shouldRetry: false,
+ };
+ case EmailingDomainDriverExceptionCode.UNSUBSCRIBE_MULTIPLE_RECIPIENTS:
+ return {
+ state: CAMPAIGN_DELIVERY_STATE.FAILED,
+ skipReason: null,
+ failureReason: CAMPAIGN_FAILURE_REASON.UNSUBSCRIBE_MULTIPLE_RECIPIENTS,
+ shouldRetry: false,
+ };
+ default: {
return assertUnreachable(error.code);
+ }
}
};
diff --git a/packages/twenty-server/src/modules/emailing/zod-schemas/sendable-draft-campaign.zod-schema.ts b/packages/twenty-server/src/modules/emailing/zod-schemas/sendable-draft-campaign.zod-schema.ts
index d83e59c1a7d..fa7a30c23ae 100644
--- a/packages/twenty-server/src/modules/emailing/zod-schemas/sendable-draft-campaign.zod-schema.ts
+++ b/packages/twenty-server/src/modules/emailing/zod-schemas/sendable-draft-campaign.zod-schema.ts
@@ -13,4 +13,5 @@ export const sendableDraftCampaignSchema = z.object({
}),
fromAddress: z.object({ primaryEmail: z.email() }),
listId: z.string().min(1),
+ unsubscribeTopicId: z.string().nullish(),
});
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-inbound-webhook-driver.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-inbound-webhook-driver.service.ts
index 45b270e88ef..fb8d1dba0fc 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-inbound-webhook-driver.service.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-inbound-webhook-driver.service.ts
@@ -1,66 +1,37 @@
import { Injectable, Logger } from '@nestjs/common';
-import type SnsPayloadValidator from 'sns-payload-validator';
-import { isDefined, parseJson } from 'twenty-shared/utils';
+import { isDefined } from 'twenty-shared/utils';
-import { SnsSignatureVerifierService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/sns-signature-verifier.service';
-import { SnsSubscriptionConfirmerService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/sns-subscription-confirmer.service';
+import { SnsEnvelopeService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/sns-envelope.service';
import { type SesInboundNotification } from 'src/modules/messaging-webhooks/drivers/aws-ses/types/sns-message.type';
import { InboundMailHandlerService } from 'src/modules/messaging-webhooks/handlers/inbound-mail-handler.service';
-import { MessagingWebhookExceptionCode } from 'src/modules/messaging-webhooks/messaging-webhook-exception-code.enum';
-import { MessagingWebhookException } from 'src/modules/messaging-webhooks/messaging-webhook.exception';
import { type NormalizedInboundMailNotification } from 'src/modules/messaging-webhooks/types/normalized-inbound-mail-notification.type';
import { INBOUND_EMAIL_MESSAGE_SOURCE } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/constants/inbound-email-message-source.constant';
import { type InboundEmailMessageReference } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/types/inbound-email-message-reference.type';
-type SnsPayload = SnsPayloadValidator.SnsPayload;
-
@Injectable()
export class SesInboundWebhookDriverService {
private readonly logger = new Logger(SesInboundWebhookDriverService.name);
constructor(
- private readonly snsSignatureVerifierService: SnsSignatureVerifierService,
- private readonly snsSubscriptionConfirmerService: SnsSubscriptionConfirmerService,
+ private readonly snsEnvelopeService: SnsEnvelopeService,
private readonly inboundMailHandlerService: InboundMailHandlerService,
) {}
async handle(rawBody: Buffer): Promise<void> {
- const payload = parseJson<SnsPayload>(rawBody.toString('utf8'));
-
- if (!isDefined(payload)) {
- throw new MessagingWebhookException(
- 'Invalid SNS payload',
- MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,
+ const envelope =
+ await this.snsEnvelopeService.openNotification<SesInboundNotification>(
+ rawBody,
);
- }
-
- await this.snsSignatureVerifierService.assertAllowedAndSigned(payload);
-
- if (
- payload.Type === 'SubscriptionConfirmation' ||
- payload.Type === 'UnsubscribeConfirmation'
- ) {
- await this.snsSubscriptionConfirmerService.confirm(payload.SubscribeURL);
+ if (!isDefined(envelope)) {
return;
}
- if (payload.Type !== 'Notification') {
- return;
- }
-
- const notification = parseJson<SesInboundNotification>(payload.Message);
-
- if (!isDefined(notification)) {
- throw new MessagingWebhookException(
- 'Invalid SNS notification message',
- MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,
- );
- }
+ const { notification, messageId } = envelope;
await this.inboundMailHandlerService.handle(
- this.normalizeNotification(notification, payload.MessageId),
+ this.normalizeNotification(notification, messageId),
);
}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-outbound-webhook-driver.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-outbound-webhook-driver.service.ts
index 09cada62d48..99732f31d2f 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-outbound-webhook-driver.service.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/ses-outbound-webhook-driver.service.ts
@@ -1,11 +1,9 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, Logger } from '@nestjs/common';
-import type SnsPayloadValidator from 'sns-payload-validator';
-import { isDefined, parseJson } from 'twenty-shared/utils';
+import { isDefined } from 'twenty-shared/utils';
import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
-import { SnsSignatureVerifierService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/sns-signature-verifier.service';
-import { SnsSubscriptionConfirmerService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/sns-subscription-confirmer.service';
+import { SnsEnvelopeService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/sns-envelope.service';
import { type SesOutboundNotification } from 'src/modules/messaging-webhooks/drivers/aws-ses/types/ses-outbound-notification.type';
import { normalizeSesOutboundEvent } from 'src/modules/messaging-webhooks/drivers/aws-ses/utils/normalize-ses-outbound-event.util';
import { OutboundDeliveryEventHandlerService } from 'src/modules/messaging-webhooks/handlers/outbound-delivery-event-handler.service';
@@ -13,51 +11,28 @@ import { OutboundSendingStateHandlerService } from 'src/modules/messaging-webhoo
import { MessagingWebhookExceptionCode } from 'src/modules/messaging-webhooks/messaging-webhook-exception-code.enum';
import { MessagingWebhookException } from 'src/modules/messaging-webhooks/messaging-webhook.exception';
-type SnsPayload = SnsPayloadValidator.SnsPayload;
-
@Injectable()
export class SesOutboundWebhookDriverService {
+ private readonly logger = new Logger(SesOutboundWebhookDriverService.name);
+
constructor(
private readonly exceptionHandlerService: ExceptionHandlerService,
- private readonly snsSignatureVerifierService: SnsSignatureVerifierService,
- private readonly snsSubscriptionConfirmerService: SnsSubscriptionConfirmerService,
+ private readonly snsEnvelopeService: SnsEnvelopeService,
private readonly outboundDeliveryEventHandlerService: OutboundDeliveryEventHandlerService,
private readonly outboundSendingStateHandlerService: OutboundSendingStateHandlerService,
) {}
async handle(rawBody: Buffer): Promise<void> {
- const payload = parseJson<SnsPayload>(rawBody.toString('utf8'));
-
- if (!isDefined(payload)) {
- throw new MessagingWebhookException(
- 'Invalid SNS payload',
- MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,
+ const envelope =
+ await this.snsEnvelopeService.openNotification<SesOutboundNotification>(
+ rawBody,
);
- }
-
- await this.snsSignatureVerifierService.assertAllowedAndSigned(payload);
-
- if (
- payload.Type === 'SubscriptionConfirmation' ||
- payload.Type === 'UnsubscribeConfirmation'
- ) {
- await this.snsSubscriptionConfirmerService.confirm(payload.SubscribeURL);
-
- return;
- }
- if (payload.Type !== 'Notification') {
+ if (!isDefined(envelope)) {
return;
}
- const notification = parseJson<SesOutboundNotification>(payload.Message);
-
- if (!isDefined(notification)) {
- throw new MessagingWebhookException(
- 'Invalid SNS notification message',
- MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,
- );
- }
+ const { notification, messageId } = envelope;
const event = normalizeSesOutboundEvent(notification);
@@ -65,7 +40,7 @@ export class SesOutboundWebhookDriverService {
case 'DELIVERY':
await this.outboundDeliveryEventHandlerService.handle({
...event.delivery,
- dedupeKey: payload.MessageId,
+ dedupeKey: messageId,
});
return;
@@ -76,6 +51,12 @@ export class SesOutboundWebhookDriverService {
return;
case 'UNPROCESSABLE':
+ if (event.reason === 'UNSUPPORTED_EVENT_NAME') {
+ this.logger.log(`Ignored SES outbound event ${event.eventName}`);
+
+ return;
+ }
+
this.exceptionHandlerService.captureExceptions([
new MessagingWebhookException(
`Dropped SES outbound event ${event.eventName}: ${event.reason}`,
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/sns-envelope.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/sns-envelope.service.ts
new file mode 100644
index 00000000000..f825147aae3
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/services/sns-envelope.service.ts
@@ -0,0 +1,61 @@
+import { Injectable } from '@nestjs/common';
+
+import { isObject } from '@sniptt/guards';
+import { isDefined, parseJson } from 'twenty-shared/utils';
+
+import { SnsSignatureVerifierService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/sns-signature-verifier.service';
+import { SnsSubscriptionConfirmerService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/sns-subscription-confirmer.service';
+import type SnsPayloadValidator from 'sns-payload-validator';
+import { MessagingWebhookExceptionCode } from 'src/modules/messaging-webhooks/messaging-webhook-exception-code.enum';
+import { MessagingWebhookException } from 'src/modules/messaging-webhooks/messaging-webhook.exception';
+
+type SnsPayload = SnsPayloadValidator.SnsPayload;
+
+@Injectable()
+export class SnsEnvelopeService {
+ constructor(
+ private readonly snsSignatureVerifierService: SnsSignatureVerifierService,
+ private readonly snsSubscriptionConfirmerService: SnsSubscriptionConfirmerService,
+ ) {}
+
+ async openNotification<TNotification>(
+ rawBody: Buffer,
+ ): Promise<{ notification: TNotification; messageId: string } | null> {
+ const payload = parseJson<SnsPayload>(rawBody.toString('utf8'));
+
+ if (!isDefined(payload)) {
+ throw new MessagingWebhookException(
+ 'Invalid SNS payload',
+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,
+ );
+ }
+
+ await this.snsSignatureVerifierService.assertAllowedAndSigned(payload);
+
+ if (
+ payload.Type === 'SubscriptionConfirmation' ||
+ payload.Type === 'UnsubscribeConfirmation'
+ ) {
+ await this.snsSubscriptionConfirmerService.confirm(payload.SubscribeURL);
+
+ return null;
+ }
+
+ if (payload.Type !== 'Notification') {
+ return null;
+ }
+
+ const notification = parseJson<TNotification>(payload.Message);
+
+ // parseJson happily returns a JSON scalar, which every caller then reads as
+ // a notification object.
+ if (!isObject(notification)) {
+ throw new MessagingWebhookException(
+ 'Invalid SNS notification message',
+ MessagingWebhookExceptionCode.MESSAGING_WEBHOOK_INVALID_PAYLOAD,
+ );
+ }
+
+ return { notification, messageId: payload.MessageId };
+ }
+}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/handlers/inbound-unsubscribe-handler.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/handlers/inbound-unsubscribe-handler.service.ts
index 9b4a27aa9d0..489ce0c554b 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/handlers/inbound-unsubscribe-handler.service.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/handlers/inbound-unsubscribe-handler.service.ts
@@ -4,8 +4,6 @@ import { isNonEmptyString } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
import { UnsubscribeTokenService } from 'src/engine/core-modules/emailing-domain/services/unsubscribe-token.service';
-import { MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
-import { MessageSuppressionSource } from 'src/engine/core-modules/emailing-domain/types/message-suppression-source.type';
import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';
@Injectable()
@@ -24,24 +22,23 @@ export class InboundUnsubscribeHandlerService {
return;
}
- const payload = this.unsubscribeTokenService.verify(subject.trim());
+ const verification = this.unsubscribeTokenService.verify(subject.trim());
- if (!isDefined(payload)) {
+ if (!isDefined(verification)) {
this.logger.warn('Unsubscribe email received with an invalid token');
return;
}
+ const { payload } = verification;
+
if (payload.preview === true) {
return;
}
- await this.messageSuppressionService.suppress({
+ await this.messageSuppressionService.unsubscribeFromEverything({
workspaceId: payload.workspaceId,
emailAddress: payload.emailAddress,
- reason: MessageSuppressionReason.UNSUBSCRIBE,
- source: MessageSuppressionSource.SYSTEM,
- unsubscribeTopicId: payload.unsubscribeTopicId ?? null,
});
}
}
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-delivery-event-handler.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-delivery-event-handler.service.ts
index 333731e44c3..b0c5c8def36 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-delivery-event-handler.service.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-delivery-event-handler.service.ts
@@ -22,6 +22,7 @@ export class OutboundDeliveryEventHandlerService {
event,
{
id: event.dedupeKey,
+ allowDuplicatedPrefixes: true,
retryLimit: DELIVERY_EVENT_RETRY_LIMIT,
backoff: CAMPAIGN_SEND_RETRY_BACKOFF,
},
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhooks.module.ts b/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhooks.module.ts
index fd27f3ea058..2d383dcf43f 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhooks.module.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/messaging-webhooks.module.ts
@@ -7,6 +7,7 @@ import { ResendWebhookDriverService } from 'src/modules/messaging-webhooks/drive
import { ResendWebhookVerifierService } from 'src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-verifier.service';
import { SesInboundWebhookDriverService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/ses-inbound-webhook-driver.service';
import { SesOutboundWebhookDriverService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/ses-outbound-webhook-driver.service';
+import { SnsEnvelopeService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/sns-envelope.service';
import { SnsSignatureVerifierService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/sns-signature-verifier.service';
import { SnsSubscriptionConfirmerService } from 'src/modules/messaging-webhooks/drivers/aws-ses/services/sns-subscription-confirmer.service';
import { InboundMailHandlerService } from 'src/modules/messaging-webhooks/handlers/inbound-mail-handler.service';
@@ -27,6 +28,7 @@ import { MessagingWebhooksController } from 'src/modules/messaging-webhooks/mess
OutboundDeliveryEventProcessorService,
OutboundSendingStateHandlerService,
MessagingOutboundDeliveryEventJob,
+ SnsEnvelopeService,
SnsSignatureVerifierService,
SnsSubscriptionConfirmerService,
SesInboundWebhookDriverService,
diff --git a/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/email-group/services/email-group-message-outbound.service.ts b/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/email-group/services/email-group-message-outbound.service.ts
index d73d9bfadfa..a592cd926b3 100644
--- a/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/email-group/services/email-group-message-outbound.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/email-group/services/email-group-message-outbound.service.ts
@@ -1,10 +1,11 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, Logger } from '@nestjs/common';
import { isNonEmptyString } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
import { EmailingDomainStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-status.type';
import { EmailingDomainEntity } from 'src/engine/core-modules/emailing-domain/emailing-domain.entity';
+import { EmailBillingService } from 'src/modules/emailing/services/email-billing.service';
import { EmailingDomainSenderService } from 'src/modules/emailing/services/emailing-domain-sender.service';
import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import {
@@ -17,13 +18,17 @@ import { type MessageOutboundDriver } from 'src/modules/messaging/message-outbou
import { type SendMessageInput } from 'src/modules/messaging/message-outbound-manager/types/send-message-input.type';
import { type SendMessageResult } from 'src/modules/messaging/message-outbound-manager/types/send-message-result.type';
import { getDomainFromEmail } from 'src/utils/get-domain-from-email';
+import { countDeliveredRecipients } from 'src/engine/core-modules/emailing-domain/utils/count-delivered-recipients.util';
@Injectable()
export class EmailGroupMessageOutboundService implements MessageOutboundDriver {
+ private readonly logger = new Logger(EmailGroupMessageOutboundService.name);
+
constructor(
@InjectWorkspaceScopedRepository(EmailingDomainEntity)
private readonly emailingDomainRepository: WorkspaceScopedRepository<EmailingDomainEntity>,
private readonly emailingDomainSenderService: EmailingDomainSenderService,
+ private readonly emailBillingService: EmailBillingService,
) {}
async sendMessage(
@@ -39,10 +44,15 @@ export class EmailGroupMessageOutboundService implements MessageOutboundDriver {
);
}
+ await this.emailBillingService.validateEmailCreditsOrThrow(
+ connectedAccount.workspaceId,
+ );
+
const result = await this.emailingDomainSenderService.sendEmail(
connectedAccount.workspaceId,
emailingDomain.id,
{
+ sendKind: 'TRANSACTIONAL',
to: this.toRecipientArray(sendMessageInput.to),
cc: this.toRecipientArray(sendMessageInput.cc),
bcc: this.toRecipientArray(sendMessageInput.bcc),
@@ -57,6 +67,21 @@ export class EmailGroupMessageOutboundService implements MessageOutboundDriver {
},
);
+ // The provider has already accepted the mail, so surfacing a billing
+ // failure would invite a retry that sends it a second time.
+ await this.emailBillingService
+ .billSentEmails({
+ workspaceId: connectedAccount.workspaceId,
+ sentEmailCount: countDeliveredRecipients(result.deliveredRecipients),
+ })
+ .catch((error) => {
+ this.logger.error(
+ `Workspace ${connectedAccount.workspaceId} sent email ${result.messageId} but failed to bill it, so this send is unbilled: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ });
+
return {
headerMessageId: result.messageId,
messageExternalId: result.messageId,
diff --git a/packages/twenty-server/test/integration/metadata/suites/emailing/message-suppression.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/emailing/message-suppression.integration-spec.ts
new file mode 100644
index 00000000000..45d26471475
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/emailing/message-suppression.integration-spec.ts
@@ -0,0 +1,178 @@
+import { gql } from 'graphql-tag';
+import { makeMetadataAPIRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { updateFeatureFlag } from 'test/integration/metadata/suites/utils/update-feature-flag.util';
+import { FeatureFlagKey } from 'twenty-shared/types';
+import { v4 } from 'uuid';
+import { isDefined } from 'twenty-shared/utils';
+
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const CREATE_MESSAGE_SUPPRESSION = gql`
+ mutation CreateMessageSuppression($input: CreateMessageSuppressionInput!) {
+ createMessageSuppression(input: $input) {
+ id
+ emailAddress
+ reason
+ source
+ unsubscribeTopicId
+ }
+ }
+`;
+
+const DELETE_MESSAGE_SUPPRESSION = gql`
+ mutation DeleteMessageSuppression($id: UUID!) {
+ deleteMessageSuppression(id: $id)
+ }
+`;
+
+const MESSAGE_SUPPRESSIONS = gql`
+ query MessageSuppressions($input: FindMessageSuppressionsInput!) {
+ messageSuppressions(input: $input) {
+ totalCount
+ records {
+ id
+ emailAddress
+ reason
+ }
+ }
+ }
+`;
+
+describe('messageSuppressionResolver (integration)', () => {
+ const createdSuppressionIds: string[] = [];
+
+ beforeAll(async () => {
+ await updateFeatureFlag({
+ featureFlag: FeatureFlagKey.IS_EMAIL_GROUP_ENABLED,
+ value: true,
+ expectToFail: false,
+ });
+ });
+
+ afterAll(async () => {
+ await updateFeatureFlag({
+ featureFlag: FeatureFlagKey.IS_EMAIL_GROUP_ENABLED,
+ value: false,
+ expectToFail: false,
+ });
+ });
+
+ afterEach(async () => {
+ for (const id of createdSuppressionIds) {
+ await testDataSource
+ .query('DELETE FROM core."messageSuppression" WHERE id = $1', [id])
+ .catch(() => {});
+ }
+ createdSuppressionIds.length = 0;
+ });
+
+ const createSuppression = async (emailAddress: string) => {
+ const response = await makeMetadataAPIRequest({
+ query: CREATE_MESSAGE_SUPPRESSION,
+ variables: { input: { emailAddress } },
+ });
+
+ const createdId: string | undefined =
+ response.body.data?.createMessageSuppression?.id;
+
+ if (isDefined(createdId)) {
+ createdSuppressionIds.push(createdId);
+ }
+
+ return response;
+ };
+
+ const insertHardSuppression = async (emailAddress: string) => {
+ const suppressionId = v4();
+
+ await testDataSource.query(
+ `INSERT INTO core."messageSuppression"
+ ("id", "workspaceId", "emailAddress", "reason", "source", "providerEventId", "unsubscribeTopicId")
+ VALUES ($1, $2, $3, 'BOUNCE', 'WEBHOOK', NULL, NULL)`,
+ [suppressionId, SEED_APPLE_WORKSPACE_ID, emailAddress],
+ );
+ createdSuppressionIds.push(suppressionId);
+
+ return suppressionId;
+ };
+
+ it('should suppress an address on request and expose it through the list query', async () => {
+ const emailAddress = `manual-${v4()}@example.com`;
+
+ const createResponse = await createSuppression(emailAddress);
+
+ expect(createResponse.body.errors).toBeUndefined();
+ expect(createResponse.body.data.createMessageSuppression).toMatchObject({
+ emailAddress,
+ reason: 'UNSUBSCRIBE',
+ source: 'SYSTEM',
+ unsubscribeTopicId: null,
+ });
+
+ const listResponse = await makeMetadataAPIRequest({
+ query: MESSAGE_SUPPRESSIONS,
+ variables: { input: { searchTerm: emailAddress, limit: 30, offset: 0 } },
+ });
+
+ expect(listResponse.body.data.messageSuppressions.totalCount).toBe(1);
+ });
+
+ it('should lower-case the suppressed address so sends match it', async () => {
+ const emailAddress = `Mixed-${v4()}@Example.com`;
+
+ const createResponse = await createSuppression(emailAddress);
+
+ expect(createResponse.body.data.createMessageSuppression.emailAddress).toBe(
+ emailAddress.toLowerCase(),
+ );
+ });
+
+ it('should remove a suppression that was added by mistake', async () => {
+ const emailAddress = `undo-${v4()}@example.com`;
+ const createResponse = await createSuppression(emailAddress);
+ const suppressionId = createResponse.body.data.createMessageSuppression.id;
+
+ const deleteResponse = await makeMetadataAPIRequest({
+ query: DELETE_MESSAGE_SUPPRESSION,
+ variables: { id: suppressionId },
+ });
+
+ expect(deleteResponse.body.errors).toBeUndefined();
+ expect(deleteResponse.body.data.deleteMessageSuppression).toBe(true);
+
+ const listResponse = await makeMetadataAPIRequest({
+ query: MESSAGE_SUPPRESSIONS,
+ variables: { input: { searchTerm: emailAddress, limit: 30, offset: 0 } },
+ });
+
+ expect(listResponse.body.data.messageSuppressions.totalCount).toBe(0);
+ });
+
+ it('should refuse to remove a hard bounce', async () => {
+ const suppressionId = await insertHardSuppression(
+ `bounced-${v4()}@example.com`,
+ );
+
+ const deleteResponse = await makeMetadataAPIRequest({
+ query: DELETE_MESSAGE_SUPPRESSION,
+ variables: { id: suppressionId },
+ });
+
+ expect(deleteResponse.body.errors[0].extensions).toMatchObject({
+ code: 'FORBIDDEN',
+ subCode: 'MESSAGE_SUPPRESSION_NOT_REMOVABLE',
+ });
+ });
+
+ it('should fail when the suppression does not exist', async () => {
+ const deleteResponse = await makeMetadataAPIRequest({
+ query: DELETE_MESSAGE_SUPPRESSION,
+ variables: { id: v4() },
+ });
+
+ expect(deleteResponse.body.errors[0].extensions).toMatchObject({
+ code: 'NOT_FOUND',
+ subCode: 'MESSAGE_SUPPRESSION_NOT_FOUND',
+ });
+ });
+});