Skip to content

The open alternative to Salesforce, designed for AI.

Email campaigns 2/4: claim each send exactly once (#25123)

neo773cfcf5d0ba439
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 509b775211f..16603291a4f 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -2807,6 +2807,11 @@ type CampaignAudiencePreviewDTO {
sendable: Int!
}
+type CancelMessageCampaignOutputDTO {
+ campaignId: String!
+ canceledMessageCount: Int!
+}
+
type SendEmailViaDomainOutput {
messageId: String!
}
@@ -3787,6 +3792,7 @@ type Mutation {
removeRoleFromAgent(agentId: UUID!): Boolean!
sendEmailViaEmailingDomain(input: SendEmailViaDomainInput!): SendEmailViaDomainOutput!
sendMessageCampaign(input: SendMessageCampaignInput!): SendMessageCampaignOutputDTO!
+ cancelMessageCampaign(input: CancelMessageCampaignInput!): CancelMessageCampaignOutputDTO!
sendMessageCampaignTest(input: SendMessageCampaignTestInput!): SendEmailViaDomainOutput!
createUnsubscribeTopic(input: CreateUnsubscribeTopicInput!): UnsubscribeTopic!
updateUnsubscribeTopic(input: UpdateUnsubscribeTopicInput!): UnsubscribeTopic!
@@ -4861,6 +4867,10 @@ input SendMessageCampaignInput {
campaignId: String!
}
+input CancelMessageCampaignInput {
+ campaignId: String!
+}
+
input SendMessageCampaignTestInput {
toAddress: String!
unsubscribeTopicId: String
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index a4379e47dd3..d77e5351460 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -2422,6 +2422,12 @@ export interface CampaignAudiencePreviewDTO {
__typename: 'CampaignAudiencePreviewDTO'
}
+export interface CancelMessageCampaignOutputDTO {
+ campaignId: Scalars['String']
+ canceledMessageCount: Scalars['Int']
+ __typename: 'CancelMessageCampaignOutputDTO'
+}
+
export interface SendEmailViaDomainOutput {
messageId: Scalars['String']
__typename: 'SendEmailViaDomainOutput'
@@ -3262,6 +3268,7 @@ export interface Mutation {
removeRoleFromAgent: Scalars['Boolean']
sendEmailViaEmailingDomain: SendEmailViaDomainOutput
sendMessageCampaign: SendMessageCampaignOutputDTO
+ cancelMessageCampaign: CancelMessageCampaignOutputDTO
sendMessageCampaignTest: SendEmailViaDomainOutput
createUnsubscribeTopic: UnsubscribeTopic
updateUnsubscribeTopic: UnsubscribeTopic
@@ -5899,6 +5906,13 @@ export interface CampaignAudiencePreviewDTOGenqlSelection{
__scalar?: boolean | number
}
+export interface CancelMessageCampaignOutputDTOGenqlSelection{
+ campaignId?: boolean | number
+ canceledMessageCount?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface SendEmailViaDomainOutputGenqlSelection{
messageId?: boolean | number
__typename?: boolean | number
@@ -6814,6 +6828,7 @@ export interface MutationGenqlSelection{
removeRoleFromAgent?: { __args: {agentId: Scalars['UUID']} }
sendEmailViaEmailingDomain?: (SendEmailViaDomainOutputGenqlSelection & { __args: {input: SendEmailViaDomainInput} })
sendMessageCampaign?: (SendMessageCampaignOutputDTOGenqlSelection & { __args: {input: SendMessageCampaignInput} })
+ cancelMessageCampaign?: (CancelMessageCampaignOutputDTOGenqlSelection & { __args: {input: CancelMessageCampaignInput} })
sendMessageCampaignTest?: (SendEmailViaDomainOutputGenqlSelection & { __args: {input: SendMessageCampaignTestInput} })
createUnsubscribeTopic?: (UnsubscribeTopicGenqlSelection & { __args: {input: CreateUnsubscribeTopicInput} })
updateUnsubscribeTopic?: (UnsubscribeTopicGenqlSelection & { __args: {input: UpdateUnsubscribeTopicInput} })
@@ -7241,6 +7256,8 @@ export interface SendEmailViaDomainInput {emailingDomainId: Scalars['String'],to
export interface SendMessageCampaignInput {campaignId: Scalars['String']}
+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 CreateUnsubscribeTopicInput {name: Scalars['String'],description?: (Scalars['String'] | null),visibility?: (UnsubscribeTopicVisibility | null)}
@@ -9113,6 +9130,14 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null
+ const CancelMessageCampaignOutputDTO_possibleTypes: string[] = ['CancelMessageCampaignOutputDTO']
+ export const isCancelMessageCampaignOutputDTO = (obj?: { __typename?: any } | null): obj is CancelMessageCampaignOutputDTO => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isCancelMessageCampaignOutputDTO"')
+ return CancelMessageCampaignOutputDTO_possibleTypes.includes(obj.__typename)
+ }
+
+
+
const SendEmailViaDomainOutput_possibleTypes: string[] = ['SendEmailViaDomainOutput']
export const isSendEmailViaDomainOutput = (obj?: { __typename?: any } | null): obj is SendEmailViaDomainOutput => {
if (!obj?.__typename) throw new Error('__typename is missing in "isSendEmailViaDomainOutput"')
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 745d965a6aa..61755549b83 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -79,22 +79,22 @@ export default {
301,
302,
303,
- 310,
311,
- 314,
- 351,
- 358,
- 360,
+ 312,
+ 315,
+ 352,
+ 359,
361,
362,
363,
- 365,
- 367,
- 372,
- 386,
- 399,
- 512,
- 536
+ 364,
+ 366,
+ 368,
+ 373,
+ 387,
+ 400,
+ 514,
+ 538
],
"types": {
"BillingProductDTO": {
@@ -5453,6 +5453,17 @@ export default {
1
]
},
+ "CancelMessageCampaignOutputDTO": {
+ "campaignId": [
+ 1
+ ],
+ "canceledMessageCount": [
+ 26
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"SendEmailViaDomainOutput": {
"messageId": [
1
@@ -5483,7 +5494,7 @@ export default {
26
],
"skipped": [
- 307
+ 308
],
"__typename": [
1
@@ -5500,10 +5511,10 @@ export default {
1
],
"reason": [
- 310
+ 311
],
"source": [
- 311
+ 312
],
"unsubscribeTopicId": [
3
@@ -5516,7 +5527,7 @@ export default {
"MessageSuppressionSource": {},
"MessageSuppressionList": {
"records": [
- 309
+ 310
],
"totalCount": [
26
@@ -5542,7 +5553,7 @@ export default {
1
],
"visibility": [
- 314
+ 315
],
"__typename": [
1
@@ -5588,7 +5599,7 @@ export default {
1
],
"location": [
- 316
+ 317
],
"__typename": [
1
@@ -5616,13 +5627,13 @@ export default {
1
],
"IMAP": [
- 318
+ 319
],
"SMTP": [
- 318
+ 319
],
"CALDAV": [
- 318
+ 319
],
"__typename": [
1
@@ -5642,7 +5653,7 @@ export default {
3
],
"connectionParameters": [
- 319
+ 320
],
"__typename": [
1
@@ -5867,7 +5878,7 @@ export default {
1
],
"series": [
- 328
+ 329
],
"xAxisLabel": [
1
@@ -5916,7 +5927,7 @@ export default {
1
],
"data": [
- 330
+ 331
],
"__typename": [
1
@@ -5924,7 +5935,7 @@ export default {
},
"LineChartData": {
"series": [
- 331
+ 332
],
"xAxisLabel": [
1
@@ -5961,7 +5972,7 @@ export default {
},
"PieChartData": {
"data": [
- 333
+ 334
],
"showLegend": [
8
@@ -6066,13 +6077,13 @@ export default {
},
"EventLogQueryResult": {
"records": [
- 338
+ 339
],
"totalCount": [
26
],
"pageInfo": [
- 339
+ 340
],
"__typename": [
1
@@ -6136,7 +6147,7 @@ export default {
1
],
"parts": [
- 324
+ 325
],
"processedAt": [
4
@@ -6205,7 +6216,7 @@ export default {
},
"AiSystemPromptPreview": {
"sections": [
- 344
+ 345
],
"estimatedTokenCount": [
26
@@ -6233,7 +6244,7 @@ export default {
26
],
"error": [
- 346
+ 347
],
"__typename": [
1
@@ -6266,10 +6277,10 @@ export default {
},
"StartWorkspaceSetupChatResult": {
"outcome": [
- 351
+ 352
],
"thread": [
- 343
+ 344
],
"__typename": [
1
@@ -6307,10 +6318,10 @@ export default {
3
],
"evaluations": [
- 352
+ 353
],
"messages": [
- 342
+ 343
],
"createdAt": [
4
@@ -6366,7 +6377,7 @@ export default {
9
],
"scope": [
- 358
+ 359
],
"__typename": [
1
@@ -6381,19 +6392,19 @@ export default {
1
],
"syncStatus": [
- 360
+ 361
],
"syncStage": [
- 361
+ 362
],
"visibility": [
- 362
+ 363
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 363
+ 364
],
"isSyncEnabled": [
8
@@ -6444,7 +6455,7 @@ export default {
1
],
"pendingSyncAction": [
- 365
+ 366
],
"messageChannelId": [
3
@@ -6486,7 +6497,7 @@ export default {
1
],
"provenance": [
- 367
+ 368
],
"__typename": [
1
@@ -6515,7 +6526,7 @@ export default {
3
],
"through": [
- 368
+ 369
],
"__typename": [
1
@@ -6535,7 +6546,7 @@ export default {
1
],
"emit": [
- 369
+ 370
],
"action": [
1
@@ -6570,7 +6581,7 @@ export default {
},
"CollectionHash": {
"collectionName": [
- 372
+ 373
],
"hash": [
1
@@ -6634,13 +6645,13 @@ export default {
},
"MinimalMetadata": {
"objectMetadataItems": [
- 373
+ 374
],
"views": [
- 374
+ 375
],
"collectionHashes": [
- 371
+ 372
],
"__typename": [
1
@@ -6817,7 +6828,7 @@ export default {
2,
{
"input": [
- 377,
+ 378,
"GetApiKeyInput!"
]
}
@@ -6926,7 +6937,7 @@ export default {
10,
{
"input": [
- 378,
+ 379,
"AgentIdInput!"
]
}
@@ -6939,7 +6950,7 @@ export default {
"CursorPaging!"
],
"filter": [
- 379,
+ 380,
"ObjectFilter!"
]
}
@@ -6969,7 +6980,7 @@ export default {
21,
{
"input": [
- 380,
+ 381,
"LogicFunctionIdInput!"
]
}
@@ -6981,7 +6992,7 @@ export default {
9,
{
"input": [
- 380,
+ 381,
"LogicFunctionIdInput!"
]
}
@@ -6990,7 +7001,7 @@ export default {
1,
{
"input": [
- 380,
+ 381,
"LogicFunctionIdInput!"
]
}
@@ -7212,22 +7223,22 @@ export default {
305,
{
"input": [
- 381,
+ 382,
"PreviewMessageCampaignAudienceInput!"
]
}
],
"messageSuppressions": [
- 312,
+ 313,
{
"input": [
- 382,
+ 383,
"FindMessageSuppressionsInput!"
]
}
],
"unsubscribeTopics": [
- 313
+ 314
],
"myMessageChannels": [
296,
@@ -7241,7 +7252,7 @@ export default {
294
],
"getToolIndex": [
- 323
+ 324
],
"getToolInputSchema": [
9,
@@ -7253,10 +7264,10 @@ export default {
}
],
"webhooks": [
- 322
+ 323
],
"webhook": [
- 322,
+ 323,
{
"id": [
3,
@@ -7265,7 +7276,7 @@ export default {
}
],
"myMessageFolders": [
- 364,
+ 365,
{
"messageChannelId": [
3
@@ -7273,7 +7284,7 @@ export default {
}
],
"myCalendarChannels": [
- 359,
+ 360,
{
"connectedAccountId": [
3
@@ -7281,17 +7292,17 @@ export default {
}
],
"minimalMetadata": [
- 375
+ 376
],
"appKeyValue": [
- 357,
+ 358,
{
"key": [
1,
"String!"
],
"scope": [
- 358
+ 359
]
}
],
@@ -7299,7 +7310,7 @@ export default {
213,
{
"filter": [
- 383
+ 384
]
}
],
@@ -7313,13 +7324,13 @@ export default {
}
],
"findWorkspaceAiStats": [
- 354
+ 355
],
"chatThreads": [
- 343
+ 344
],
"chatThread": [
- 343,
+ 344,
{
"id": [
3,
@@ -7328,7 +7339,7 @@ export default {
}
],
"chatMessages": [
- 342,
+ 343,
{
"threadId": [
3,
@@ -7337,7 +7348,7 @@ export default {
}
],
"chatStreamCatchupChunks": [
- 347,
+ 348,
{
"threadId": [
3,
@@ -7346,13 +7357,13 @@ export default {
}
],
"getAiSystemPromptPreview": [
- 345
+ 346
],
"skills": [
- 341
+ 342
],
"skill": [
- 341,
+ 342,
{
"id": [
3,
@@ -7361,7 +7372,7 @@ export default {
}
],
"agentTurns": [
- 353,
+ 354,
{
"agentId": [
3,
@@ -7370,13 +7381,13 @@ export default {
}
],
"timelineActivityTypes": [
- 370
+ 371
],
"metadataTranslations": [
- 366,
+ 367,
{
"input": [
- 384,
+ 385,
"MetadataTranslationsInput!"
]
}
@@ -7439,37 +7450,37 @@ export default {
219
],
"eventLogs": [
- 340,
+ 341,
{
"input": [
- 385,
+ 386,
"EventLogQueryInput!"
]
}
],
"pieChartData": [
- 334,
+ 335,
{
"input": [
- 389,
+ 390,
"PieChartDataInput!"
]
}
],
"lineChartData": [
- 332,
+ 333,
{
"input": [
- 390,
+ 391,
"LineChartDataInput!"
]
}
],
"barChartData": [
- 329,
+ 330,
{
"input": [
- 391,
+ 392,
"BarChartDataInput!"
]
}
@@ -7484,7 +7495,7 @@ export default {
}
],
"getConnectedImapSmtpCaldavAccount": [
- 320,
+ 321,
{
"id": [
3,
@@ -7493,7 +7504,7 @@ export default {
}
],
"getAutoCompleteAddress": [
- 315,
+ 316,
{
"address": [
1,
@@ -7512,7 +7523,7 @@ export default {
}
],
"getAddressDetails": [
- 317,
+ 318,
{
"placeId": [
1,
@@ -7528,7 +7539,7 @@ export default {
281,
{
"input": [
- 392
+ 393
]
}
],
@@ -7560,10 +7571,10 @@ export default {
},
"ObjectFilter": {
"and": [
- 379
+ 380
],
"or": [
- 379
+ 380
],
"id": [
29
@@ -7617,7 +7628,7 @@ export default {
},
"FindMessageSuppressionsInput": {
"reason": [
- 310
+ 311
],
"searchTerm": [
1
@@ -7665,10 +7676,10 @@ export default {
},
"EventLogQueryInput": {
"table": [
- 386
+ 387
],
"filters": [
- 387
+ 388
],
"first": [
26
@@ -7689,7 +7700,7 @@ export default {
1
],
"dateRange": [
- 388
+ 389
],
"recordId": [
1
@@ -7767,7 +7778,7 @@ export default {
8,
{
"input": [
- 394,
+ 395,
"AddQuerySubscriptionInput!"
]
}
@@ -7776,7 +7787,7 @@ export default {
8,
{
"input": [
- 395,
+ 396,
"RemoveQueryFromEventStreamInput!"
]
}
@@ -7785,7 +7796,7 @@ export default {
155,
{
"inputs": [
- 396,
+ 397,
"[CreateNavigationMenuItemInput!]!"
]
}
@@ -7794,7 +7805,7 @@ export default {
155,
{
"input": [
- 396,
+ 397,
"CreateNavigationMenuItemInput!"
]
}
@@ -7803,7 +7814,7 @@ export default {
155,
{
"inputs": [
- 397,
+ 398,
"[UpdateOneNavigationMenuItemInput!]!"
]
}
@@ -7812,7 +7823,7 @@ export default {
155,
{
"input": [
- 397,
+ 398,
"UpdateOneNavigationMenuItemInput!"
]
}
@@ -7886,7 +7897,7 @@ export default {
152,
{
"file": [
- 399,
+ 400,
"Upload!"
]
}
@@ -7895,7 +7906,7 @@ export default {
152,
{
"file": [
- 399,
+ 400,
"Upload!"
]
}
@@ -7904,7 +7915,7 @@ export default {
152,
{
"file": [
- 399,
+ 400,
"Upload!"
]
}
@@ -7913,7 +7924,7 @@ export default {
152,
{
"file": [
- 399,
+ 400,
"Upload!"
]
}
@@ -7922,7 +7933,7 @@ export default {
152,
{
"file": [
- 399,
+ 400,
"Upload!"
]
}
@@ -7931,7 +7942,7 @@ export default {
152,
{
"file": [
- 399,
+ 400,
"Upload!"
],
"fieldMetadataId": [
@@ -7944,7 +7955,7 @@ export default {
152,
{
"file": [
- 399,
+ 400,
"Upload!"
],
"fieldMetadataUniversalIdentifier": [
@@ -7957,7 +7968,7 @@ export default {
74,
{
"input": [
- 400,
+ 401,
"UpsertUsageLimitInput!"
]
}
@@ -7975,7 +7986,7 @@ export default {
53,
{
"input": [
- 401,
+ 402,
"CreateViewFilterGroupInput!"
]
}
@@ -7988,7 +7999,7 @@ export default {
"String!"
],
"input": [
- 402,
+ 403,
"UpdateViewFilterGroupInput!"
]
}
@@ -8015,7 +8026,7 @@ export default {
55,
{
"input": [
- 403,
+ 404,
"CreateViewFilterInput!"
]
}
@@ -8024,7 +8035,7 @@ export default {
55,
{
"input": [
- 404,
+ 405,
"UpdateViewFilterInput!"
]
}
@@ -8033,7 +8044,7 @@ export default {
55,
{
"input": [
- 406,
+ 407,
"DeleteViewFilterInput!"
]
}
@@ -8042,7 +8053,7 @@ export default {
55,
{
"input": [
- 407,
+ 408,
"DestroyViewFilterInput!"
]
}
@@ -8051,7 +8062,7 @@ export default {
61,
{
"input": [
- 408,
+ 409,
"CreateViewInput!"
]
}
@@ -8064,7 +8075,7 @@ export default {
"String!"
],
"input": [
- 409,
+ 410,
"UpdateViewInput!"
]
}
@@ -8091,7 +8102,7 @@ export default {
61,
{
"input": [
- 410,
+ 411,
"UpsertViewWidgetInput!"
]
}
@@ -8100,7 +8111,7 @@ export default {
58,
{
"input": [
- 416,
+ 417,
"CreateViewSortInput!"
]
}
@@ -8109,7 +8120,7 @@ export default {
58,
{
"input": [
- 417,
+ 418,
"UpdateViewSortInput!"
]
}
@@ -8118,7 +8129,7 @@ export default {
8,
{
"input": [
- 419,
+ 420,
"DeleteViewSortInput!"
]
}
@@ -8127,7 +8138,7 @@ export default {
8,
{
"input": [
- 420,
+ 421,
"DestroyViewSortInput!"
]
}
@@ -8136,7 +8147,7 @@ export default {
51,
{
"input": [
- 421,
+ 422,
"UpdateViewFieldInput!"
]
}
@@ -8145,7 +8156,7 @@ export default {
51,
{
"input": [
- 423,
+ 424,
"CreateViewFieldInput!"
]
}
@@ -8154,7 +8165,7 @@ export default {
51,
{
"inputs": [
- 423,
+ 424,
"[CreateViewFieldInput!]!"
]
}
@@ -8163,7 +8174,7 @@ export default {
51,
{
"input": [
- 424,
+ 425,
"DeleteViewFieldInput!"
]
}
@@ -8172,7 +8183,7 @@ export default {
51,
{
"input": [
- 425,
+ 426,
"DestroyViewFieldInput!"
]
}
@@ -8181,7 +8192,7 @@ export default {
60,
{
"input": [
- 426,
+ 427,
"UpdateViewFieldGroupInput!"
]
}
@@ -8190,7 +8201,7 @@ export default {
60,
{
"input": [
- 428,
+ 429,
"CreateViewFieldGroupInput!"
]
}
@@ -8199,7 +8210,7 @@ export default {
60,
{
"inputs": [
- 428,
+ 429,
"[CreateViewFieldGroupInput!]!"
]
}
@@ -8208,7 +8219,7 @@ export default {
60,
{
"input": [
- 429,
+ 430,
"DeleteViewFieldGroupInput!"
]
}
@@ -8217,7 +8228,7 @@ export default {
60,
{
"input": [
- 430,
+ 431,
"DestroyViewFieldGroupInput!"
]
}
@@ -8226,7 +8237,7 @@ export default {
61,
{
"input": [
- 431,
+ 432,
"UpsertFieldsWidgetInput!"
]
}
@@ -8235,7 +8246,7 @@ export default {
2,
{
"input": [
- 434,
+ 435,
"CreateApiKeyInput!"
]
}
@@ -8244,7 +8255,7 @@ export default {
2,
{
"input": [
- 435,
+ 436,
"UpdateApiKeyInput!"
]
}
@@ -8253,7 +8264,7 @@ export default {
2,
{
"input": [
- 436,
+ 437,
"RevokeApiKeyInput!"
]
}
@@ -8455,7 +8466,7 @@ export default {
151,
{
"input": [
- 437,
+ 438,
"CreateApprovedAccessDomainInput!"
]
}
@@ -8464,7 +8475,7 @@ export default {
8,
{
"input": [
- 438,
+ 439,
"DeleteApprovedAccessDomainInput!"
]
}
@@ -8473,7 +8484,7 @@ export default {
151,
{
"input": [
- 439,
+ 440,
"ValidateApprovedAccessDomainInput!"
]
}
@@ -8482,7 +8493,7 @@ export default {
125,
{
"input": [
- 440,
+ 441,
"CreatePageLayoutTabInput!"
]
}
@@ -8495,7 +8506,7 @@ export default {
"String!"
],
"input": [
- 441,
+ 442,
"UpdatePageLayoutTabInput!"
]
}
@@ -8513,7 +8524,7 @@ export default {
126,
{
"input": [
- 442,
+ 443,
"CreatePageLayoutInput!"
]
}
@@ -8526,7 +8537,7 @@ export default {
"String!"
],
"input": [
- 443,
+ 444,
"UpdatePageLayoutInput!"
]
}
@@ -8548,7 +8559,7 @@ export default {
"String!"
],
"input": [
- 444,
+ 445,
"UpdatePageLayoutWithTabsInput!"
]
}
@@ -8584,7 +8595,7 @@ export default {
82,
{
"input": [
- 447,
+ 448,
"CreatePageLayoutWidgetInput!"
]
}
@@ -8597,7 +8608,7 @@ export default {
"String!"
],
"input": [
- 448,
+ 449,
"UpdatePageLayoutWidgetInput!"
]
}
@@ -8615,7 +8626,7 @@ export default {
10,
{
"input": [
- 449,
+ 450,
"CreateAgentInput!"
]
}
@@ -8624,7 +8635,7 @@ export default {
10,
{
"input": [
- 450,
+ 451,
"UpdateAgentInput!"
]
}
@@ -8633,7 +8644,7 @@ export default {
10,
{
"input": [
- 378,
+ 379,
"AgentIdInput!"
]
}
@@ -8642,7 +8653,7 @@ export default {
23,
{
"input": [
- 451,
+ 452,
"CreateOneObjectInput!"
]
}
@@ -8651,7 +8662,7 @@ export default {
23,
{
"input": [
- 453,
+ 454,
"DeleteOneObjectInput!"
]
}
@@ -8660,7 +8671,7 @@ export default {
23,
{
"input": [
- 454,
+ 455,
"UpdateOneObjectInput!"
]
}
@@ -8669,7 +8680,7 @@ export default {
241,
{
"input": [
- 457,
+ 458,
"CreateOneIndexInput!"
]
}
@@ -8678,7 +8689,7 @@ export default {
241,
{
"input": [
- 460,
+ 461,
"DeleteOneIndexInput!"
]
}
@@ -8687,7 +8698,7 @@ export default {
21,
{
"input": [
- 380,
+ 381,
"LogicFunctionIdInput!"
]
}
@@ -8696,7 +8707,7 @@ export default {
21,
{
"input": [
- 461,
+ 462,
"CreateLogicFunctionFromSourceInput!"
]
}
@@ -8705,7 +8716,7 @@ export default {
147,
{
"input": [
- 462,
+ 463,
"ExecuteOneLogicFunctionInput!"
]
}
@@ -8714,7 +8725,7 @@ export default {
8,
{
"input": [
- 463,
+ 464,
"UpdateLogicFunctionFromSourceInput!"
]
}
@@ -8723,7 +8734,7 @@ export default {
14,
{
"input": [
- 465,
+ 466,
"CreateCommandMenuItemInput!"
]
}
@@ -8732,7 +8743,7 @@ export default {
14,
{
"input": [
- 466,
+ 467,
"UpdateCommandMenuItemInput!"
]
}
@@ -8759,7 +8770,7 @@ export default {
13,
{
"input": [
- 467,
+ 468,
"CreateFrontComponentInput!"
]
}
@@ -8768,7 +8779,7 @@ export default {
13,
{
"input": [
- 468,
+ 469,
"UpdateFrontComponentInput!"
]
}
@@ -8786,7 +8797,7 @@ export default {
67,
{
"data": [
- 470,
+ 471,
"ActivateWorkspaceInput!"
]
}
@@ -8795,7 +8806,7 @@ export default {
67,
{
"data": [
- 471,
+ 472,
"UpdateWorkspaceInput!"
]
}
@@ -8826,7 +8837,7 @@ export default {
210,
{
"input": [
- 472,
+ 473,
"CreateApplicationRegistrationInput!"
]
}
@@ -8835,7 +8846,7 @@ export default {
73,
{
"input": [
- 473,
+ 474,
"UpdateApplicationRegistrationInput!"
]
}
@@ -8862,7 +8873,7 @@ export default {
183,
{
"input": [
- 475,
+ 476,
"CreateApplicationRegistrationVariableInput!"
]
}
@@ -8871,7 +8882,7 @@ export default {
183,
{
"input": [
- 476,
+ 477,
"UpdateApplicationRegistrationVariableInput!"
]
}
@@ -8889,7 +8900,7 @@ export default {
73,
{
"file": [
- 399,
+ 400,
"Upload!"
],
"universalIdentifier": [
@@ -8951,7 +8962,7 @@ export default {
"UUID!"
],
"input": [
- 478,
+ 479,
"UpdateApplicationInput!"
]
}
@@ -8972,7 +8983,7 @@ export default {
233,
{
"input": [
- 479,
+ 480,
"CreateOneFieldMetadataInput!"
]
}
@@ -8981,7 +8992,7 @@ export default {
233,
{
"input": [
- 481,
+ 482,
"UpdateOneFieldMetadataInput!"
]
}
@@ -8990,7 +9001,7 @@ export default {
233,
{
"input": [
- 483,
+ 484,
"DeleteOneFieldInput!"
]
}
@@ -8999,7 +9010,7 @@ export default {
57,
{
"input": [
- 484,
+ 485,
"CreateViewGroupInput!"
]
}
@@ -9008,7 +9019,7 @@ export default {
57,
{
"inputs": [
- 484,
+ 485,
"[CreateViewGroupInput!]!"
]
}
@@ -9017,7 +9028,7 @@ export default {
57,
{
"input": [
- 485,
+ 486,
"UpdateViewGroupInput!"
]
}
@@ -9026,7 +9037,7 @@ export default {
57,
{
"inputs": [
- 485,
+ 486,
"[UpdateViewGroupInput!]!"
]
}
@@ -9035,7 +9046,7 @@ export default {
57,
{
"input": [
- 487,
+ 488,
"DeleteViewGroupInput!"
]
}
@@ -9044,7 +9055,7 @@ export default {
57,
{
"input": [
- 488,
+ 489,
"DestroyViewGroupInput!"
]
}
@@ -9066,7 +9077,7 @@ export default {
46,
{
"createRoleInput": [
- 489,
+ 490,
"CreateRoleInput!"
]
}
@@ -9075,7 +9086,7 @@ export default {
46,
{
"updateRoleInput": [
- 490,
+ 491,
"UpdateRoleInput!"
]
}
@@ -9093,7 +9104,7 @@ export default {
43,
{
"upsertObjectPermissionsInput": [
- 492,
+ 493,
"UpsertObjectPermissionsInput!"
]
}
@@ -9102,7 +9113,7 @@ export default {
44,
{
"upsertPermissionFlagsInput": [
- 494,
+ 495,
"UpsertPermissionFlagsInput!"
]
}
@@ -9111,7 +9122,7 @@ export default {
38,
{
"upsertFieldPermissionsInput": [
- 495,
+ 496,
"UpsertFieldPermissionsInput!"
]
}
@@ -9120,7 +9131,7 @@ export default {
254,
{
"input": [
- 497,
+ 498,
"UpsertRowLevelPermissionPredicatesInput!"
]
}
@@ -9148,46 +9159,55 @@ export default {
}
],
"sendEmailViaEmailingDomain": [
- 306,
+ 307,
{
"input": [
- 500,
+ 501,
"SendEmailViaDomainInput!"
]
}
],
"sendMessageCampaign": [
- 308,
+ 309,
{
"input": [
- 501,
+ 502,
"SendMessageCampaignInput!"
]
}
],
- "sendMessageCampaignTest": [
+ "cancelMessageCampaign": [
306,
{
"input": [
- 502,
+ 503,
+ "CancelMessageCampaignInput!"
+ ]
+ }
+ ],
+ "sendMessageCampaignTest": [
+ 307,
+ {
+ "input": [
+ 504,
"SendMessageCampaignTestInput!"
]
}
],
"createUnsubscribeTopic": [
- 313,
+ 314,
{
"input": [
- 503,
+ 505,
"CreateUnsubscribeTopicInput!"
]
}
],
"updateUnsubscribeTopic": [
- 313,
+ 314,
{
"input": [
- 504,
+ 506,
"UpdateUnsubscribeTopicInput!"
]
}
@@ -9205,7 +9225,7 @@ export default {
296,
{
"input": [
- 505,
+ 507,
"UpdateMessageChannelInput!"
]
}
@@ -9214,7 +9234,7 @@ export default {
304,
{
"input": [
- 507,
+ 509,
"CreateEmailGroupChannelInput!"
]
}
@@ -9223,7 +9243,7 @@ export default {
296,
{
"input": [
- 508,
+ 510,
"UpdateEmailGroupChannelInput!"
]
}
@@ -9241,7 +9261,7 @@ export default {
294,
{
"input": [
- 509,
+ 511,
"CreateEmailingDomainInput!"
]
}
@@ -9265,34 +9285,34 @@ export default {
}
],
"runAgent": [
- 325,
+ 326,
{
"input": [
- 510,
+ 512,
"RunAgentInput!"
]
}
],
"createWebhook": [
- 322,
+ 323,
{
"input": [
- 513,
+ 515,
"CreateWebhookInput!"
]
}
],
"updateWebhook": [
- 322,
+ 323,
{
"input": [
- 514,
+ 516,
"UpdateWebhookInput!"
]
}
],
"deleteWebhook": [
- 322,
+ 323,
{
"id": [
3,
@@ -9301,37 +9321,37 @@ export default {
}
],
"updateMessageFolder": [
- 364,
+ 365,
{
"input": [
- 516,
+ 518,
"UpdateMessageFolderInput!"
]
}
],
"updateMessageFolders": [
- 364,
+ 365,
{
"input": [
- 518,
+ 520,
"UpdateMessageFoldersInput!"
]
}
],
"updateCalendarChannel": [
- 359,
+ 360,
{
"input": [
- 519,
+ 521,
"UpdateCalendarChannelInput!"
]
}
],
"setAppKeyValue": [
- 357,
+ 358,
{
"input": [
- 521,
+ 523,
"SetAppKeyValueInput!"
]
}
@@ -9344,33 +9364,33 @@ export default {
"String!"
],
"scope": [
- 358
+ 359
]
}
],
"enqueueJob": [
- 355,
+ 356,
{
"input": [
- 522,
+ 524,
"EnqueueJobInput!"
]
}
],
"enqueueJobs": [
- 356,
+ 357,
{
"input": [
- 523,
+ 525,
"EnqueueJobsInput!"
]
}
],
"createChatThread": [
- 343
+ 344
],
"sendChatMessage": [
- 348,
+ 349,
{
"threadId": [
3,
@@ -9391,13 +9411,13 @@ export default {
1
],
"fileAttachments": [
- 524,
+ 526,
"[FileAttachmentInput!]"
]
}
],
"retryChatMessage": [
- 348,
+ 349,
{
"threadId": [
3,
@@ -9409,7 +9429,7 @@ export default {
}
],
"answerAgentChatQuestion": [
- 348,
+ 349,
{
"threadId": [
3,
@@ -9420,14 +9440,14 @@ export default {
"UUID!"
],
"answers": [
- 525,
+ 527,
"[AgentChatQuestionAnswerInput!]!"
],
"modelId": [
1
],
"fileAttachments": [
- 524,
+ 526,
"[FileAttachmentInput!]"
]
}
@@ -9442,7 +9462,7 @@ export default {
}
],
"renameChatThread": [
- 343,
+ 344,
{
"id": [
3,
@@ -9455,7 +9475,7 @@ export default {
}
],
"archiveChatThread": [
- 343,
+ 344,
{
"id": [
3,
@@ -9464,7 +9484,7 @@ export default {
}
],
"unarchiveChatThread": [
- 343,
+ 344,
{
"id": [
3,
@@ -9491,7 +9511,7 @@ export default {
}
],
"startWorkspaceSetupChat": [
- 350,
+ 351,
{
"companyContext": [
9
@@ -9502,25 +9522,25 @@ export default {
}
],
"createSkill": [
- 341,
+ 342,
{
"input": [
- 526,
+ 528,
"CreateSkillInput!"
]
}
],
"updateSkill": [
- 341,
+ 342,
{
"input": [
- 527,
+ 529,
"UpdateSkillInput!"
]
}
],
"deleteSkill": [
- 341,
+ 342,
{
"id": [
3,
@@ -9529,7 +9549,7 @@ export default {
}
],
"activateSkill": [
- 341,
+ 342,
{
"id": [
3,
@@ -9538,7 +9558,7 @@ export default {
}
],
"deactivateSkill": [
- 341,
+ 342,
{
"id": [
3,
@@ -9547,7 +9567,7 @@ export default {
}
],
"evaluateAgentTurn": [
- 352,
+ 353,
{
"turnId": [
3,
@@ -9556,7 +9576,7 @@ export default {
}
],
"runEvaluationInput": [
- 353,
+ 354,
{
"agentId": [
3,
@@ -9569,16 +9589,16 @@ export default {
}
],
"updateTimelineActivityType": [
- 370,
+ 371,
{
"input": [
- 528,
+ 530,
"UpdateTimelineActivityTypeInput!"
]
}
],
"resetTimelineActivityType": [
- 370,
+ 371,
{
"id": [
3,
@@ -9590,7 +9610,7 @@ export default {
263,
{
"input": [
- 529,
+ 531,
"GetAuthorizationUrlForSSOInput!"
]
}
@@ -9756,7 +9776,7 @@ export default {
266,
{
"input": [
- 530
+ 532
]
}
],
@@ -9768,7 +9788,7 @@ export default {
"String!"
],
"file": [
- 399,
+ 400,
"Upload!"
]
}
@@ -9934,7 +9954,7 @@ export default {
8,
{
"input": [
- 531,
+ 533,
"UpdateWorkspaceMemberSettingsInput!"
]
}
@@ -9968,7 +9988,7 @@ export default {
220,
{
"input": [
- 532,
+ 534,
"SetupOIDCSsoInput!"
]
}
@@ -9977,7 +9997,7 @@ export default {
220,
{
"input": [
- 533,
+ 535,
"SetupSAMLSsoInput!"
]
}
@@ -9986,7 +10006,7 @@ export default {
216,
{
"input": [
- 534,
+ 536,
"DeleteSsoInput!"
]
}
@@ -9995,13 +10015,13 @@ export default {
217,
{
"input": [
- 535,
+ 537,
"EditSsoInput!"
]
}
],
"createObjectEvent": [
- 337,
+ 338,
{
"event": [
1,
@@ -10021,10 +10041,10 @@ export default {
}
],
"trackAnalytics": [
- 337,
+ 338,
{
"type": [
- 536,
+ 538,
"AnalyticsType!"
],
"name": [
@@ -10039,7 +10059,7 @@ export default {
}
],
"duplicateDashboard": [
- 335,
+ 336,
{
"id": [
3,
@@ -10064,25 +10084,25 @@ export default {
278
],
"createCalendarEvent": [
- 327,
+ 328,
{
"input": [
- 537,
+ 539,
"CreateCalendarEventInput!"
]
}
],
"sendEmail": [
- 336,
+ 337,
{
"input": [
- 538,
+ 540,
"SendEmailInput!"
]
}
],
"startChannelSync": [
- 326,
+ 327,
{
"connectedAccountId": [
3,
@@ -10091,14 +10111,14 @@ export default {
}
],
"saveImapSmtpCaldavAccount": [
- 321,
+ 322,
{
"handle": [
1,
"String!"
],
"connectionParameters": [
- 540,
+ 542,
"EmailAccountConnectionParameters!"
],
"id": [
@@ -10110,7 +10130,7 @@ export default {
180,
{
"input": [
- 542,
+ 544,
"UpdateLabPublicFeatureFlagInput!"
]
}
@@ -10175,7 +10195,7 @@ export default {
283,
{
"file": [
- 399,
+ 400,
"Upload!"
],
"applicationUniversalIdentifier": [
@@ -10200,7 +10220,7 @@ export default {
"String!"
],
"files": [
- 543,
+ 545,
"[ApplicationFileUploadRequestInput!]!"
]
}
@@ -10323,7 +10343,7 @@ export default {
3
],
"update": [
- 398
+ 399
],
"__typename": [
1
@@ -10462,7 +10482,7 @@ export default {
3
],
"update": [
- 405
+ 406
],
"__typename": [
1
@@ -10633,19 +10653,19 @@ export default {
3
],
"view": [
- 411
+ 412
],
"viewFields": [
- 412
+ 413
],
"viewFilters": [
- 413
+ 414
],
"viewFilterGroups": [
- 414
+ 415
],
"viewSorts": [
- 415
+ 416
],
"__typename": [
1
@@ -10794,7 +10814,7 @@ export default {
3
],
"update": [
- 418
+ 419
],
"__typename": [
1
@@ -10832,7 +10852,7 @@ export default {
3
],
"update": [
- 422
+ 423
],
"__typename": [
1
@@ -10908,7 +10928,7 @@ export default {
3
],
"update": [
- 427
+ 428
],
"__typename": [
1
@@ -10972,10 +10992,10 @@ export default {
3
],
"groups": [
- 432
+ 433
],
"fields": [
- 433
+ 434
],
"__typename": [
1
@@ -10995,7 +11015,7 @@ export default {
8
],
"fields": [
- 433
+ 434
],
"__typename": [
1
@@ -11166,7 +11186,7 @@ export default {
8
],
"tabs": [
- 445
+ 446
],
"__typename": [
1
@@ -11189,7 +11209,7 @@ export default {
86
],
"widgets": [
- 446
+ 447
],
"__typename": [
1
@@ -11354,7 +11374,7 @@ export default {
},
"CreateOneObjectInput": {
"object": [
- 452
+ 453
],
"__typename": [
1
@@ -11414,7 +11434,7 @@ export default {
},
"UpdateOneObjectInput": {
"update": [
- 455
+ 456
],
"id": [
3
@@ -11467,7 +11487,7 @@ export default {
24
],
"translations": [
- 456
+ 457
],
"__typename": [
1
@@ -11489,7 +11509,7 @@ export default {
},
"CreateOneIndexInput": {
"index": [
- 458
+ 459
],
"__typename": [
1
@@ -11500,7 +11520,7 @@ export default {
3
],
"fields": [
- 459
+ 460
],
"indexType": [
242
@@ -11585,7 +11605,7 @@ export default {
3
],
"update": [
- 464
+ 465
],
"__typename": [
1
@@ -11745,7 +11765,7 @@ export default {
3
],
"update": [
- 469
+ 470
],
"__typename": [
1
@@ -11872,7 +11892,7 @@ export default {
1
],
"update": [
- 474
+ 475
],
"__typename": [
1
@@ -11926,7 +11946,7 @@ export default {
1
],
"update": [
- 477
+ 478
],
"__typename": [
1
@@ -11956,7 +11976,7 @@ export default {
},
"CreateOneFieldMetadataInput": {
"field": [
- 480
+ 481
],
"__typename": [
1
@@ -12029,7 +12049,7 @@ export default {
3
],
"update": [
- 482
+ 483
],
"__typename": [
1
@@ -12088,7 +12108,7 @@ export default {
9
],
"translations": [
- 456
+ 457
],
"__typename": [
1
@@ -12127,7 +12147,7 @@ export default {
3
],
"update": [
- 486
+ 487
],
"__typename": [
1
@@ -12212,7 +12232,7 @@ export default {
},
"UpdateRoleInput": {
"update": [
- 491
+ 492
],
"id": [
3
@@ -12267,7 +12287,7 @@ export default {
3
],
"objectPermissions": [
- 493
+ 494
],
"__typename": [
1
@@ -12309,7 +12329,7 @@ export default {
3
],
"fieldPermissions": [
- 496
+ 497
],
"__typename": [
1
@@ -12340,10 +12360,10 @@ export default {
3
],
"predicates": [
- 498
+ 499
],
"predicateGroups": [
- 499
+ 500
],
"__typename": [
1
@@ -12441,6 +12461,14 @@ export default {
1
]
},
+ "CancelMessageCampaignInput": {
+ "campaignId": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"SendMessageCampaignTestInput": {
"toAddress": [
1
@@ -12469,7 +12497,7 @@ export default {
1
],
"visibility": [
- 314
+ 315
],
"__typename": [
1
@@ -12486,7 +12514,7 @@ export default {
1
],
"visibility": [
- 314
+ 315
],
"__typename": [
1
@@ -12497,7 +12525,7 @@ export default {
3
],
"update": [
- 506
+ 508
],
"__typename": [
1
@@ -12570,7 +12598,7 @@ export default {
3
],
"messages": [
- 511
+ 513
],
"__typename": [
1
@@ -12578,7 +12606,7 @@ export default {
},
"RunAgentMessageInput": {
"role": [
- 512
+ 514
],
"content": [
1
@@ -12613,7 +12641,7 @@ export default {
3
],
"update": [
- 515
+ 517
],
"__typename": [
1
@@ -12641,7 +12669,7 @@ export default {
3
],
"update": [
- 517
+ 519
],
"__typename": [
1
@@ -12660,7 +12688,7 @@ export default {
3
],
"update": [
- 517
+ 519
],
"__typename": [
1
@@ -12671,7 +12699,7 @@ export default {
3
],
"update": [
- 520
+ 522
],
"__typename": [
1
@@ -12679,13 +12707,13 @@ export default {
},
"UpdateCalendarChannelInputUpdates": {
"visibility": [
- 362
+ 363
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 363
+ 364
],
"isSyncEnabled": [
8
@@ -12702,7 +12730,7 @@ export default {
9
],
"scope": [
- 358
+ 359
],
"__typename": [
1
@@ -12830,7 +12858,7 @@ export default {
8
],
"translations": [
- 456
+ 457
],
"__typename": [
1
@@ -12996,7 +13024,7 @@ export default {
1
],
"files": [
- 539
+ 541
],
"__typename": [
1
@@ -13018,13 +13046,13 @@ export default {
1
],
"IMAP": [
- 541
+ 543
],
"SMTP": [
- 541
+ 543
],
"CALDAV": [
- 541
+ 543
],
"__typename": [
1
@@ -13089,13 +13117,13 @@ export default {
255,
{
"input": [
- 545,
+ 547,
"LogicFunctionLogsInput!"
]
}
],
"onAgentChatEvent": [
- 349,
+ 350,
{
"threadId": [
3,
@@ -13104,10 +13132,10 @@ export default {
}
],
"eventLogsLive": [
- 338,
+ 339,
{
"table": [
- 386,
+ 387,
"EventLogTable!"
]
}
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 29a72cdbabd..3c346fe0bb1 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -904,6 +904,16 @@ export type CampaignSkippedRecipientsDto = {
overCap: Scalars['Int']['output'];
};
+export type CancelMessageCampaignInput = {
+ campaignId: Scalars['String']['input'];
+};
+
+export type CancelMessageCampaignOutputDto = {
+ __typename?: 'CancelMessageCampaignOutputDTO';
+ campaignId: Scalars['String']['output'];
+ canceledMessageCount: Scalars['Int']['output'];
+};
+
export type Captcha = {
__typename?: 'Captcha';
provider?: Maybe<CaptchaDriverType>;
@@ -2699,6 +2709,7 @@ export type Mutation = {
assignRoleToAgent: Scalars['Boolean']['output'];
assignRoleToApiKey: Scalars['Boolean']['output'];
authorizeApp: AuthorizeApp;
+ cancelMessageCampaign: CancelMessageCampaignOutputDto;
cancelSwitchBillingInterval: BillingUpdate;
cancelSwitchBillingPlan: BillingUpdate;
cancelSwitchResourceCreditPrice: BillingUpdate;
@@ -2995,6 +3006,11 @@ export type MutationAuthorizeAppArgs = {
};
+export type MutationCancelMessageCampaignArgs = {
+ input: CancelMessageCampaignInput;
+};
+
+
export type MutationCheckPublicDomainValidRecordsArgs = {
domain: Scalars['String']['input'];
};
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 9e6f2120b2b..2713b372557 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
@@ -17,6 +17,7 @@ import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twent
import { UserSessionCleanupCronCommand } from 'src/engine/core-modules/user-session/crons/commands/user-session-cleanup.cron.command';
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 { 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';
@@ -54,6 +55,8 @@ export class CronRegisterAllCommand extends CommandRunner {
private readonly webhookSubscriptionRenewalCronCommand: WebhookSubscriptionRenewalCronCommand,
+ private readonly emailingOngoingStaleCronCommand: EmailingOngoingStaleCronCommand,
+
private readonly workflowCronTriggerCronCommand: WorkflowCronTriggerCronCommand,
private readonly workflowRunEnqueueCronCommand: WorkflowRunEnqueueCronCommand,
private readonly workflowHandleStaledRunsCronCommand: WorkflowHandleStaledRunsCronCommand,
@@ -130,6 +133,10 @@ export class CronRegisterAllCommand extends CommandRunner {
name: 'WebhookSubscriptionRenewal',
command: this.webhookSubscriptionRenewalCronCommand,
},
+ {
+ name: 'EmailingOngoingStale',
+ command: this.emailingOngoingStaleCronCommand,
+ },
{
name: 'CheckCustomDomainValidRecords',
command: this.checkCustomDomainValidRecordsCronCommand,
diff --git a/packages/twenty-server/src/database/commands/database-command.module.ts b/packages/twenty-server/src/database/commands/database-command.module.ts
index 8f191ce8414..1507df75556 100644
--- a/packages/twenty-server/src/database/commands/database-command.module.ts
+++ b/packages/twenty-server/src/database/commands/database-command.module.ts
@@ -52,6 +52,7 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
import { WorkspaceVersionModule } from 'src/engine/workspace-manager/workspace-version/workspace-version.module';
import { WebhookSubscriptionModule } from 'src/modules/connected-account/webhook-subscription-manager/webhook-subscription.module';
import { CalendarEventImportManagerModule } from 'src/modules/calendar/calendar-event-import-manager/calendar-event-import-manager.module';
+import { EmailingModule } from 'src/modules/emailing/emailing.module';
import { MessagingImportManagerModule } from 'src/modules/messaging/message-import-manager/messaging-import-manager.module';
import { WorkflowRunQueueModule } from 'src/modules/workflow/workflow-runner/workflow-run-queue/workflow-run-queue.module';
import { AutomatedTriggerModule } from 'src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.module';
@@ -65,6 +66,7 @@ import { WorkflowCoreConsistencyModule } from 'src/modules/workflow/workflow-cor
MessagingImportManagerModule,
CalendarEventImportManagerModule,
WebhookSubscriptionModule,
+ EmailingModule,
AutomatedTriggerModule,
WorkflowCoreConsistencyModule,
FileModule,
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant.ts
new file mode 100644
index 00000000000..55a8624b718
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant.ts
@@ -0,0 +1,7 @@
+import { type QueueJobBackoffOptions } from 'src/engine/core-modules/message-queue/drivers/interfaces/job-options.interface';
+
+export const CAMPAIGN_SEND_RETRY_BACKOFF = {
+ strategy: 'exponential',
+ initialDelayMilliseconds: 30_000,
+ jitter: 0.5,
+} as const satisfies QueueJobBackoffOptions;
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 11fe1c43fe0..728cb4e23a3 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
@@ -8,6 +8,7 @@ export const CAMPAIGN_MESSAGE_DELIVERY_STATUS = {
} 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';
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/cancel-message-campaign-output.dto.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/cancel-message-campaign-output.dto.ts
new file mode 100644
index 00000000000..55f23a9a718
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/cancel-message-campaign-output.dto.ts
@@ -0,0 +1,10 @@
+import { Field, Int, ObjectType } from '@nestjs/graphql';
+
+@ObjectType()
+export class CancelMessageCampaignOutputDTO {
+ @Field(() => String)
+ campaignId: string;
+
+ @Field(() => Int)
+ canceledMessageCount: number;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/cancel-message-campaign.input.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/cancel-message-campaign.input.ts
new file mode 100644
index 00000000000..8c4341b1f0a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/dtos/cancel-message-campaign.input.ts
@@ -0,0 +1,10 @@
+import { Field, InputType } from '@nestjs/graphql';
+
+import { IsUUID } from 'class-validator';
+
+@InputType()
+export class CancelMessageCampaignInput {
+ @Field(() => String)
+ @IsUUID('4')
+ campaignId: string;
+}
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
new file mode 100644
index 00000000000..f007314bf5a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-count-group.type.ts
@@ -0,0 +1,9 @@
+import { type CampaignDeliveryState } from 'src/engine/core-modules/emailing-domain/types/campaign-delivery-state.type';
+
+export type CampaignCountGroup = {
+ state: CampaignDeliveryState;
+ total: string;
+ deliveredCount: string;
+ bouncedCount: string;
+ complainedCount: string;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-counts.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-counts.type.ts
new file mode 100644
index 00000000000..c041b2c5bbd
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/campaign-counts.type.ts
@@ -0,0 +1,10 @@
+export type CampaignCounts = {
+ totalCount: number;
+ inProgressCount: number;
+ sentCount: number;
+ deliveredCount: number;
+ failedCount: number;
+ skippedCount: number;
+ bouncedCount: number;
+ complainedCount: 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
new file mode 100644
index 00000000000..8cb98427a8c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/materialize-campaign-chunk-job-data.type.ts
@@ -0,0 +1,15 @@
+import { type CampaignMessageRecipient } from 'src/modules/emailing/types/campaign-message-recipient.type';
+
+export type MaterializeCampaignChunkJobData = {
+ workspaceId: string;
+ campaignId: string;
+ messageChannelId: string;
+ emailingDomainId: string;
+ // Stamped once by the planning job so every chunk shares one receivedAt,
+ // the way a single looping job used to.
+ receivedAtIso: string;
+ // False for recipients a previous attempt already materialised: their rows
+ // exist and only the send job is missing.
+ shouldCreateMessages: boolean;
+ recipients: CampaignMessageRecipient[];
+};
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
new file mode 100644
index 00000000000..45c73f159e8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/compute-campaign-counts.util.spec.ts
@@ -0,0 +1,98 @@
+import { CAMPAIGN_DELIVERY_STATE } from 'src/engine/core-modules/emailing-domain/constants/campaign-delivery-state.constant';
+import { type CampaignCountGroup } from 'src/engine/core-modules/emailing-domain/types/campaign-count-group.type';
+import { computeCampaignCounts } from 'src/engine/core-modules/emailing-domain/utils/compute-campaign-counts.util';
+
+const buildGroup = (
+ overrides: Partial<CampaignCountGroup>,
+): CampaignCountGroup => ({
+ state: CAMPAIGN_DELIVERY_STATE.SENT,
+ total: '0',
+ deliveredCount: '0',
+ bouncedCount: '0',
+ complainedCount: '0',
+ ...overrides,
+});
+
+describe('computeCampaignCounts', () => {
+ it('keeps counting a delivered message as sent', () => {
+ const counts = computeCampaignCounts({
+ groups: [buildGroup({ total: '1', deliveredCount: '1' })],
+ });
+
+ expect(counts.sentCount).toBe(1);
+ expect(counts.deliveredCount).toBe(1);
+ });
+
+ it('counts a complaint against a delivered message without losing either', () => {
+ const counts = computeCampaignCounts({
+ groups: [
+ buildGroup({ total: '1', deliveredCount: '1', complainedCount: '1' }),
+ ],
+ });
+
+ expect(counts.sentCount).toBe(1);
+ expect(counts.deliveredCount).toBe(1);
+ expect(counts.complainedCount).toBe(1);
+ });
+
+ it('does not count a message we never sent', () => {
+ const counts = computeCampaignCounts({
+ groups: [
+ buildGroup({ state: CAMPAIGN_DELIVERY_STATE.SKIPPED, total: '1' }),
+ buildGroup({ state: CAMPAIGN_DELIVERY_STATE.FAILED, total: '1' }),
+ ],
+ });
+
+ expect(counts.sentCount).toBe(0);
+ expect(counts.skippedCount).toBe(1);
+ expect(counts.failedCount).toBe(1);
+ });
+
+ it('counts a bounce for a message that was sent', () => {
+ const counts = computeCampaignCounts({
+ groups: [buildGroup({ total: '1', bouncedCount: '1' })],
+ });
+
+ expect(counts.sentCount).toBe(1);
+ expect(counts.bouncedCount).toBe(1);
+ expect(counts.deliveredCount).toBe(0);
+ });
+
+ it('treats everything still queued or sending as in progress', () => {
+ const counts = computeCampaignCounts({
+ groups: [
+ buildGroup({ state: CAMPAIGN_DELIVERY_STATE.QUEUED, total: '7' }),
+ buildGroup({ state: CAMPAIGN_DELIVERY_STATE.SENDING, total: '3' }),
+ ],
+ });
+
+ expect(counts.inProgressCount).toBe(10);
+ expect(counts.totalCount).toBe(10);
+ });
+
+ it('adds every group up into one total', () => {
+ const counts = computeCampaignCounts({
+ groups: [
+ buildGroup({ state: CAMPAIGN_DELIVERY_STATE.SENT, total: '600' }),
+ buildGroup({ state: CAMPAIGN_DELIVERY_STATE.SKIPPED, total: '3' }),
+ buildGroup({ state: CAMPAIGN_DELIVERY_STATE.FAILED, total: '2' }),
+ ],
+ });
+
+ expect(counts.totalCount).toBe(605);
+ expect(counts.sentCount).toBe(600);
+ });
+
+ it('reads an empty campaign as all zeroes', () => {
+ expect(computeCampaignCounts({ groups: [] })).toEqual({
+ totalCount: 0,
+ inProgressCount: 0,
+ sentCount: 0,
+ deliveredCount: 0,
+ failedCount: 0,
+ skippedCount: 0,
+ bouncedCount: 0,
+ complainedCount: 0,
+ });
+ });
+});
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
new file mode 100644
index 00000000000..7163f223a9c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/compute-campaign-counts.util.ts
@@ -0,0 +1,44 @@
+import { CAMPAIGN_DELIVERY_STATE } from 'src/engine/core-modules/emailing-domain/constants/campaign-delivery-state.constant';
+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';
+
+const EMPTY_CAMPAIGN_COUNTS: CampaignCounts = {
+ totalCount: 0,
+ inProgressCount: 0,
+ sentCount: 0,
+ deliveredCount: 0,
+ failedCount: 0,
+ skippedCount: 0,
+ bouncedCount: 0,
+ complainedCount: 0,
+};
+
+const countFailedInGroup = (group: CampaignCountGroup): number =>
+ group.state === CAMPAIGN_DELIVERY_STATE.FAILED ? Number(group.total) : 0;
+
+export const computeCampaignCounts = ({
+ groups,
+}: {
+ groups: CampaignCountGroup[];
+}): CampaignCounts =>
+ groups.reduce<CampaignCounts>((counts, group) => {
+ const total = Number(group.total);
+ const isInProgress =
+ group.state === CAMPAIGN_DELIVERY_STATE.QUEUED ||
+ group.state === CAMPAIGN_DELIVERY_STATE.SENDING;
+
+ return {
+ totalCount: counts.totalCount + total,
+ inProgressCount: counts.inProgressCount + (isInProgress ? total : 0),
+ sentCount:
+ counts.sentCount +
+ (group.state === CAMPAIGN_DELIVERY_STATE.SENT ? total : 0),
+ skippedCount:
+ counts.skippedCount +
+ (group.state === CAMPAIGN_DELIVERY_STATE.SKIPPED ? total : 0),
+ failedCount: counts.failedCount + countFailedInGroup(group),
+ deliveredCount: counts.deliveredCount + Number(group.deliveredCount),
+ bouncedCount: counts.bouncedCount + Number(group.bouncedCount),
+ complainedCount: counts.complainedCount + Number(group.complainedCount),
+ };
+ }, EMPTY_CAMPAIGN_COUNTS);
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 94a912a6b7e..16630933ea3 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
@@ -24,6 +24,7 @@ import { OnboardingModule } from 'src/engine/core-modules/onboarding/onboarding.
import { EmailSenderJob } from 'src/engine/core-modules/email/email-sender.job';
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 { RefreshCampaignStatsJob } from 'src/modules/emailing/jobs/refresh-campaign-stats.job';
import { SendCampaignEmailJob } from 'src/modules/emailing/jobs/send-campaign-email.job';
@@ -111,6 +112,7 @@ import { WorkflowModule } from 'src/modules/workflow/workflow.module';
EmailSenderJob,
SendCampaignEmailJob,
MaterializeCampaignJob,
+ MaterializeCampaignChunkJob,
RefreshCampaignStatsJob,
UpdateSubscriptionQuantityJob,
HandleWorkspaceMemberDeletedJob,
diff --git a/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.ts b/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.ts
index f7372a98468..b10a4cacfce 100644
--- a/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.ts
@@ -57,11 +57,14 @@ export class WorkspaceDataSource {
getRepository<T extends ObjectLiteral = ObjectRecord>(
nameSingular: string,
rolePermissionConfig?: RolePermissionConfig,
+ repositoryOptions?: { shouldSkipEventEmission?: boolean },
): WorkspaceRepository<T> {
return this.buildRepository<T>({
nameSingular,
rolePermissionConfig,
executor: new PoolQueryExecutor({ pool: this.pool }),
+ shouldSkipEventEmission:
+ repositoryOptions?.shouldSkipEventEmission ?? false,
});
}
@@ -73,12 +76,15 @@ export class WorkspaceDataSource {
getRepository: <T extends ObjectLiteral = ObjectRecord>(
nameSingular: string,
rolePermissionConfig?: RolePermissionConfig,
+ repositoryOptions?: { shouldSkipEventEmission?: boolean },
) =>
this.buildRepository<T>({
nameSingular,
rolePermissionConfig,
executor,
isTransactional: true,
+ shouldSkipEventEmission:
+ repositoryOptions?.shouldSkipEventEmission ?? false,
}),
executeRawQuery: (sql, parameters = []) =>
executor.execute({ text: sql, values: parameters }),
@@ -100,11 +106,13 @@ export class WorkspaceDataSource {
rolePermissionConfig,
executor,
isTransactional = false,
+ shouldSkipEventEmission = false,
}: {
nameSingular: string;
rolePermissionConfig?: RolePermissionConfig;
executor: QueryExecutor;
isTransactional?: boolean;
+ shouldSkipEventEmission?: boolean;
}): WorkspaceRepository<T> {
const objectMetadataId =
this.internalContext.objectIdByNameSingular[nameSingular];
@@ -121,6 +129,7 @@ export class WorkspaceDataSource {
rolePermissionConfig,
executor,
isTransactional,
+ shouldSkipEventEmission,
});
}
@@ -131,11 +140,13 @@ export class WorkspaceDataSource {
rolePermissionConfig,
executor,
isTransactional = false,
+ shouldSkipEventEmission = false,
}: {
objectMetadataId: string;
rolePermissionConfig?: RolePermissionConfig;
executor: QueryExecutor;
isTransactional?: boolean;
+ shouldSkipEventEmission?: boolean;
}): WorkspaceRepository<T> {
const flatObjectMetadata =
this.getFlatObjectMetadataOrThrow(objectMetadataId);
@@ -154,6 +165,7 @@ export class WorkspaceDataSource {
executor,
objectRecordsPermissions,
shouldBypassPermissionChecks,
+ shouldSkipEventEmission: shouldSkipEventEmission ?? false,
tableShapeByObjectMetadataId: (targetObjectMetadataId) =>
this.getTableShape(targetObjectMetadataId),
flatObjectMetadataByObjectMetadataId: (targetObjectMetadataId) =>
@@ -164,6 +176,7 @@ export class WorkspaceDataSource {
rolePermissionConfig,
executor,
isTransactional,
+ shouldSkipEventEmission,
}),
isTransactional,
runInNewTransaction: (work) =>
@@ -174,6 +187,7 @@ export class WorkspaceDataSource {
rolePermissionConfig,
executor: transactionExecutor,
isTransactional: true,
+ shouldSkipEventEmission,
}),
),
),
diff --git a/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts b/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts
index 1456f1c17c3..1b50d643e9a 100644
--- a/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts
@@ -97,6 +97,12 @@ type WorkspaceRepositoryOptions = {
executor: QueryExecutor;
objectRecordsPermissions: ObjectsPermissions;
shouldBypassPermissionChecks: boolean;
+ // Suppresses the CREATED/UPDATED/DELETED database events this repository
+ // would otherwise emit, and with them the snapshot SELECT that reads every
+ // written row back to build the event payload. Only for bulk system writes
+ // whose rows no subscriber cares about (campaign materialisation, backfills):
+ // webhooks, workflow triggers and timeline activities will NOT fire.
+ shouldSkipEventEmission: boolean;
tableShapeByObjectMetadataId: (
objectMetadataId: string,
) => WorkspaceTableShape;
@@ -1048,11 +1054,13 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
generatedMaps.push(...(result.generatedMaps as ObjectRecord[]));
- const recordsAfterWrite = await this.buildIdsEventSnapshotQueryBuilder([
- input.id,
- ]).getMany<ObjectRecord>({
- noFormatting: true,
- });
+ const recordsAfterWrite = this.options.shouldSkipEventEmission
+ ? []
+ : await this.buildIdsEventSnapshotQueryBuilder([
+ input.id,
+ ]).getMany<ObjectRecord>({
+ noFormatting: true,
+ });
recordsAfter.push(
...mergeReturnedUpdateTimestamps(
@@ -1140,7 +1148,7 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
}
private async emitCreateEvents(insertedIds: string[]): Promise<void> {
- if (insertedIds.length === 0) {
+ if (insertedIds.length === 0 || this.options.shouldSkipEventEmission) {
return;
}
@@ -1302,7 +1310,7 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
}
const recordsAfterWrite =
- kind === 'delete'
+ kind === 'delete' || this.options.shouldSkipEventEmission
? undefined
: await eventSelectQueryBuilder.getMany<ObjectRecord>({
noFormatting: true,
@@ -1413,6 +1421,10 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
recordsBefore: ObjectRecord[];
recordsAfter?: ObjectRecord[];
}): void {
+ if (this.options.shouldSkipEventEmission) {
+ return;
+ }
+
const actions = MUTATION_EVENT_ACTIONS_BY_KIND[kind];
const formattedBefore = this.formatResult<ObjectRecord[]>(recordsBefore);
diff --git a/packages/twenty-server/src/engine/twenty-orm/types/workspace-transaction-scope.type.ts b/packages/twenty-server/src/engine/twenty-orm/types/workspace-transaction-scope.type.ts
index ee8de8f0c93..cf45e3d20ad 100644
--- a/packages/twenty-server/src/engine/twenty-orm/types/workspace-transaction-scope.type.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/types/workspace-transaction-scope.type.ts
@@ -9,6 +9,7 @@ export type WorkspaceTransactionScope = {
getRepository: <T extends ObjectLiteral = ObjectRecord>(
objectMetadataName: string,
rolePermissionConfig?: RolePermissionConfig,
+ repositoryOptions?: { shouldSkipEventEmission?: boolean },
) => WorkspaceRepository<T>;
executeRawQuery: (
sql: string,
diff --git a/packages/twenty-server/src/engine/twenty-orm/workspace-orm.manager.ts b/packages/twenty-server/src/engine/twenty-orm/workspace-orm.manager.ts
index f9fde19dc4b..03331c14a2e 100644
--- a/packages/twenty-server/src/engine/twenty-orm/workspace-orm.manager.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/workspace-orm.manager.ts
@@ -29,19 +29,28 @@ export class WorkspaceOrmManager {
getRepository<T extends ObjectLiteral = ObjectRecord>(
workspaceEntity: Type<T>,
permissionOptions?: RolePermissionConfig,
- repositoryOptions?: { useReplica?: boolean },
+ repositoryOptions?: {
+ useReplica?: boolean;
+ shouldSkipEventEmission?: boolean;
+ },
): WorkspaceRepository<T>;
getRepository<T extends ObjectLiteral = ObjectRecord>(
objectMetadataName: string,
permissionOptions?: RolePermissionConfig,
- repositoryOptions?: { useReplica?: boolean },
+ repositoryOptions?: {
+ useReplica?: boolean;
+ shouldSkipEventEmission?: boolean;
+ },
): WorkspaceRepository<T>;
getRepository<T extends ObjectLiteral = ObjectRecord>(
workspaceEntityOrObjectMetadataName: Type<T> | string,
permissionOptions?: RolePermissionConfig,
- repositoryOptions?: { useReplica?: boolean },
+ repositoryOptions?: {
+ useReplica?: boolean;
+ shouldSkipEventEmission?: boolean;
+ },
): WorkspaceRepository<T> {
const objectMetadataName = this.resolveObjectMetadataName(
workspaceEntityOrObjectMetadataName,
@@ -49,7 +58,10 @@ export class WorkspaceOrmManager {
return this.workspaceDataSourceService
.getDataSource({ useReplica: repositoryOptions?.useReplica ?? false })
- .getRepository<T>(objectMetadataName, permissionOptions);
+ .getRepository<T>(objectMetadataName, permissionOptions, {
+ shouldSkipEventEmission:
+ repositoryOptions?.shouldSkipEventEmission ?? false,
+ });
}
private resolveObjectMetadataName<T extends ObjectLiteral>(
diff --git a/packages/twenty-server/src/modules/emailing/constants/emailing-ongoing-stale-cron-pattern.constant.ts b/packages/twenty-server/src/modules/emailing/constants/emailing-ongoing-stale-cron-pattern.constant.ts
new file mode 100644
index 00000000000..724ffe68d77
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/constants/emailing-ongoing-stale-cron-pattern.constant.ts
@@ -0,0 +1 @@
+export const EMAILING_ONGOING_STALE_CRON_PATTERN = '0 * * * *';
diff --git a/packages/twenty-server/src/modules/emailing/crons/commands/emailing-ongoing-stale.cron.command.ts b/packages/twenty-server/src/modules/emailing/crons/commands/emailing-ongoing-stale.cron.command.ts
new file mode 100644
index 00000000000..801b9a43769
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/crons/commands/emailing-ongoing-stale.cron.command.ts
@@ -0,0 +1,31 @@
+import { EMAILING_ONGOING_STALE_CRON_PATTERN } from 'src/modules/emailing/constants/emailing-ongoing-stale-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 { EmailingOngoingStaleCronJob } from 'src/modules/emailing/crons/jobs/emailing-ongoing-stale.cron.job';
+
+@Command({
+ name: 'cron:emailing:ongoing-stale',
+ description:
+ 'Starts a cron job to reconcile message campaigns left in the sending status',
+})
+export class EmailingOngoingStaleCronCommand extends CommandRunner {
+ constructor(
+ @InjectMessageQueue(MessageQueue.cronQueue)
+ private readonly messageQueueService: MessageQueueService,
+ ) {
+ super();
+ }
+
+ async run(): Promise<void> {
+ await this.messageQueueService.addCron<undefined>({
+ jobName: EmailingOngoingStaleCronJob.name,
+ data: undefined,
+ options: {
+ repeat: { pattern: EMAILING_ONGOING_STALE_CRON_PATTERN },
+ },
+ });
+ }
+}
diff --git a/packages/twenty-server/src/modules/emailing/crons/jobs/emailing-ongoing-stale.cron.job.ts b/packages/twenty-server/src/modules/emailing/crons/jobs/emailing-ongoing-stale.cron.job.ts
new file mode 100644
index 00000000000..3a8fcddbb7d
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/crons/jobs/emailing-ongoing-stale.cron.job.ts
@@ -0,0 +1,48 @@
+import { EMAILING_ONGOING_STALE_CRON_PATTERN } from 'src/modules/emailing/constants/emailing-ongoing-stale-cron-pattern.constant';
+import { Logger } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { Repository } from 'typeorm';
+import { WorkspaceActivationStatus } from 'twenty-shared/workspace';
+
+import { SentryCronMonitor } from 'src/engine/core-modules/cron/sentry-cron-monitor.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 { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { MessageCampaignRecoveryService } from 'src/modules/emailing/services/message-campaign-recovery.service';
+
+@Processor(MessageQueue.cronQueue)
+export class EmailingOngoingStaleCronJob {
+ private readonly logger = new Logger(EmailingOngoingStaleCronJob.name);
+
+ constructor(
+ @InjectRepository(WorkspaceEntity)
+ private readonly workspaceRepository: Repository<WorkspaceEntity>,
+ private readonly messageCampaignRecoveryService: MessageCampaignRecoveryService,
+ ) {}
+
+ @Process(EmailingOngoingStaleCronJob.name)
+ @SentryCronMonitor(
+ EmailingOngoingStaleCronJob.name,
+ EMAILING_ONGOING_STALE_CRON_PATTERN,
+ )
+ async handle(): Promise<void> {
+ const workspaces = await this.workspaceRepository.find({
+ where: { activationStatus: WorkspaceActivationStatus.ACTIVE },
+ select: ['id'],
+ });
+
+ for (const workspace of workspaces) {
+ await this.messageCampaignRecoveryService
+ .recoverOngoingStaleCampaigns({ workspaceId: workspace.id })
+ .catch((error) => {
+ this.logger.error(
+ `[${EmailingOngoingStaleCronJob.name}] Cannot recover ongoing stale campaigns of workspace ${workspace.id}: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ });
+ }
+ }
+}
diff --git a/packages/twenty-server/src/modules/emailing/emailing.module.ts b/packages/twenty-server/src/modules/emailing/emailing.module.ts
index 511c938a355..9c89bf7b426 100644
--- a/packages/twenty-server/src/modules/emailing/emailing.module.ts
+++ b/packages/twenty-server/src/modules/emailing/emailing.module.ts
@@ -4,10 +4,12 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
import { EmailingDomainModule } from 'src/engine/core-modules/emailing-domain/emailing-domain.module';
import { EmailingDomainEntity } from 'src/engine/core-modules/emailing-domain/emailing-domain.entity';
+import { CampaignDeliveryEntity } from 'src/engine/core-modules/emailing-domain/campaign-delivery.entity';
import { MessageSuppressionEntity } from 'src/engine/core-modules/emailing-domain/message-suppression.entity';
import { UnsubscribeTopicEntity } from 'src/engine/core-modules/emailing-domain/unsubscribe-topic.entity';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { MessageChannelMetadataModule } from 'src/engine/metadata-modules/message-channel/message-channel-metadata.module';
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
import { UserRoleModule } from 'src/engine/metadata-modules/user-role/user-role.module';
@@ -16,6 +18,8 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkspaceEventEmitterModule } from 'src/engine/workspace-event-emitter/workspace-event-emitter.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 { 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';
@@ -23,7 +27,13 @@ import { CampaignVariableService } from 'src/modules/emailing/services/campaign-
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';
+import { MessageCampaignRecoveryService } from 'src/modules/emailing/services/message-campaign-recovery.service';
import { MessageCampaignStatisticsService } from 'src/modules/emailing/services/message-campaign-statistics.service';
+import { MessageCampaignAudienceService } from 'src/modules/emailing/services/message-campaign-audience.service';
+import { MessageCampaignDeliveryFeedbackService } from 'src/modules/emailing/services/message-campaign-delivery-feedback.service';
+import { MessageCampaignDeliveryService } from 'src/modules/emailing/services/message-campaign-delivery.service';
+import { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';
+import { MessageCampaignMaterializationService } from 'src/modules/emailing/services/message-campaign-materialization.service';
import { MessageCampaignService } from 'src/modules/emailing/services/message-campaign.service';
import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';
import { UnsubscribeTopicService } from 'src/modules/emailing/services/unsubscribe-topic.service';
@@ -45,6 +55,8 @@ import { SaveCampaignTool } from 'src/modules/emailing/tools/save-campaign-tool'
EmailingDomainEntity,
MessageSuppressionEntity,
UnsubscribeTopicEntity,
+ CampaignDeliveryEntity,
+ WorkspaceEntity,
]),
],
controllers: [UnsubscribeController],
@@ -52,7 +64,13 @@ import { SaveCampaignTool } from 'src/modules/emailing/tools/save-campaign-tool'
CampaignVariableService,
EmailBillingService,
MessageCampaignService,
+ MessageCampaignAudienceService,
+ MessageCampaignDeliveryService,
+ MessageCampaignDeliveryFeedbackService,
+ MessageCampaignLifecycleService,
+ MessageCampaignMaterializationService,
MessageCampaignDraftService,
+ MessageCampaignRecoveryService,
MessageCampaignStatisticsService,
MessageSuppressionService,
UnsubscribeTopicService,
@@ -64,15 +82,22 @@ import { SaveCampaignTool } from 'src/modules/emailing/tools/save-campaign-tool'
provideWorkspaceScopedRepository(EmailingDomainEntity),
provideWorkspaceScopedRepository(MessageSuppressionEntity),
provideWorkspaceScopedRepository(UnsubscribeTopicEntity),
+ provideWorkspaceScopedRepository(CampaignDeliveryEntity),
+ EmailingOngoingStaleCronCommand,
+ EmailingOngoingStaleCronJob,
],
exports: [
EmailingDomainSenderService,
MessageCampaignService,
+ MessageCampaignDeliveryService,
+ MessageCampaignDeliveryFeedbackService,
+ MessageCampaignMaterializationService,
MessageCampaignDraftService,
MessageCampaignStatisticsService,
MessageSuppressionService,
UnsubscribeTopicService,
SaveCampaignTool,
+ EmailingOngoingStaleCronCommand,
],
})
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
new file mode 100644
index 00000000000..62824861b2c
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/jobs/materialize-campaign-chunk.job.ts
@@ -0,0 +1,20 @@
+import { MATERIALIZE_CAMPAIGN_CHUNK_JOB } from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
+import { type MaterializeCampaignChunkJobData } from 'src/engine/core-modules/emailing-domain/types/materialize-campaign-chunk-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 { MessageCampaignMaterializationService } from 'src/modules/emailing/services/message-campaign-materialization.service';
+
+@Processor(MessageQueue.emailQueue)
+export class MaterializeCampaignChunkJob {
+ constructor(
+ private readonly messageCampaignMaterializationService: MessageCampaignMaterializationService,
+ ) {}
+
+ @Process(MATERIALIZE_CAMPAIGN_CHUNK_JOB)
+ async handle(data: MaterializeCampaignChunkJobData): Promise<void> {
+ await this.messageCampaignMaterializationService.processMaterializeChunkJob(
+ data,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/modules/emailing/jobs/materialize-campaign.job.ts b/packages/twenty-server/src/modules/emailing/jobs/materialize-campaign.job.ts
index 4876a99ec0b..34f13be794f 100644
--- a/packages/twenty-server/src/modules/emailing/jobs/materialize-campaign.job.ts
+++ b/packages/twenty-server/src/modules/emailing/jobs/materialize-campaign.job.ts
@@ -3,16 +3,18 @@ import { type MaterializeCampaignJobData } from 'src/engine/core-modules/emailin
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 { MessageCampaignService } from 'src/modules/emailing/services/message-campaign.service';
+import { MessageCampaignMaterializationService } from 'src/modules/emailing/services/message-campaign-materialization.service';
@Processor(MessageQueue.emailQueue)
export class MaterializeCampaignJob {
constructor(
- private readonly messageCampaignService: MessageCampaignService,
+ private readonly messageCampaignMaterializationService: MessageCampaignMaterializationService,
) {}
@Process(MATERIALIZE_CAMPAIGN_JOB)
async handle(data: MaterializeCampaignJobData): Promise<void> {
- await this.messageCampaignService.processMaterializeJob(data);
+ await this.messageCampaignMaterializationService.processMaterializeJob(
+ data,
+ );
}
}
diff --git a/packages/twenty-server/src/modules/emailing/jobs/send-campaign-email.job.ts b/packages/twenty-server/src/modules/emailing/jobs/send-campaign-email.job.ts
index 3f3a51c52d2..f63a8627eab 100644
--- a/packages/twenty-server/src/modules/emailing/jobs/send-campaign-email.job.ts
+++ b/packages/twenty-server/src/modules/emailing/jobs/send-campaign-email.job.ts
@@ -1,5 +1,5 @@
import { SEND_CAMPAIGN_EMAIL_JOB } from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
-import { MessageCampaignService } from 'src/modules/emailing/services/message-campaign.service';
+import { MessageCampaignDeliveryService } from 'src/modules/emailing/services/message-campaign-delivery.service';
import { type SendCampaignEmailJobData } from 'src/engine/core-modules/emailing-domain/types/send-campaign-email-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';
@@ -8,11 +8,11 @@ import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queu
@Processor(MessageQueue.emailQueue)
export class SendCampaignEmailJob {
constructor(
- private readonly messageCampaignService: MessageCampaignService,
+ private readonly messageCampaignDeliveryService: MessageCampaignDeliveryService,
) {}
@Process(SEND_CAMPAIGN_EMAIL_JOB)
async handle(data: SendCampaignEmailJobData): Promise<void> {
- await this.messageCampaignService.processSendJob(data);
+ await this.messageCampaignDeliveryService.processSendJob(data);
}
}
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 db5ee1c6c61..7613c2a80dc 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
@@ -6,6 +6,8 @@ import { FeatureFlagKey } from 'twenty-shared/types';
import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
import { CampaignAudiencePreviewDTO } from 'src/engine/core-modules/emailing-domain/dtos/campaign-audience-preview.dto';
+import { CancelMessageCampaignInput } from 'src/engine/core-modules/emailing-domain/dtos/cancel-message-campaign.input';
+import { CancelMessageCampaignOutputDTO } from 'src/engine/core-modules/emailing-domain/dtos/cancel-message-campaign-output.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 { PreviewMessageCampaignAudienceInput } from 'src/engine/core-modules/emailing-domain/dtos/preview-message-campaign-audience.input';
@@ -27,6 +29,8 @@ import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.g
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
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';
@UseGuards(
@@ -44,6 +48,8 @@ export class EmailingSendResolver {
constructor(
private readonly emailingDomainSenderService: EmailingDomainSenderService,
private readonly messageCampaignService: MessageCampaignService,
+ private readonly messageCampaignAudienceService: MessageCampaignAudienceService,
+ private readonly messageCampaignLifecycleService: MessageCampaignLifecycleService,
private readonly emailGroupAccessService: EmailGroupAccessService,
private readonly emailBillingService: EmailBillingService,
) {}
@@ -93,6 +99,22 @@ export class EmailingSendResolver {
});
}
+ @Mutation(() => CancelMessageCampaignOutputDTO)
+ @RequireFeatureFlag(FeatureFlagKey.IS_EMAIL_GROUP_ENABLED)
+ async cancelMessageCampaign(
+ @Args('input') input: CancelMessageCampaignInput,
+ @AuthWorkspace() currentWorkspace: WorkspaceEntity,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
+ ): Promise<CancelMessageCampaignOutputDTO> {
+ this.emailGroupAccessService.validateEmailGroupAccessOrThrow();
+
+ return this.messageCampaignLifecycleService.cancelCampaignOrThrow({
+ workspaceId: currentWorkspace.id,
+ userWorkspaceId,
+ campaignId: input.campaignId,
+ });
+ }
+
@Mutation(() => SendEmailViaDomainOutputDTO)
@RequireFeatureFlag(FeatureFlagKey.IS_EMAIL_GROUP_ENABLED)
async sendMessageCampaignTest(
@@ -125,7 +147,7 @@ export class EmailingSendResolver {
): Promise<CampaignAudiencePreviewDTO> {
this.emailGroupAccessService.validateEmailGroupAccessOrThrow();
- return this.messageCampaignService.previewAudience({
+ return this.messageCampaignAudienceService.previewAudience({
workspaceId: currentWorkspace.id,
userWorkspaceId,
listId: input.listId,
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
new file mode 100644
index 00000000000..c3b14fd7953
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-audience.service.ts
@@ -0,0 +1,174 @@
+import { Injectable } from '@nestjs/common';
+
+import { isNonEmptyString } from '@sniptt/guards';
+import { In } from 'typeorm';
+
+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(
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly messageSuppressionService: MessageSuppressionService,
+ private readonly userRoleService: UserRoleService,
+ ) {}
+
+ async resolveNormalizedAudience({
+ workspaceId,
+ listId,
+ roleId,
+ }: {
+ workspaceId: string;
+ listId: string;
+ roleId: string;
+ }): Promise<NormalizedAudience> {
+ return this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ const rawRecipients = await this.resolveRecipientsFromList({
+ listId,
+ roleId,
+ });
+
+ return normalizeCampaignRecipients(
+ rawRecipients,
+ MAX_CAMPAIGN_RECIPIENTS,
+ );
+ });
+ }
+
+ async previewAudience({
+ workspaceId,
+ userWorkspaceId,
+ listId,
+ unsubscribeTopicId,
+ }: {
+ workspaceId: string;
+ userWorkspaceId: string;
+ listId: string;
+ unsubscribeTopicId?: string;
+ }): Promise<CampaignAudiencePreview> {
+ 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 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,
+ };
+ });
+ }
+
+ private async resolveRecipientsFromList({
+ listId,
+ roleId,
+ }: {
+ listId: string;
+ roleId: string;
+ }): Promise<RawCampaignRecipient[]> {
+ const listMemberRepository = this.workspaceOrmManager.getRepository(
+ MessageListMemberWorkspaceEntity,
+ { unionOf: [roleId] },
+ );
+
+ const members = await listMemberRepository.find({ where: { listId } });
+ const personIds = members.map((member) => member.personId);
+
+ if (personIds.length === 0) {
+ return [];
+ }
+
+ const personRepository = this.workspaceOrmManager.getRepository(
+ PersonWorkspaceEntity,
+ { unionOf: [roleId] },
+ );
+
+ const people = await personRepository.find({
+ where: { id: In(personIds) },
+ });
+
+ return people.map(toRawRecipient);
+ }
+}
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
new file mode 100644
index 00000000000..d3ca4de6cfe
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery-feedback.service.ts
@@ -0,0 +1,63 @@
+import { Injectable } from '@nestjs/common';
+
+import { CampaignDeliveryEntity } from 'src/engine/core-modules/emailing-domain/campaign-delivery.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 { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';
+import { isDefined } from 'twenty-shared/utils';
+
+@Injectable()
+export class MessageCampaignDeliveryFeedbackService {
+ constructor(
+ @InjectWorkspaceScopedRepository(CampaignDeliveryEntity)
+ private readonly campaignDeliveryRepository: WorkspaceScopedRepository<CampaignDeliveryEntity>,
+ private readonly messageCampaignLifecycleService: MessageCampaignLifecycleService,
+ ) {}
+
+ async recordProviderOutcomeByProviderMessageId({
+ workspaceId,
+ providerMessageId,
+ outcome,
+ }: {
+ workspaceId: string;
+ providerMessageId: string;
+ outcome: 'DELIVERED' | 'BOUNCED' | 'COMPLAINED';
+ }): Promise<void> {
+ const delivery = await this.campaignDeliveryRepository.findOneBy(
+ workspaceId,
+ { providerMessageId },
+ );
+
+ if (!isDefined(delivery)) {
+ return;
+ }
+
+ await this.campaignDeliveryRepository.update(
+ workspaceId,
+ { id: delivery.id },
+ this.buildOutcomeStamp(outcome),
+ );
+
+ await this.messageCampaignLifecycleService.scheduleStatsRefresh({
+ workspaceId,
+ campaignId: delivery.campaignId,
+ });
+ }
+
+ private buildOutcomeStamp(
+ outcome: 'DELIVERED' | 'BOUNCED' | 'COMPLAINED',
+ ): Partial<
+ Pick<CampaignDeliveryEntity, 'deliveredAt' | 'bouncedAt' | 'complainedAt'>
+ > {
+ const occurredAt = new Date();
+
+ switch (outcome) {
+ case 'DELIVERED':
+ return { deliveredAt: occurredAt };
+ case 'BOUNCED':
+ return { bouncedAt: occurredAt };
+ case 'COMPLAINED':
+ return { complainedAt: occurredAt };
+ }
+ }
+}
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
new file mode 100644
index 00000000000..7b149edaf19
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery.service.ts
@@ -0,0 +1,390 @@
+import { Injectable, Logger } from '@nestjs/common';
+
+import { In } from 'typeorm';
+
+import { CampaignDeliveryEntity } from 'src/engine/core-modules/emailing-domain/campaign-delivery.entity';
+import { CAMPAIGN_DELIVERY_CLAIM_TTL_MS } from 'src/engine/core-modules/emailing-domain/constants/campaign-delivery-claim-ttl-ms.constant';
+import { CAMPAIGN_DELIVERY_STATE } from 'src/engine/core-modules/emailing-domain/constants/campaign-delivery-state.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';
+import { v4 } from 'uuid';
+import { type EmailingDomainEmailContent } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-email-content.type';
+import { type EmailingDomainSendEmailResult } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-email-result.type';
+import { type SendCampaignEmailJobData } from 'src/engine/core-modules/emailing-domain/types/send-campaign-email-job-data.type';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace-repository';
+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 { 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';
+import { resolveCampaignSendFailure } from 'src/modules/emailing/utils/resolve-campaign-send-failure.util';
+import { renderCampaignEmail } from 'src/modules/emailing/utils/render-campaign-email.util';
+import { MessageChannelMessageAssociationWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel-message-association.workspace-entity';
+import { MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
+import { PersonWorkspaceEntity } from 'src/modules/person/standard-objects/person.workspace-entity';
+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;
+};
+
+@Injectable()
+export class MessageCampaignDeliveryService {
+ private readonly logger = new Logger(MessageCampaignDeliveryService.name);
+
+ constructor(
+ @InjectWorkspaceScopedRepository(CampaignDeliveryEntity)
+ private readonly campaignDeliveryRepository: WorkspaceScopedRepository<CampaignDeliveryEntity>,
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly emailingDomainSenderService: EmailingDomainSenderService,
+ private readonly emailBillingService: EmailBillingService,
+ private readonly campaignVariableService: CampaignVariableService,
+ private readonly messageCampaignLifecycleService: MessageCampaignLifecycleService,
+ ) {}
+
+ async processSendJob(data: SendCampaignEmailJobData): Promise<void> {
+ const { workspaceId, campaignId } = data;
+
+ await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ const messageRepository = this.workspaceOrmManager.getRepository(
+ MessageWorkspaceEntity,
+ { shouldBypassPermissionChecks: true },
+ );
+
+ const sendContext = await this.loadSendContext({ data });
+
+ if (!isDefined(sendContext)) {
+ return;
+ }
+
+ await this.deliverMessage({ data, messageRepository, sendContext });
+
+ await this.messageCampaignLifecycleService.finalizeCampaignIfComplete({
+ workspaceId,
+ campaignId,
+ });
+ }, buildSystemAuthContext(workspaceId));
+ }
+
+ private async loadSendContext({
+ data,
+ }: {
+ data: SendCampaignEmailJobData;
+ }): Promise<SendContext | null> {
+ const { workspaceId, campaignId, messageId, personId } = data;
+
+ const campaignRepository = this.workspaceOrmManager.getRepository(
+ MessageCampaignWorkspaceEntity,
+ { shouldBypassPermissionChecks: true },
+ );
+
+ const campaign = await campaignRepository.findOne({
+ where: { id: campaignId },
+ });
+
+ if (
+ !isDefined(campaign) ||
+ campaign.status === MessageCampaignStatus.CANCELED
+ ) {
+ return null;
+ }
+
+ const claimToken = await this.claimDeliveryForSending({
+ workspaceId,
+ messageId,
+ });
+
+ if (!isDefined(claimToken)) {
+ return null;
+ }
+
+ const campaignAfterClaim = await campaignRepository.findOne({
+ where: { id: campaignId },
+ select: { id: true, status: true },
+ });
+
+ if (campaignAfterClaim?.status === MessageCampaignStatus.CANCELED) {
+ await this.settleClaimedDelivery({
+ workspaceId,
+ messageId,
+ claimToken,
+ update: {
+ state: CAMPAIGN_DELIVERY_STATE.SKIPPED,
+ skipReason: CAMPAIGN_SKIP_REASON.CAMPAIGN_CANCELED,
+ },
+ });
+
+ return null;
+ }
+
+ const personRepository = this.workspaceOrmManager.getRepository(
+ PersonWorkspaceEntity,
+ { shouldBypassPermissionChecks: true },
+ );
+
+ return {
+ campaign,
+ claimToken,
+ person: await personRepository.findOne({ where: { id: personId } }),
+ };
+ }
+
+ private async deliverMessage({
+ data,
+ messageRepository,
+ sendContext: { campaign, person, claimToken },
+ }: {
+ data: SendCampaignEmailJobData;
+ messageRepository: MessageRepository;
+ sendContext: SendContext;
+ }): Promise<void> {
+ const {
+ workspaceId,
+ campaignId,
+ messageId,
+ recipientEmail,
+ emailingDomainId,
+ } = 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) {
+ await this.settleClaimedDelivery({
+ workspaceId,
+ messageId,
+ claimToken,
+ update: {
+ state: CAMPAIGN_DELIVERY_STATE.SKIPPED,
+ skipReason: CAMPAIGN_SKIP_REASON.OUT_OF_CREDITS,
+ },
+ });
+
+ return;
+ }
+
+ const result = await this.sendOrRecordFailure({
+ messageId,
+ claimToken,
+ campaignId,
+ workspaceId,
+ emailingDomainId,
+ email: {
+ from: campaign.fromAddress?.primaryEmail ?? '',
+ to: [recipientEmail],
+ subject,
+ text: plainText,
+ html,
+ unsubscribeTopicId: campaign.unsubscribeTopicId ?? undefined,
+ },
+ });
+
+ if (!isDefined(result)) {
+ return;
+ }
+
+ await messageRepository.update(messageId, {
+ headerMessageId: result.messageId,
+ subject,
+ text: plainText,
+ });
+
+ const affected = await this.settleClaimedDelivery({
+ workspaceId,
+ messageId,
+ claimToken,
+ update: {
+ state: CAMPAIGN_DELIVERY_STATE.SENT,
+ providerMessageId: result.messageId,
+ sentAt: new Date(),
+ },
+ });
+
+ if (affected !== 1) {
+ this.logger.warn(
+ `Campaign ${campaignId} delivered message ${messageId} but another worker owns the claim, so this send is recorded by neither and is not billed`,
+ );
+
+ return;
+ }
+
+ await this.emailBillingService.billSentEmails({
+ workspaceId,
+ sentEmailCount: 1,
+ });
+
+ await this.linkMessageToProviderThread({
+ messageId,
+ providerMessageId: result.messageId,
+ });
+ }
+
+ private async linkMessageToProviderThread({
+ messageId,
+ providerMessageId,
+ }: {
+ messageId: string;
+ providerMessageId: string;
+ }): Promise<void> {
+ const associationRepository = this.workspaceOrmManager.getRepository(
+ MessageChannelMessageAssociationWorkspaceEntity,
+ { shouldBypassPermissionChecks: true },
+ );
+
+ await associationRepository.update(
+ { messageId },
+ {
+ messageExternalId: providerMessageId,
+ messageThreadExternalId: providerMessageId,
+ },
+ );
+ }
+
+ private async sendOrRecordFailure({
+ messageId,
+ claimToken,
+ campaignId,
+ workspaceId,
+ emailingDomainId,
+ email,
+ }: {
+ messageId: string;
+ claimToken: string;
+ campaignId: string;
+ workspaceId: string;
+ emailingDomainId: string;
+ email: EmailingDomainEmailContent;
+ }): Promise<EmailingDomainSendEmailResult | null> {
+ try {
+ return await this.emailingDomainSenderService.sendEmail(
+ workspaceId,
+ emailingDomainId,
+ email,
+ );
+ } catch (error) {
+ await this.recordSendFailure({
+ workspaceId,
+ messageId,
+ claimToken,
+ campaignId,
+ error,
+ });
+
+ return null;
+ }
+ }
+
+ private async recordSendFailure({
+ workspaceId,
+ messageId,
+ claimToken,
+ campaignId,
+ error,
+ }: {
+ workspaceId: string;
+ messageId: string;
+ claimToken: string;
+ campaignId: string;
+ error: unknown;
+ }): Promise<void> {
+ const { state, skipReason, failureReason, shouldRetry } =
+ resolveCampaignSendFailure(error);
+
+ await this.settleClaimedDelivery({
+ workspaceId,
+ messageId,
+ claimToken,
+ update: shouldRetry
+ ? { state: CAMPAIGN_DELIVERY_STATE.QUEUED, skipReason, failureReason }
+ : { state, skipReason, failureReason },
+ });
+
+ if (state === CAMPAIGN_DELIVERY_STATE.FAILED) {
+ this.logger.warn(
+ `Campaign ${campaignId} send failed for message ${messageId}: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
+
+ if (shouldRetry) {
+ throw error;
+ }
+ }
+
+ private async claimDeliveryForSending({
+ workspaceId,
+ messageId,
+ }: {
+ workspaceId: string;
+ messageId: string;
+ }): Promise<string | null> {
+ const claimToken = v4();
+
+ const { affected } = await this.campaignDeliveryRepository.update(
+ workspaceId,
+ {
+ id: messageId,
+ state: In([
+ CAMPAIGN_DELIVERY_STATE.QUEUED,
+ CAMPAIGN_DELIVERY_STATE.FAILED,
+ ]),
+ },
+ {
+ state: CAMPAIGN_DELIVERY_STATE.SENDING,
+ claimToken,
+ claimExpiresAt: new Date(Date.now() + CAMPAIGN_DELIVERY_CLAIM_TTL_MS),
+ },
+ );
+
+ return affected === 1 ? claimToken : null;
+ }
+
+ private async settleClaimedDelivery({
+ workspaceId,
+ messageId,
+ claimToken,
+ update,
+ }: {
+ workspaceId: string;
+ messageId: string;
+ claimToken: string;
+ update: Partial<
+ Pick<
+ CampaignDeliveryEntity,
+ | 'state'
+ | 'skipReason'
+ | 'failureReason'
+ | 'providerMessageId'
+ | 'sentAt'
+ >
+ >;
+ }): Promise<number> {
+ const { affected } = await this.campaignDeliveryRepository.update(
+ workspaceId,
+ { id: messageId, claimToken },
+ { ...update, claimToken: null, claimExpiresAt: null },
+ );
+
+ return affected ?? 0;
+ }
+}
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
new file mode 100644
index 00000000000..fcfb677defb
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-lifecycle.service.ts
@@ -0,0 +1,238 @@
+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_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';
+
+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';
+import { MessageCampaignStatisticsService } from 'src/modules/emailing/services/message-campaign-statistics.service';
+import { MessageCampaignWorkspaceEntity } from 'src/modules/emailing/standard-objects/message-campaign.workspace-entity';
+import { computeCampaignTerminalStatus } from 'src/modules/emailing/utils/compute-campaign-terminal-status.util';
+import { MessageCampaignStatus } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+type CampaignStatusTransition = {
+ workspaceId: string;
+ campaignId: string;
+ from: MessageCampaignStatus;
+ to: MessageCampaignStatus;
+ roleId?: string;
+};
+
+@Injectable()
+export class MessageCampaignLifecycleService {
+ constructor(
+ @InjectWorkspaceScopedRepository(CampaignDeliveryEntity)
+ private readonly campaignDeliveryRepository: WorkspaceScopedRepository<CampaignDeliveryEntity>,
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly userRoleService: UserRoleService,
+ private readonly messageCampaignStatisticsService: MessageCampaignStatisticsService,
+ @InjectMessageQueue(MessageQueue.emailQueue)
+ private readonly messageQueueService: MessageQueueService,
+ @InjectCacheStorage(CacheStorageNamespace.ModuleEmailing)
+ private readonly cacheStorageService: CacheStorageService,
+ ) {}
+
+ async transitionCampaignStatus({
+ workspaceId,
+ campaignId,
+ from,
+ to,
+ roleId,
+ }: CampaignStatusTransition): Promise<boolean> {
+ return this.workspaceOrmManager.executeInWorkspaceContext(
+ async () => {
+ const campaignRepository = this.workspaceOrmManager.getRepository(
+ MessageCampaignWorkspaceEntity,
+ isDefined(roleId)
+ ? { unionOf: [roleId] }
+ : { shouldBypassPermissionChecks: true },
+ );
+
+ const { affected } = await campaignRepository.update(
+ { id: campaignId, status: from },
+ { status: to },
+ );
+
+ return affected === 1;
+ },
+ isDefined(roleId) ? undefined : buildSystemAuthContext(workspaceId),
+ );
+ }
+
+ async cancelCampaignOrThrow({
+ workspaceId,
+ userWorkspaceId,
+ campaignId,
+ }: {
+ workspaceId: string;
+ userWorkspaceId: string;
+ campaignId: string;
+ }): Promise<{ campaignId: string; canceledMessageCount: number }> {
+ const roleId = await this.userRoleService.getRoleIdForUserWorkspace({
+ workspaceId,
+ userWorkspaceId,
+ });
+
+ const canceled = await this.transitionCampaignStatus({
+ workspaceId,
+ campaignId,
+ roleId,
+ from: MessageCampaignStatus.SENDING,
+ to: MessageCampaignStatus.CANCELED,
+ });
+
+ if (!canceled) {
+ throw new EmailingDomainException(
+ `Campaign ${campaignId} is not sending`,
+ EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_CANCELABLE,
+ );
+ }
+
+ const canceledMessageCount = await this.settleDeliveries({
+ workspaceId,
+ criteria: {
+ campaignId,
+ state: CAMPAIGN_DELIVERY_STATE.QUEUED,
+ },
+ update: {
+ state: CAMPAIGN_DELIVERY_STATE.SKIPPED,
+ skipReason: CAMPAIGN_SKIP_REASON.CAMPAIGN_CANCELED,
+ },
+ });
+
+ await this.scheduleStatsRefresh({ workspaceId, campaignId });
+
+ return { campaignId, canceledMessageCount };
+ }
+
+ async failDeliveriesWithExpiredClaims({
+ workspaceId,
+ campaignId,
+ }: {
+ workspaceId: string;
+ campaignId: string;
+ }): Promise<number> {
+ return this.settleDeliveries({
+ workspaceId,
+ criteria: {
+ campaignId,
+ state: CAMPAIGN_DELIVERY_STATE.SENDING,
+ claimExpiresAt: LessThan(new Date()),
+ },
+ update: {
+ state: CAMPAIGN_DELIVERY_STATE.FAILED,
+ failureReason: CAMPAIGN_FAILURE_REASON.CLAIM_EXPIRED,
+ claimToken: null,
+ claimExpiresAt: null,
+ },
+ });
+ }
+
+ private async settleDeliveries({
+ workspaceId,
+ criteria,
+ update,
+ }: {
+ workspaceId: string;
+ criteria: FindOptionsWhere<CampaignDeliveryEntity>;
+ update: QueryDeepPartialEntity<CampaignDeliveryEntity>;
+ }): Promise<number> {
+ const { affected } = await this.campaignDeliveryRepository.update(
+ workspaceId,
+ criteria,
+ update,
+ );
+
+ return affected ?? 0;
+ }
+
+ async finalizeCampaignIfComplete({
+ workspaceId,
+ campaignId,
+ }: {
+ workspaceId: string;
+ campaignId: string;
+ }): Promise<void> {
+ const counts =
+ await this.messageCampaignStatisticsService.countDeliveriesByState({
+ workspaceId,
+ campaignId,
+ });
+
+ const terminalStatus = computeCampaignTerminalStatus(counts);
+
+ if (!isDefined(terminalStatus)) {
+ return;
+ }
+
+ const correctableStatuses =
+ terminalStatus === MessageCampaignStatus.SENT
+ ? [
+ MessageCampaignStatus.SENDING,
+ MessageCampaignStatus.SENT_WITH_ERRORS,
+ ]
+ : [MessageCampaignStatus.SENDING];
+
+ await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ const campaignRepository = this.workspaceOrmManager.getRepository(
+ MessageCampaignWorkspaceEntity,
+ { shouldBypassPermissionChecks: true },
+ );
+
+ await campaignRepository.update(
+ { id: campaignId, status: In(correctableStatuses) },
+ { status: terminalStatus, sentAt: new Date() },
+ );
+ }, 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 },
+ );
+ }
+}
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
new file mode 100644
index 00000000000..3093dba2171
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-materialization.service.ts
@@ -0,0 +1,480 @@
+import { CAMPAIGN_SEND_RETRY_BACKOFF } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant';
+import { Injectable } from '@nestjs/common';
+
+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 { 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 chunk from 'lodash.chunk';
+import { In } from 'typeorm';
+import { v4 } from 'uuid';
+
+import {
+ MATERIALIZE_CAMPAIGN_CHUNK_JOB,
+ SEND_CAMPAIGN_EMAIL_JOB,
+} from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
+import { type MaterializeCampaignChunkJobData } from 'src/engine/core-modules/emailing-domain/types/materialize-campaign-chunk-job-data.type';
+import { type MaterializeCampaignJobData } from 'src/engine/core-modules/emailing-domain/types/materialize-campaign-job-data.type';
+import { type SendCampaignEmailJobData } from 'src/engine/core-modules/emailing-domain/types/send-campaign-email-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';
+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 { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';
+import { MessageCampaignWorkspaceEntity } from 'src/modules/emailing/standard-objects/message-campaign.workspace-entity';
+import { type CampaignRecipient } from 'src/engine/core-modules/emailing-domain/types/campaign-recipient.type';
+import { type CampaignMessageRecipient } from 'src/modules/emailing/types/campaign-message-recipient.type';
+import { buildCampaignMessageId } from 'src/modules/emailing/utils/build-campaign-message-id.util';
+import { compileCampaignEmailContent } from 'src/modules/emailing/utils/compile-campaign-email-content.util';
+import { MessageDirection } from 'src/modules/messaging/common/enums/message-direction.enum';
+import { MessageChannelMessageAssociationWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel-message-association.workspace-entity';
+import { MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';
+import { MessageThreadWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-thread.workspace-entity';
+import { MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
+import {
+ MessageCampaignStatus,
+ MessageParticipantRole,
+} from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+const MATERIALIZATION_CHUNK_SIZE = 500;
+
+// Campaign rows are machine-generated and nothing subscribes to them: no
+// webhook, workflow trigger or timeline activity. Emitting would cost a
+// snapshot SELECT of every row written plus a timeline row per recipient.
+const SKIP_EVENT_EMISSION = { shouldSkipEventEmission: true };
+
+type CampaignMessageRow = {
+ recipient: CampaignMessageRecipient;
+ messageId: string;
+ threadId: string;
+ temporaryExternalId: string;
+};
+
+@Injectable()
+export class MessageCampaignMaterializationService {
+ constructor(
+ @InjectWorkspaceScopedRepository(CampaignDeliveryEntity)
+ private readonly campaignDeliveryRepository: WorkspaceScopedRepository<CampaignDeliveryEntity>,
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly messageCampaignLifecycleService: MessageCampaignLifecycleService,
+ @InjectMessageQueue(MessageQueue.emailQueue)
+ private readonly messageQueueService: MessageQueueService,
+ ) {}
+
+ async processMaterializeJob({
+ workspaceId,
+ campaignId,
+ messageChannelId,
+ emailingDomainId,
+ recipients,
+ }: MaterializeCampaignJobData): Promise<void> {
+ await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ const campaignRepository = this.workspaceOrmManager.getRepository(
+ MessageCampaignWorkspaceEntity,
+ { shouldBypassPermissionChecks: true },
+ );
+
+ const campaign = await campaignRepository.findOne({
+ where: { id: campaignId },
+ });
+
+ if (
+ !isDefined(campaign) ||
+ campaign.status !== MessageCampaignStatus.SENDING
+ ) {
+ return;
+ }
+
+ const uniqueRecipients = this.deduplicateRecipientsByMessageId({
+ campaignId,
+ recipients,
+ });
+
+ const existingDeliveries = await this.campaignDeliveryRepository.find(
+ workspaceId,
+ { where: { campaignId }, select: { id: true, state: true } },
+ );
+ const existingMessageIds = new Set(
+ existingDeliveries.map((delivery) => delivery.id),
+ );
+ const queuedMessageIds = new Set(
+ existingDeliveries
+ .filter(
+ (delivery) => delivery.state === CAMPAIGN_DELIVERY_STATE.QUEUED,
+ )
+ .map((delivery) => delivery.id),
+ );
+
+ const recipientsStrandedByAnEarlierAttempt = uniqueRecipients.filter(
+ (recipient) => queuedMessageIds.has(recipient.messageId),
+ );
+
+ const recipientsToCreate = uniqueRecipients.filter(
+ (recipient) => !existingMessageIds.has(recipient.messageId),
+ );
+
+ const enqueuedChunkCount = await this.enqueueMaterializationChunks({
+ workspaceId,
+ campaignId,
+ messageChannelId,
+ emailingDomainId,
+ recipientsToCreate,
+ recipientsStrandedByAnEarlierAttempt,
+ });
+
+ // Only finalize here when there is no chunk left to run. Doing it while
+ // chunks are still pending would see zero deliveries and settle the
+ // campaign as SENT_WITH_ERRORS before a single message exists.
+ if (enqueuedChunkCount === 0) {
+ await this.messageCampaignLifecycleService.finalizeCampaignIfComplete({
+ workspaceId,
+ campaignId,
+ });
+ }
+ }, buildSystemAuthContext(workspaceId));
+ }
+
+ private async enqueueMaterializationChunks({
+ workspaceId,
+ campaignId,
+ messageChannelId,
+ emailingDomainId,
+ recipientsToCreate,
+ recipientsStrandedByAnEarlierAttempt,
+ }: {
+ workspaceId: string;
+ campaignId: string;
+ messageChannelId: string;
+ emailingDomainId: string;
+ recipientsToCreate: CampaignMessageRecipient[];
+ recipientsStrandedByAnEarlierAttempt: CampaignMessageRecipient[];
+ }): Promise<number> {
+ const receivedAtIso = new Date().toISOString();
+
+ const chunks: MaterializeCampaignChunkJobData[] = [
+ ...chunk(recipientsToCreate, MATERIALIZATION_CHUNK_SIZE).map(
+ (recipients) => ({ recipients, shouldCreateMessages: true }),
+ ),
+ ...chunk(
+ recipientsStrandedByAnEarlierAttempt,
+ MATERIALIZATION_CHUNK_SIZE,
+ ).map((recipients) => ({ recipients, shouldCreateMessages: false })),
+ ].map(({ recipients, shouldCreateMessages }) => ({
+ workspaceId,
+ campaignId,
+ messageChannelId,
+ emailingDomainId,
+ receivedAtIso,
+ shouldCreateMessages,
+ recipients,
+ }));
+
+ if (chunks.length === 0) {
+ return 0;
+ }
+
+ await this.messageQueueService.bulkAdd<MaterializeCampaignChunkJobData>(
+ MATERIALIZE_CAMPAIGN_CHUNK_JOB,
+ chunks,
+ { retryLimit: 3, backoff: CAMPAIGN_SEND_RETRY_BACKOFF },
+ );
+
+ return chunks.length;
+ }
+
+ async processMaterializeChunkJob({
+ workspaceId,
+ campaignId,
+ messageChannelId,
+ emailingDomainId,
+ receivedAtIso,
+ shouldCreateMessages,
+ recipients,
+ }: MaterializeCampaignChunkJobData): Promise<void> {
+ await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ const campaignRepository = this.workspaceOrmManager.getRepository(
+ MessageCampaignWorkspaceEntity,
+ { shouldBypassPermissionChecks: true },
+ );
+
+ const campaign = await campaignRepository.findOne({
+ where: { id: campaignId },
+ });
+
+ // A cancel between chunks stops the ones that have not run yet.
+ if (
+ !isDefined(campaign) ||
+ campaign.status !== MessageCampaignStatus.SENDING
+ ) {
+ return;
+ }
+
+ if (shouldCreateMessages) {
+ const { plainText: unrenderedText } = await compileCampaignEmailContent(
+ campaign.bodyTemplate ?? '',
+ null,
+ );
+
+ await this.insertMessagesBeforeTheirDeliveries({
+ workspaceId,
+ campaignId,
+ messageChannelId,
+ fromAddress: campaign.fromAddress?.primaryEmail ?? '',
+ subjectTemplate: campaign.subject ?? '',
+ text: unrenderedText,
+ now: new Date(receivedAtIso),
+ recipients: await this.rejectAlreadyMaterializedRecipients({
+ campaignId,
+ recipients,
+ }),
+ });
+ }
+
+ await this.enqueueSendJobs({
+ workspaceId,
+ campaignId,
+ emailingDomainId,
+ recipients,
+ });
+
+ await this.messageCampaignLifecycleService.finalizeCampaignIfComplete({
+ workspaceId,
+ campaignId,
+ });
+ }, buildSystemAuthContext(workspaceId));
+ }
+
+ // A retried chunk job must not insert the rows its previous attempt already
+ // wrote: message ids are deterministic and would collide, and the thread,
+ // association and participant rows would be duplicated under fresh ids.
+ private async rejectAlreadyMaterializedRecipients({
+ campaignId,
+ recipients,
+ }: {
+ campaignId: string;
+ recipients: CampaignMessageRecipient[];
+ }): Promise<CampaignMessageRecipient[]> {
+ if (recipients.length === 0) {
+ return [];
+ }
+
+ const messageRepository = this.workspaceOrmManager.getRepository(
+ MessageWorkspaceEntity,
+ { shouldBypassPermissionChecks: true },
+ );
+
+ const alreadyMaterialized = await messageRepository.find({
+ where: {
+ messageCampaignId: campaignId,
+ id: In(recipients.map((recipient) => recipient.messageId)),
+ },
+ select: { id: true },
+ });
+
+ if (alreadyMaterialized.length === 0) {
+ return recipients;
+ }
+
+ const alreadyMaterializedIds = new Set(
+ alreadyMaterialized.map((message) => message.id),
+ );
+
+ return recipients.filter(
+ (recipient) => !alreadyMaterializedIds.has(recipient.messageId),
+ );
+ }
+
+ private deduplicateRecipientsByMessageId({
+ campaignId,
+ recipients,
+ }: {
+ campaignId: string;
+ recipients: CampaignRecipient[];
+ }): CampaignMessageRecipient[] {
+ const recipientsByMessageId = new Map<string, CampaignMessageRecipient>();
+
+ for (const recipient of recipients) {
+ const messageId = buildCampaignMessageId({
+ campaignId,
+ personId: recipient.personId,
+ });
+
+ if (!recipientsByMessageId.has(messageId)) {
+ recipientsByMessageId.set(messageId, { ...recipient, messageId });
+ }
+ }
+
+ return [...recipientsByMessageId.values()];
+ }
+
+ private async enqueueSendJobs({
+ workspaceId,
+ campaignId,
+ emailingDomainId,
+ recipients,
+ }: {
+ workspaceId: string;
+ campaignId: string;
+ emailingDomainId: string;
+ recipients: CampaignMessageRecipient[];
+ }): Promise<void> {
+ if (recipients.length === 0) {
+ return;
+ }
+
+ await this.messageQueueService.bulkAdd<SendCampaignEmailJobData>(
+ SEND_CAMPAIGN_EMAIL_JOB,
+ recipients.map((recipient) => ({
+ workspaceId,
+ campaignId,
+ messageId: recipient.messageId,
+ personId: recipient.personId,
+ recipientEmail: recipient.email,
+ emailingDomainId,
+ })),
+ { retryLimit: 3, backoff: CAMPAIGN_SEND_RETRY_BACKOFF },
+ );
+ }
+
+ private async insertMessagesBeforeTheirDeliveries({
+ workspaceId,
+ campaignId,
+ messageChannelId,
+ fromAddress,
+ subjectTemplate,
+ text,
+ now,
+ recipients,
+ }: {
+ workspaceId: string;
+ campaignId: string;
+ messageChannelId: string;
+ fromAddress: string;
+ subjectTemplate: string;
+ text: string;
+ now: Date;
+ recipients: CampaignMessageRecipient[];
+ }): Promise<void> {
+ await this.insertChunk({
+ campaignId,
+ messageChannelId,
+ fromAddress,
+ subjectTemplate,
+ text,
+ now,
+ rows: recipients.map((recipient) => ({
+ recipient,
+ messageId: recipient.messageId,
+ threadId: v4(),
+ temporaryExternalId: v4(),
+ })),
+ });
+
+ await this.campaignDeliveryRepository.upsert(
+ workspaceId,
+ recipients.map((recipient) => ({
+ id: recipient.messageId,
+ campaignId,
+ personId: recipient.personId,
+ recipientEmail: recipient.email,
+ state: CAMPAIGN_DELIVERY_STATE.QUEUED,
+ })),
+ { conflictPaths: ['id'], skipUpdateIfNoValuesChanged: true },
+ );
+ }
+
+ private async insertChunk({
+ campaignId,
+ messageChannelId,
+ fromAddress,
+ subjectTemplate,
+ text,
+ now,
+ rows,
+ }: {
+ campaignId: string;
+ messageChannelId: string;
+ fromAddress: string;
+ subjectTemplate: string;
+ text: string;
+ now: Date;
+ rows: CampaignMessageRow[];
+ }): Promise<void> {
+ await this.workspaceOrmManager.runInWorkspaceTransaction(
+ async (transactionScope) => {
+ await transactionScope
+ .getRepository<MessageThreadWorkspaceEntity>(
+ 'messageThread',
+ { 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) => ({
+ 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,
+ },
+ ]),
+ );
+ },
+ );
+ }
+}
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-recovery.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-recovery.service.ts
new file mode 100644
index 00000000000..3139dc7f722
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-recovery.service.ts
@@ -0,0 +1,153 @@
+import { Injectable, Logger } from '@nestjs/common';
+
+import { In, LessThan, MoreThan } from 'typeorm';
+import { MessageCampaignStatus } from 'twenty-shared/types';
+
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+import { MessageCampaignStatisticsService } from 'src/modules/emailing/services/message-campaign-statistics.service';
+import { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';
+import { MessageCampaignWorkspaceEntity } from 'src/modules/emailing/standard-objects/message-campaign.workspace-entity';
+import { MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
+
+const SENDING_STALE_THRESHOLD_MS = 60 * 60 * 1000;
+
+@Injectable()
+export class MessageCampaignRecoveryService {
+ private readonly logger = new Logger(MessageCampaignRecoveryService.name);
+
+ constructor(
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly messageCampaignLifecycleService: MessageCampaignLifecycleService,
+ private readonly messageCampaignStatisticsService: MessageCampaignStatisticsService,
+ ) {}
+
+ async recoverOngoingStaleCampaigns({
+ workspaceId,
+ }: {
+ workspaceId: string;
+ }): Promise<void> {
+ const staleSince = new Date(
+ Date.now() - SENDING_STALE_THRESHOLD_MS,
+ ).toISOString();
+
+ const staleCampaigns =
+ await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ const campaignRepository = this.workspaceOrmManager.getRepository(
+ MessageCampaignWorkspaceEntity,
+ { shouldBypassPermissionChecks: true },
+ );
+
+ return campaignRepository.find({
+ where: {
+ status: In([
+ MessageCampaignStatus.SENDING,
+ MessageCampaignStatus.CANCELED,
+ ]),
+ updatedAt: LessThan(staleSince),
+ },
+ select: { id: true },
+ });
+ }, buildSystemAuthContext(workspaceId));
+
+ for (const campaign of staleCampaigns) {
+ await this.recoverStaleCampaign({
+ workspaceId,
+ campaignId: campaign.id,
+ staleSince,
+ }).catch((error) => {
+ this.logger.error(
+ `Failed to recover campaign ${campaign.id} of workspace ${workspaceId}: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ });
+ }
+ }
+
+ private async hasRecentMessageProgress({
+ workspaceId,
+ campaignId,
+ staleSince,
+ }: {
+ workspaceId: string;
+ campaignId: string;
+ staleSince: string;
+ }): Promise<boolean> {
+ return this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ const messageRepository = this.workspaceOrmManager.getRepository(
+ MessageWorkspaceEntity,
+ { shouldBypassPermissionChecks: true },
+ );
+
+ return messageRepository.exists({
+ where: {
+ messageCampaignId: campaignId,
+ updatedAt: MoreThan(staleSince),
+ },
+ });
+ }, buildSystemAuthContext(workspaceId));
+ }
+
+ private async recoverStaleCampaign({
+ workspaceId,
+ campaignId,
+ staleSince,
+ }: {
+ workspaceId: string;
+ campaignId: string;
+ staleSince: string;
+ }): Promise<void> {
+ const hasProgress = await this.hasRecentMessageProgress({
+ workspaceId,
+ campaignId,
+ staleSince,
+ });
+
+ if (hasProgress) {
+ return;
+ }
+
+ const counts =
+ await this.messageCampaignStatisticsService.countDeliveriesByState({
+ workspaceId,
+ campaignId,
+ });
+
+ if (counts.totalCount > 0) {
+ await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ const failedCount =
+ await this.messageCampaignLifecycleService.failDeliveriesWithExpiredClaims(
+ { workspaceId, campaignId },
+ );
+
+ if (failedCount > 0) {
+ this.logger.warn(
+ `Campaign ${campaignId} of workspace ${workspaceId} had ${failedCount} message(s) stalled and they were failed`,
+ );
+ }
+
+ await this.messageCampaignLifecycleService.finalizeCampaignIfComplete({
+ workspaceId,
+ campaignId,
+ });
+ }, buildSystemAuthContext(workspaceId));
+
+ return;
+ }
+
+ const released =
+ await this.messageCampaignLifecycleService.transitionCampaignStatus({
+ workspaceId,
+ campaignId,
+ from: MessageCampaignStatus.SENDING,
+ to: MessageCampaignStatus.DRAFT,
+ });
+
+ if (released) {
+ this.logger.warn(
+ `Campaign ${campaignId} of workspace ${workspaceId} materialized no message and was released back to draft`,
+ );
+ }
+ }
+}
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 963bb68c404..941025386a3 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,60 +1,58 @@
import { Injectable } from '@nestjs/common';
-import { CAMPAIGN_MESSAGE_DELIVERY_STATUS } from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
+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 { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { MessageCampaignWorkspaceEntity } from 'src/modules/emailing/standard-objects/message-campaign.workspace-entity';
-import { MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
-
-type DeliveryStatusCountRow = {
- deliveryStatus: string | null;
- count: string;
-};
@Injectable()
export class MessageCampaignStatisticsService {
- constructor(private readonly workspaceOrmManager: WorkspaceOrmManager) {}
+ constructor(
+ @InjectWorkspaceScopedRepository(CampaignDeliveryEntity)
+ private readonly campaignDeliveryRepository: WorkspaceScopedRepository<CampaignDeliveryEntity>,
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ ) {}
- async refreshCampaignCounts({
+ async countDeliveriesByState({
workspaceId,
campaignId,
}: {
workspaceId: string;
campaignId: string;
- }): Promise<void> {
- await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const messageRepository = this.workspaceOrmManager.getRepository(
- MessageWorkspaceEntity,
- { shouldBypassPermissionChecks: true },
- );
-
- const deliveryStatusCountRows = await messageRepository
- .createQueryBuilder('message')
- .select('message.deliveryStatus', 'deliveryStatus')
- .addSelect('COUNT(*)', 'count')
- .where('message.messageCampaignId = :campaignId', { campaignId })
- .groupBy('message.deliveryStatus')
- .getRawMany<DeliveryStatusCountRow>();
+ }): Promise<CampaignCounts> {
+ const groups = await this.campaignDeliveryRepository
+ .createQueryBuilder('delivery')
+ .select('delivery.state', 'state')
+ .addSelect('COUNT(*)', 'total')
+ .addSelect('COUNT(delivery."deliveredAt")', 'deliveredCount')
+ .addSelect('COUNT(delivery."bouncedAt")', 'bouncedCount')
+ .addSelect('COUNT(delivery."complainedAt")', 'complainedCount')
+ .where('delivery."workspaceId" = :workspaceId', { workspaceId })
+ .andWhere('delivery."campaignId" = :campaignId', { campaignId })
+ .groupBy('delivery.state')
+ .getRawMany<CampaignCountGroup>();
- const countByDeliveryStatus = new Map(
- deliveryStatusCountRows.map((row) => [
- row.deliveryStatus,
- Number(row.count),
- ]),
- );
+ return computeCampaignCounts({ groups });
+ }
- const sentCount =
- countByDeliveryStatus.get(CAMPAIGN_MESSAGE_DELIVERY_STATUS.SENT) ?? 0;
- const failedCount =
- countByDeliveryStatus.get(CAMPAIGN_MESSAGE_DELIVERY_STATUS.FAILED) ?? 0;
- const bouncedCount =
- countByDeliveryStatus.get(CAMPAIGN_MESSAGE_DELIVERY_STATUS.BOUNCED) ??
- 0;
- const complainedCount =
- countByDeliveryStatus.get(
- CAMPAIGN_MESSAGE_DELIVERY_STATUS.COMPLAINED,
- ) ?? 0;
+ async refreshCampaignCounts({
+ workspaceId,
+ campaignId,
+ }: {
+ workspaceId: string;
+ campaignId: string;
+ }): Promise<void> {
+ const counts = await this.countDeliveriesByState({
+ workspaceId,
+ campaignId,
+ });
+ await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
const campaignRepository = this.workspaceOrmManager.getRepository(
MessageCampaignWorkspaceEntity,
{ shouldBypassPermissionChecks: true },
@@ -62,7 +60,14 @@ export class MessageCampaignStatisticsService {
await campaignRepository.update(
{ id: campaignId },
- { sentCount, failedCount, bouncedCount, complainedCount },
+ {
+ sentCount: counts.sentCount,
+ deliveredCount: counts.deliveredCount,
+ failedCount: counts.failedCount,
+ skippedCount: counts.skippedCount,
+ bouncedCount: counts.bouncedCount,
+ complainedCount: counts.complainedCount,
+ },
);
}, 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 469b6122c60..2ea7bf16ccc 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,155 +1,76 @@
-import { Injectable, Logger, type Type } from '@nestjs/common';
+import { CAMPAIGN_SEND_RETRY_BACKOFF } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant';
+import { Injectable } from '@nestjs/common';
import { isNonEmptyString } from '@sniptt/guards';
import { z } from 'zod';
-import { In, type ObjectLiteral } from 'typeorm';
-import { v4, v5 } from 'uuid';
-import {
- CAMPAIGN_MESSAGE_DELIVERY_STATUS,
- CAMPAIGN_MESSAGE_ID_NAMESPACE,
- CAMPAIGN_STATS_REFRESH_DELAY_MS,
- MATERIALIZE_CAMPAIGN_JOB,
- MAX_CAMPAIGN_RECIPIENTS,
- REFRESH_CAMPAIGN_STATS_JOB,
- SEND_CAMPAIGN_EMAIL_JOB,
-} from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
-import {
- EmailingDomainDriverException,
- EmailingDomainDriverExceptionCode,
-} from 'src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception';
+import { MATERIALIZE_CAMPAIGN_JOB } from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
import { EmailingDomainStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-status.type';
+import { UnsubscribeHostnameStatus } from 'src/engine/core-modules/emailing-domain/drivers/types/unsubscribe-hostname-status.type';
import {
EmailingDomainException,
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 CampaignRecipient } from 'src/engine/core-modules/emailing-domain/types/campaign-recipient.type';
import { type CampaignSkippedBreakdown } from 'src/engine/core-modules/emailing-domain/types/campaign-skipped-breakdown.type';
import { type MaterializeCampaignJobData } from 'src/engine/core-modules/emailing-domain/types/materialize-campaign-job-data.type';
-import { type RawCampaignRecipient } from 'src/engine/core-modules/emailing-domain/types/raw-campaign-recipient.type';
-import { type RefreshCampaignStatsJobData } from 'src/engine/core-modules/emailing-domain/types/refresh-campaign-stats-job-data.type';
-import { type SendCampaignEmailJobData } from 'src/engine/core-modules/emailing-domain/types/send-campaign-email-job-data.type';
-import { normalizeCampaignRecipients } from 'src/engine/core-modules/emailing-domain/utils/normalize-campaign-recipients.util';
-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 { MessageChannelMetadataService } from 'src/engine/metadata-modules/message-channel/message-channel-metadata.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';
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 { MessageCampaignStatisticsService } from 'src/modules/emailing/services/message-campaign-statistics.service';
-import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';
+import { MessageCampaignAudienceService } from 'src/modules/emailing/services/message-campaign-audience.service';
+import { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';
import { MessageCampaignWorkspaceEntity } from 'src/modules/emailing/standard-objects/message-campaign.workspace-entity';
-import { MessageListMemberWorkspaceEntity } from 'src/modules/emailing/standard-objects/message-list-member.workspace-entity';
import { collectCampaignVariableNamesFromTemplates } from 'src/modules/emailing/utils/collect-campaign-variable-names-from-templates.util';
-import { compileCampaignEmailContent } from 'src/modules/emailing/utils/compile-campaign-email-content.util';
-import { renderCampaignTemplate } from 'src/modules/emailing/utils/render-campaign-template.util';
+import { renderCampaignEmail } from 'src/modules/emailing/utils/render-campaign-email.util';
import { sendableDraftCampaignSchema } from 'src/modules/emailing/zod-schemas/sendable-draft-campaign.zod-schema';
-import { MessageDirection } from 'src/modules/messaging/common/enums/message-direction.enum';
-import { MessageChannelMessageAssociationWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel-message-association.workspace-entity';
-import { MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';
-import { MessageThreadWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-thread.workspace-entity';
-import { MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
-import { PersonWorkspaceEntity } from 'src/modules/person/standard-objects/person.workspace-entity';
-import {
- MessageParticipantRole,
- MessageCampaignStatus,
-} from 'twenty-shared/types';
+import { MessageCampaignStatus } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { getDomainFromEmail } from 'src/utils/get-domain-from-email';
-type SendCampaignArgs = {
- workspaceId: string;
- userWorkspaceId: string;
- campaignId: string;
-};
-
-type SendCampaignTestArgs = {
- workspaceId: string;
- toAddress: string;
- subject: string;
- html: string;
- fromAddress: string;
- unsubscribeTopicId?: string;
-};
-
type SendCampaignResult = {
campaignId: string;
queuedCount: number;
skipped: CampaignSkippedBreakdown;
};
-type CampaignAudiencePreview = {
- totalMembers: number;
- withoutEmail: number;
- duplicateEmails: number;
- globallyUnsubscribed: number;
- topicUnsubscribed: number;
- sendable: number;
-};
-
-type CampaignMessageRecipient = CampaignRecipient & { messageId: string };
-
type SendableDraftCampaign = z.infer<typeof sendableDraftCampaignSchema>;
-const toRawRecipient = (person: {
- id: string;
- emails?: { primaryEmail?: string | null } | null;
-}): RawCampaignRecipient => ({
- personId: person.id,
- email: person.emails?.primaryEmail ?? null,
-});
-
@Injectable()
export class MessageCampaignService {
- private readonly logger = new Logger(MessageCampaignService.name);
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.emailQueue)
private readonly messageQueueService: MessageQueueService,
private readonly messageChannelMetadataService: MessageChannelMetadataService,
- private readonly messageSuppressionService: MessageSuppressionService,
private readonly userRoleService: UserRoleService,
- private readonly messageCampaignStatisticsService: MessageCampaignStatisticsService,
- private readonly emailBillingService: EmailBillingService,
private readonly campaignVariableService: CampaignVariableService,
- @InjectCacheStorage(CacheStorageNamespace.ModuleEmailing)
- private readonly cacheStorageService: CacheStorageService,
+ private readonly messageCampaignAudienceService: MessageCampaignAudienceService,
+ private readonly messageCampaignLifecycleService: MessageCampaignLifecycleService,
) {}
- private getRoleScopedRepository<T extends ObjectLiteral>(
- entity: Type<T>,
- roleId: string,
- ) {
- return this.workspaceOrmManager.getRepository(entity, {
- unionOf: [roleId],
- });
- }
-
- private getSystemRepository<T extends ObjectLiteral>(entity: Type<T>) {
- return this.workspaceOrmManager.getRepository(entity, {
- shouldBypassPermissionChecks: true,
- });
- }
-
async send({
workspaceId,
userWorkspaceId,
campaignId,
- }: SendCampaignArgs): Promise<SendCampaignResult> {
+ }: {
+ workspaceId: string;
+ userWorkspaceId: string;
+ campaignId: string;
+ }): Promise<SendCampaignResult> {
const roleId = await this.userRoleService.getRoleIdForUserWorkspace({
workspaceId,
userWorkspaceId,
@@ -157,57 +78,26 @@ export class MessageCampaignService {
const { fromAddress, listId } =
await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const sendableCampaign = await this.findSendableDraftCampaignOrThrow(
- workspaceId,
- campaignId,
- roleId,
- );
+ const { fromAddress, listId } =
+ await this.findSendableDraftCampaignOrThrow({
+ workspaceId,
+ campaignId,
+ roleId,
+ });
- return {
- fromAddress: sendableCampaign.fromAddress.primaryEmail,
- listId: sendableCampaign.listId,
- };
+ return { fromAddress: fromAddress.primaryEmail, listId };
});
- const emailingDomain = await this.findVerifiedEmailingDomainOrThrow(
+ const emailingDomain = await this.findSendReadyEmailingDomainOrThrow({
workspaceId,
fromAddress,
- );
+ });
const { recipients, skipped } =
- await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const rawRecipients = await this.resolveRecipientsFromList(
- listId,
- roleId,
- );
-
- const normalized = normalizeCampaignRecipients(
- rawRecipients,
- MAX_CAMPAIGN_RECIPIENTS,
- );
-
- const campaignRepository = await this.getRoleScopedRepository(
- MessageCampaignWorkspaceEntity,
- roleId,
- );
-
- // Conditional update so two concurrent sends cannot both enqueue
- const { affected } = await campaignRepository.update(
- { id: campaignId, status: MessageCampaignStatus.DRAFT },
- { status: MessageCampaignStatus.SENDING },
- );
-
- if (affected !== 1) {
- throw new EmailingDomainException(
- `Campaign ${campaignId} is no longer a sendable draft`,
- EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_SENDABLE,
- );
- }
-
- return {
- recipients: normalized.recipients,
- skipped: normalized.skipped,
- };
+ await this.messageCampaignAudienceService.resolveNormalizedAudience({
+ workspaceId,
+ listId,
+ roleId,
});
const messageChannel =
@@ -217,17 +107,45 @@ export class MessageCampaignService {
workspaceId,
});
- await this.messageQueueService.add<MaterializeCampaignJobData>(
- MATERIALIZE_CAMPAIGN_JOB,
- {
+ const claimed =
+ await this.messageCampaignLifecycleService.transitionCampaignStatus({
workspaceId,
campaignId,
- messageChannelId: messageChannel.id,
- emailingDomainId: emailingDomain.id,
- recipients,
- },
- { retryLimit: 3 },
- );
+ roleId,
+ from: MessageCampaignStatus.DRAFT,
+ to: MessageCampaignStatus.SENDING,
+ });
+
+ if (!claimed) {
+ throw new EmailingDomainException(
+ `Campaign ${campaignId} is no longer a sendable draft`,
+ EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_SENDABLE,
+ );
+ }
+
+ await this.messageQueueService
+ .add<MaterializeCampaignJobData>(
+ MATERIALIZE_CAMPAIGN_JOB,
+ {
+ workspaceId,
+ campaignId,
+ messageChannelId: messageChannel.id,
+ emailingDomainId: emailingDomain.id,
+ recipients,
+ },
+ { retryLimit: 3, backoff: CAMPAIGN_SEND_RETRY_BACKOFF },
+ )
+ .catch(async (error) => {
+ await this.messageCampaignLifecycleService.transitionCampaignStatus({
+ workspaceId,
+ campaignId,
+ roleId,
+ from: MessageCampaignStatus.SENDING,
+ to: MessageCampaignStatus.DRAFT,
+ });
+
+ throw error;
+ });
return { campaignId, queuedCount: recipients.length, skipped };
}
@@ -239,21 +157,29 @@ export class MessageCampaignService {
html,
fromAddress,
unsubscribeTopicId,
- }: SendCampaignTestArgs): Promise<EmailingDomainSendEmailResult> {
- const emailingDomain = await this.findVerifiedEmailingDomainOrThrow(
+ }: {
+ workspaceId: string;
+ toAddress: string;
+ subject: string;
+ html: string;
+ fromAddress: string;
+ unsubscribeTopicId?: string;
+ }): Promise<EmailingDomainSendEmailResult> {
+ const emailingDomain = await this.findSendReadyEmailingDomainOrThrow({
workspaceId,
fromAddress,
- );
+ });
const variables =
await this.campaignVariableService.buildVariablesForPerson(
workspaceId,
null,
);
- const renderedSubject = renderCampaignTemplate(subject, variables, {
- escapeValues: false,
+ const rendered = await renderCampaignEmail({
+ subjectTemplate: subject,
+ bodyTemplate: html,
+ variables,
});
- const compiledContent = await compileCampaignEmailContent(html, variables);
return this.emailingDomainSenderService.sendEmail(
workspaceId,
@@ -261,23 +187,29 @@ export class MessageCampaignService {
{
from: fromAddress,
to: [toAddress],
- subject: renderedSubject,
- text: compiledContent.plainText,
- html: compiledContent.html,
+ subject: rendered.subject,
+ text: rendered.plainText,
+ html: rendered.html,
unsubscribeTopicId,
},
);
}
- private async findVerifiedEmailingDomainOrThrow(
- workspaceId: string,
- fromAddress: string,
- ): Promise<EmailingDomainEntity> {
- const fromDomain = getDomainFromEmail(fromAddress)?.toLowerCase();
-
+ private async findSendReadyEmailingDomainOrThrow({
+ workspaceId,
+ fromAddress,
+ }: {
+ workspaceId: string;
+ fromAddress: string;
+ }): Promise<EmailingDomainEntity> {
const emailingDomain = await this.emailingDomainRepository.findOne(
workspaceId,
- { where: { domain: fromDomain, status: EmailingDomainStatus.VERIFIED } },
+ {
+ where: {
+ domain: getDomainFromEmail(fromAddress)?.toLowerCase(),
+ status: EmailingDomainStatus.VERIFIED,
+ },
+ },
);
if (!isDefined(emailingDomain)) {
@@ -287,295 +219,32 @@ export class MessageCampaignService {
);
}
- return emailingDomain;
- }
-
- async processMaterializeJob(data: MaterializeCampaignJobData): Promise<void> {
- const {
- workspaceId,
- campaignId,
- messageChannelId,
- emailingDomainId,
- recipients,
- } = data;
-
- await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const campaignRepository = await this.getSystemRepository(
- MessageCampaignWorkspaceEntity,
- );
-
- const campaign = await campaignRepository.findOne({
- where: { id: campaignId },
- });
-
- if (!isDefined(campaign)) {
- return;
- }
-
- const recipientsByMessageId = new Map<string, CampaignMessageRecipient>();
-
- for (const recipient of recipients) {
- const messageId = this.campaignMessageId(
- campaignId,
- recipient.personId,
- );
-
- if (!recipientsByMessageId.has(messageId)) {
- recipientsByMessageId.set(messageId, { ...recipient, messageId });
- }
- }
-
- const allRecipients = [...recipientsByMessageId.values()];
-
- const messageRepository = await this.getSystemRepository(
- MessageWorkspaceEntity,
- );
-
- const existingMessages = await messageRepository.find({
- where: { messageCampaignId: campaignId },
- select: { id: true },
- });
- const existingMessageIds = new Set(
- existingMessages.map((message) => message.id),
- );
-
- const recipientsToCreate = allRecipients.filter(
- (recipient) => !existingMessageIds.has(recipient.messageId),
- );
-
- if (recipientsToCreate.length > 0) {
- await this.materializeCampaignMessages({
- campaignId,
- messageChannelId,
- fromAddress: campaign.fromAddress?.primaryEmail ?? '',
- subjectTemplate: campaign.subject ?? '',
- bodyTemplate: campaign.bodyTemplate ?? '',
- recipients: recipientsToCreate,
- });
- }
-
- for (const recipient of allRecipients) {
- await this.messageQueueService.add<SendCampaignEmailJobData>(
- SEND_CAMPAIGN_EMAIL_JOB,
- {
- workspaceId,
- campaignId,
- messageId: recipient.messageId,
- personId: recipient.personId,
- recipientEmail: recipient.email,
- emailingDomainId,
- },
- { retryLimit: 3 },
- );
- }
-
- await this.finalizeCampaignIfComplete(workspaceId, campaignId);
- }, buildSystemAuthContext(workspaceId));
- }
-
- async processSendJob(data: SendCampaignEmailJobData): Promise<void> {
- const {
- workspaceId,
- campaignId,
- messageId,
- personId,
- recipientEmail,
- emailingDomainId,
- } = data;
-
- await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const messageRepository = await this.getSystemRepository(
- MessageWorkspaceEntity,
- );
-
- const message = await messageRepository.findOne({
- where: { id: messageId },
- });
-
- if (
- !isDefined(message) ||
- (message.deliveryStatus !== CAMPAIGN_MESSAGE_DELIVERY_STATUS.QUEUED &&
- message.deliveryStatus !== CAMPAIGN_MESSAGE_DELIVERY_STATUS.FAILED)
- ) {
- return;
- }
-
- const campaignRepository = await this.getSystemRepository(
- MessageCampaignWorkspaceEntity,
- );
-
- const campaign = await campaignRepository.findOne({
- where: { id: campaignId },
- });
-
- if (!isDefined(campaign)) {
- return;
- }
-
- const personRepository = await this.getSystemRepository(
- PersonWorkspaceEntity,
- );
-
- const person = await personRepository.findOne({
- where: { id: personId },
- });
-
- const variables =
- await this.campaignVariableService.buildVariablesForPerson(
- workspaceId,
- person,
- );
- const subject = renderCampaignTemplate(
- campaign.subject ?? '',
- variables,
- {
- escapeValues: false,
- },
- );
- const compiledContent = await compileCampaignEmailContent(
- campaign.bodyTemplate ?? '',
- variables,
+ if (
+ emailingDomain.unsubscribeHostnameStatus !==
+ UnsubscribeHostnameStatus.ACTIVE ||
+ !isNonEmptyString(emailingDomain.unsubscribeHostname)
+ ) {
+ throw new EmailingDomainException(
+ `Cannot send email for ${emailingDomain.domain}: unsubscribe domain is not active (status: ${emailingDomain.unsubscribeHostnameStatus})`,
+ EmailingDomainExceptionCode.EMAILING_DOMAIN_UNSUBSCRIBE_NOT_READY,
);
- const fromAddress = campaign.fromAddress?.primaryEmail ?? '';
- const unsubscribeTopicId = campaign.unsubscribeTopicId ?? undefined;
-
- const hasEmailCredits =
- await this.emailBillingService.hasEmailCredits(workspaceId);
-
- if (!hasEmailCredits) {
- await messageRepository.update(messageId, {
- deliveryStatus: CAMPAIGN_MESSAGE_DELIVERY_STATUS.SKIPPED,
- });
-
- return;
- }
-
- try {
- let result: EmailingDomainSendEmailResult;
-
- try {
- result = await this.emailingDomainSenderService.sendEmail(
- workspaceId,
- emailingDomainId,
- {
- from: fromAddress,
- to: [recipientEmail],
- subject,
- text: compiledContent.plainText,
- html: compiledContent.html,
- unsubscribeTopicId,
- },
- );
- } catch (error) {
- const code =
- error instanceof EmailingDomainDriverException ? error.code : null;
-
- if (
- code === EmailingDomainDriverExceptionCode.ALL_RECIPIENTS_SUPPRESSED
- ) {
- await messageRepository.update(messageId, {
- deliveryStatus: CAMPAIGN_MESSAGE_DELIVERY_STATUS.SKIPPED,
- });
-
- return;
- }
-
- await messageRepository.update(messageId, {
- deliveryStatus: CAMPAIGN_MESSAGE_DELIVERY_STATUS.FAILED,
- });
- this.logger.warn(
- `Campaign ${campaignId} send failed for ${recipientEmail}: ${
- error instanceof Error ? error.message : String(error)
- }`,
- );
-
- const isRetryable =
- !isDefined(code) ||
- code === EmailingDomainDriverExceptionCode.TEMPORARY_ERROR ||
- code === EmailingDomainDriverExceptionCode.UNKNOWN;
-
- if (isRetryable) {
- throw error;
- }
-
- return;
- }
-
- await messageRepository.update(messageId, {
- deliveryStatus: CAMPAIGN_MESSAGE_DELIVERY_STATUS.SENT,
- headerMessageId: result.messageId,
- subject,
- text: compiledContent.plainText,
- });
-
- await this.emailBillingService.billSentEmails({
- workspaceId,
- sentEmailCount: 1,
- });
-
- const associationRepository = await this.getSystemRepository(
- MessageChannelMessageAssociationWorkspaceEntity,
- );
+ }
- await associationRepository.update(
- { messageId },
- {
- messageExternalId: result.messageId,
- messageThreadExternalId: result.messageId,
- },
- );
- } finally {
- await this.finalizeCampaignIfComplete(workspaceId, campaignId);
- }
- }, buildSystemAuthContext(workspaceId));
+ return emailingDomain;
}
- async recordDeliveryFailureByProviderMessageId({
+ private async findSendableDraftCampaignOrThrow({
workspaceId,
- providerMessageId,
- deliveryStatus,
+ campaignId,
+ roleId,
}: {
workspaceId: string;
- providerMessageId: string;
- deliveryStatus: string;
- }): Promise<void> {
- await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const messageRepository = await this.getSystemRepository(
- MessageWorkspaceEntity,
- );
-
- const message = await messageRepository.findOne({
- where: { headerMessageId: providerMessageId },
- });
-
- if (!isDefined(message) || !isDefined(message.messageCampaignId)) {
- return;
- }
-
- if (
- message.deliveryStatus === CAMPAIGN_MESSAGE_DELIVERY_STATUS.BOUNCED ||
- message.deliveryStatus === CAMPAIGN_MESSAGE_DELIVERY_STATUS.COMPLAINED
- ) {
- return;
- }
-
- await messageRepository.update(message.id, { deliveryStatus });
-
- await this.scheduleCampaignStatsRefresh({
- workspaceId,
- campaignId: message.messageCampaignId,
- });
- }, buildSystemAuthContext(workspaceId));
- }
-
- private async findSendableDraftCampaignOrThrow(
- workspaceId: string,
- campaignId: string,
- roleId: string,
- ): Promise<SendableDraftCampaign> {
- const campaignRepository = await this.getRoleScopedRepository(
+ campaignId: string;
+ roleId: string;
+ }): Promise<SendableDraftCampaign> {
+ const campaignRepository = this.workspaceOrmManager.getRepository(
MessageCampaignWorkspaceEntity,
- roleId,
+ { unionOf: [roleId] },
);
const campaign = await campaignRepository.findOne({
@@ -610,287 +279,4 @@ export class MessageCampaignService {
return sendableCampaign.data;
}
-
- private async materializeCampaignMessages({
- campaignId,
- messageChannelId,
- fromAddress,
- subjectTemplate,
- bodyTemplate,
- recipients,
- }: {
- campaignId: string;
- messageChannelId: string;
- fromAddress: string;
- subjectTemplate: string;
- bodyTemplate: string;
- recipients: CampaignMessageRecipient[];
- }): Promise<void> {
- const now = new Date();
- // The stored message keeps the unresolved template, so placeholders stay
- // visible on the campaign's message records.
- const { plainText: text } = await compileCampaignEmailContent(
- bodyTemplate,
- null,
- );
- const rows = recipients.map((recipient) => ({
- recipient,
- messageId: recipient.messageId,
- threadId: v4(),
- temporaryExternalId: v4(),
- }));
-
- await this.workspaceOrmManager.runInWorkspaceTransaction(
- async (transactionScope) => {
- const messageThreadRepository =
- transactionScope.getRepository<MessageThreadWorkspaceEntity>(
- 'messageThread',
- { shouldBypassPermissionChecks: true },
- );
- const messageRepository =
- transactionScope.getRepository<MessageWorkspaceEntity>('message', {
- shouldBypassPermissionChecks: true,
- });
- const associationRepository =
- transactionScope.getRepository<MessageChannelMessageAssociationWorkspaceEntity>(
- 'messageChannelMessageAssociation',
- { shouldBypassPermissionChecks: true },
- );
- const participantRepository =
- transactionScope.getRepository<MessageParticipantWorkspaceEntity>(
- 'messageParticipant',
- { shouldBypassPermissionChecks: true },
- );
-
- await messageThreadRepository.insert(
- rows.map((row) => ({ id: row.threadId })),
- );
- await messageRepository.insert(
- rows.map((row) => ({
- id: row.messageId,
- headerMessageId: row.temporaryExternalId,
- subject: subjectTemplate,
- text,
- receivedAt: now,
- messageThreadId: row.threadId,
- messageCampaignId: campaignId,
- deliveryStatus: CAMPAIGN_MESSAGE_DELIVERY_STATUS.QUEUED,
- })),
- );
- await associationRepository.insert(
- rows.map((row) => ({
- id: v4(),
- messageId: row.messageId,
- messageChannelId,
- messageExternalId: row.temporaryExternalId,
- messageThreadExternalId: row.temporaryExternalId,
- direction: MessageDirection.OUTGOING,
- })),
- );
- await participantRepository.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,
- },
- ]),
- );
- },
- );
- }
-
- private async finalizeCampaignIfComplete(
- workspaceId: string,
- campaignId: string,
- ): Promise<void> {
- const messageRepository = await this.getSystemRepository(
- MessageWorkspaceEntity,
- );
-
- const queuedCount = await messageRepository.count({
- where: {
- messageCampaignId: campaignId,
- deliveryStatus: CAMPAIGN_MESSAGE_DELIVERY_STATUS.QUEUED,
- },
- });
-
- if (queuedCount > 0) {
- return;
- }
-
- const failedCount = await messageRepository.count({
- where: {
- messageCampaignId: campaignId,
- deliveryStatus: CAMPAIGN_MESSAGE_DELIVERY_STATUS.FAILED,
- },
- });
-
- const campaignRepository = await this.getSystemRepository(
- MessageCampaignWorkspaceEntity,
- );
-
- await campaignRepository.update(
- { id: campaignId, status: MessageCampaignStatus.SENDING },
- {
- status:
- failedCount > 0
- ? MessageCampaignStatus.SENT_WITH_ERRORS
- : MessageCampaignStatus.SENT,
- sentAt: new Date(),
- },
- );
-
- await this.scheduleCampaignStatsRefresh({
- workspaceId,
- campaignId,
- });
- }
-
- private async scheduleCampaignStatsRefresh({
- 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 },
- );
- }
-
- async previewAudience({
- workspaceId,
- userWorkspaceId,
- listId,
- unsubscribeTopicId,
- }: {
- workspaceId: string;
- userWorkspaceId: string;
- listId: string;
- unsubscribeTopicId?: string;
- }): Promise<CampaignAudiencePreview> {
- const roleId = await this.userRoleService.getRoleIdForUserWorkspace({
- workspaceId,
- userWorkspaceId,
- });
-
- return this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const rawRecipients = await this.resolveRecipientsFromList(
- listId,
- roleId,
- );
- const totalMembers = rawRecipients.length;
-
- const { recipients, skipped } = normalizeCampaignRecipients(
- rawRecipients,
- MAX_CAMPAIGN_RECIPIENTS,
- );
-
- 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>();
-
- let globallyUnsubscribed = 0;
- let topicUnsubscribed = 0;
- let sendable = 0;
-
- for (const recipient of recipients) {
- const normalizedEmail = recipient.email.trim().toLowerCase();
-
- if (globallySuppressed.has(normalizedEmail)) {
- globallyUnsubscribed += 1;
- } else if (topicSuppressed.has(normalizedEmail)) {
- topicUnsubscribed += 1;
- } else {
- sendable += 1;
- }
- }
-
- return {
- totalMembers,
- withoutEmail: skipped.noEmail,
- duplicateEmails: skipped.deduped,
- globallyUnsubscribed,
- topicUnsubscribed,
- sendable,
- };
- });
- }
-
- private async resolveRecipientsFromList(
- listId: string,
- roleId: string,
- ): Promise<RawCampaignRecipient[]> {
- const listMemberRepository = await this.getRoleScopedRepository(
- MessageListMemberWorkspaceEntity,
- roleId,
- );
-
- const members = await listMemberRepository.find({
- where: { listId },
- });
-
- return this.loadRecipientsByPersonIds(
- members.map((member) => member.personId),
- roleId,
- );
- }
-
- private async loadRecipientsByPersonIds(
- personIds: string[],
- roleId: string,
- ): Promise<RawCampaignRecipient[]> {
- if (personIds.length === 0) {
- return [];
- }
-
- const personRepository = await this.getRoleScopedRepository(
- PersonWorkspaceEntity,
- roleId,
- );
-
- const people = await personRepository.find({
- where: { id: In(personIds) },
- });
-
- return people.map(toRawRecipient);
- }
-
- private campaignMessageId(campaignId: string, personId: string): string {
- return v5(`${campaignId}:${personId}`, CAMPAIGN_MESSAGE_ID_NAMESPACE);
- }
}
diff --git a/packages/twenty-server/src/modules/emailing/types/campaign-message-recipient.type.ts b/packages/twenty-server/src/modules/emailing/types/campaign-message-recipient.type.ts
new file mode 100644
index 00000000000..69356c441ac
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/types/campaign-message-recipient.type.ts
@@ -0,0 +1,5 @@
+import { type CampaignRecipient } from 'src/engine/core-modules/emailing-domain/types/campaign-recipient.type';
+
+export type CampaignMessageRecipient = CampaignRecipient & {
+ messageId: string;
+};
diff --git a/packages/twenty-server/src/modules/emailing/utils/__tests__/build-campaign-message-id.util.spec.ts b/packages/twenty-server/src/modules/emailing/utils/__tests__/build-campaign-message-id.util.spec.ts
new file mode 100644
index 00000000000..e609a9c189e
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/utils/__tests__/build-campaign-message-id.util.spec.ts
@@ -0,0 +1,46 @@
+import { buildCampaignMessageId } from 'src/modules/emailing/utils/build-campaign-message-id.util';
+
+const CAMPAIGN_ID = '9b7c7e0c-6a1e-4f2e-9f3a-2b8d5c1a4e10';
+const OTHER_CAMPAIGN_ID = 'd2f4a6b8-1c3e-4a5b-8d7f-0e9c2a4b6d81';
+const PERSON_ID = '4a2f8c1d-5b6e-4c7a-9d8e-3f1b0a2c5d64';
+const OTHER_PERSON_ID = '7e5d3c1b-9a8f-4e6d-8c7b-5a4f3e2d1c09';
+
+describe('buildCampaignMessageId', () => {
+ it('returns the same id for the same campaign and person', () => {
+ expect(
+ buildCampaignMessageId({ campaignId: CAMPAIGN_ID, personId: PERSON_ID }),
+ ).toBe(
+ buildCampaignMessageId({ campaignId: CAMPAIGN_ID, personId: PERSON_ID }),
+ );
+ });
+
+ it('returns a different id for another person in the same campaign', () => {
+ expect(
+ buildCampaignMessageId({ campaignId: CAMPAIGN_ID, personId: PERSON_ID }),
+ ).not.toBe(
+ buildCampaignMessageId({
+ campaignId: CAMPAIGN_ID,
+ personId: OTHER_PERSON_ID,
+ }),
+ );
+ });
+
+ it('returns a different id for the same person in another campaign', () => {
+ expect(
+ buildCampaignMessageId({ campaignId: CAMPAIGN_ID, personId: PERSON_ID }),
+ ).not.toBe(
+ buildCampaignMessageId({
+ campaignId: OTHER_CAMPAIGN_ID,
+ personId: PERSON_ID,
+ }),
+ );
+ });
+
+ it('is stable across calls so a retried materialization reuses the same message rows', () => {
+ const ids = Array.from({ length: 5 }, () =>
+ buildCampaignMessageId({ campaignId: CAMPAIGN_ID, personId: PERSON_ID }),
+ );
+
+ expect(new Set(ids).size).toBe(1);
+ });
+});
diff --git a/packages/twenty-server/src/modules/emailing/utils/__tests__/compute-campaign-terminal-status.util.spec.ts b/packages/twenty-server/src/modules/emailing/utils/__tests__/compute-campaign-terminal-status.util.spec.ts
new file mode 100644
index 00000000000..d8aaea92b96
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/utils/__tests__/compute-campaign-terminal-status.util.spec.ts
@@ -0,0 +1,101 @@
+import { MessageCampaignStatus } from 'twenty-shared/types';
+
+import { computeCampaignTerminalStatus } from 'src/modules/emailing/utils/compute-campaign-terminal-status.util';
+
+describe('computeCampaignTerminalStatus', () => {
+ it.each([
+ { failedCount: 0, skippedCount: 0 },
+ { failedCount: 1, skippedCount: 0 },
+ { failedCount: 0, skippedCount: 1 },
+ { failedCount: 1, skippedCount: 1 },
+ ])(
+ 'should return undefined while a message is still queued (failed: $failedCount, skipped: $skippedCount)',
+ ({ failedCount, skippedCount }) => {
+ expect(
+ computeCampaignTerminalStatus({
+ totalCount: 10,
+ inProgressCount: 1,
+ failedCount,
+ skippedCount,
+ }),
+ ).toBeUndefined();
+ },
+ );
+
+ it('should return SENT when every message succeeded', () => {
+ expect(
+ computeCampaignTerminalStatus({
+ totalCount: 10,
+ inProgressCount: 0,
+ failedCount: 0,
+ skippedCount: 0,
+ }),
+ ).toBe(MessageCampaignStatus.SENT);
+ });
+
+ it('should return SENT_WITH_ERRORS when a message failed', () => {
+ expect(
+ computeCampaignTerminalStatus({
+ totalCount: 10,
+ inProgressCount: 0,
+ failedCount: 3,
+ skippedCount: 0,
+ }),
+ ).toBe(MessageCampaignStatus.SENT_WITH_ERRORS);
+ });
+
+ it('should return SENT_WITH_ERRORS when a message was skipped', () => {
+ expect(
+ computeCampaignTerminalStatus({
+ totalCount: 10,
+ inProgressCount: 0,
+ failedCount: 0,
+ skippedCount: 3,
+ }),
+ ).toBe(MessageCampaignStatus.SENT_WITH_ERRORS);
+ });
+
+ it('should return SENT_WITH_ERRORS when messages both failed and were skipped', () => {
+ expect(
+ computeCampaignTerminalStatus({
+ totalCount: 10,
+ inProgressCount: 0,
+ failedCount: 2,
+ skippedCount: 5,
+ }),
+ ).toBe(MessageCampaignStatus.SENT_WITH_ERRORS);
+ });
+
+ it('should return SENT when every message finished cleanly', () => {
+ expect(
+ computeCampaignTerminalStatus({
+ totalCount: 10,
+ inProgressCount: 0,
+ failedCount: 0,
+ skippedCount: 0,
+ }),
+ ).toBe(MessageCampaignStatus.SENT);
+ });
+
+ it('should not report a clean send when every recipient was filtered out before materialization', () => {
+ expect(
+ computeCampaignTerminalStatus({
+ totalCount: 0,
+ inProgressCount: 0,
+ failedCount: 0,
+ skippedCount: 0,
+ }),
+ ).toBe(MessageCampaignStatus.SENT_WITH_ERRORS);
+ });
+
+ it('should stay unfinished while a message is claimed but not yet resolved', () => {
+ expect(
+ computeCampaignTerminalStatus({
+ totalCount: 10,
+ inProgressCount: 1,
+ failedCount: 0,
+ skippedCount: 0,
+ }),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-server/src/modules/emailing/utils/__tests__/resolve-campaign-send-failure.util.spec.ts b/packages/twenty-server/src/modules/emailing/utils/__tests__/resolve-campaign-send-failure.util.spec.ts
new file mode 100644
index 00000000000..cf7b75f757e
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/utils/__tests__/resolve-campaign-send-failure.util.spec.ts
@@ -0,0 +1,62 @@
+import {
+ EmailingDomainDriverException,
+ EmailingDomainDriverExceptionCode,
+} from 'src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception';
+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 { resolveCampaignSendFailure } from 'src/modules/emailing/utils/resolve-campaign-send-failure.util';
+
+const driverException = (code: EmailingDomainDriverExceptionCode) =>
+ new EmailingDomainDriverException('failure', code);
+
+describe('resolveCampaignSendFailure', () => {
+ it('should retry a failure that did not come from the driver', () => {
+ const failure = resolveCampaignSendFailure(new Error('socket hang up'));
+
+ expect(failure.state).toBe(CAMPAIGN_DELIVERY_STATE.FAILED);
+ expect(failure.failureReason).toBe(CAMPAIGN_FAILURE_REASON.UNKNOWN);
+ expect(failure.shouldRetry).toBe(true);
+ });
+
+ it('should skip a message whose recipients are all suppressed without retrying', () => {
+ const failure = resolveCampaignSendFailure(
+ driverException(
+ EmailingDomainDriverExceptionCode.ALL_RECIPIENTS_SUPPRESSED,
+ ),
+ );
+
+ expect(failure.state).toBe(CAMPAIGN_DELIVERY_STATE.SKIPPED);
+ expect(failure.skipReason).toBe(CAMPAIGN_SKIP_REASON.SUPPRESSED);
+ expect(failure.shouldRetry).toBe(false);
+ });
+
+ it('should retry a temporary driver error', () => {
+ const failure = resolveCampaignSendFailure(
+ driverException(EmailingDomainDriverExceptionCode.TEMPORARY_ERROR),
+ );
+
+ expect(failure.failureReason).toBe(CAMPAIGN_FAILURE_REASON.TEMPORARY_ERROR);
+ expect(failure.shouldRetry).toBe(true);
+ });
+
+ it('should keep a misconfiguration distinguishable from an unknown failure', () => {
+ const configuration = resolveCampaignSendFailure(
+ driverException(EmailingDomainDriverExceptionCode.CONFIGURATION_ERROR),
+ );
+ const permissions = resolveCampaignSendFailure(
+ driverException(
+ EmailingDomainDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ ),
+ );
+
+ expect(configuration.failureReason).toBe(
+ CAMPAIGN_FAILURE_REASON.CONFIGURATION_ERROR,
+ );
+ expect(permissions.failureReason).toBe(
+ CAMPAIGN_FAILURE_REASON.INSUFFICIENT_PERMISSIONS,
+ );
+ expect(configuration.shouldRetry).toBe(false);
+ expect(permissions.shouldRetry).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/modules/emailing/utils/build-campaign-message-id.util.ts b/packages/twenty-server/src/modules/emailing/utils/build-campaign-message-id.util.ts
new file mode 100644
index 00000000000..b35238131bf
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/utils/build-campaign-message-id.util.ts
@@ -0,0 +1,11 @@
+import { v5 } from 'uuid';
+
+import { CAMPAIGN_MESSAGE_ID_NAMESPACE } from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
+
+export const buildCampaignMessageId = ({
+ campaignId,
+ personId,
+}: {
+ campaignId: string;
+ personId: string;
+}): string => v5(`${campaignId}:${personId}`, CAMPAIGN_MESSAGE_ID_NAMESPACE);
diff --git a/packages/twenty-server/src/modules/emailing/utils/compute-campaign-terminal-status.util.ts b/packages/twenty-server/src/modules/emailing/utils/compute-campaign-terminal-status.util.ts
new file mode 100644
index 00000000000..9a9284935a3
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/utils/compute-campaign-terminal-status.util.ts
@@ -0,0 +1,30 @@
+import { MessageCampaignStatus } from 'twenty-shared/types';
+
+import { type CampaignCounts } from 'src/engine/core-modules/emailing-domain/types/campaign-counts.type';
+
+export const computeCampaignTerminalStatus = ({
+ totalCount,
+ inProgressCount,
+ failedCount,
+ skippedCount,
+}: Pick<
+ CampaignCounts,
+ 'totalCount' | 'inProgressCount' | 'failedCount' | 'skippedCount'
+>):
+ | MessageCampaignStatus.SENT
+ | MessageCampaignStatus.SENT_WITH_ERRORS
+ | undefined => {
+ if (inProgressCount > 0) {
+ return undefined;
+ }
+
+ if (totalCount === 0) {
+ return MessageCampaignStatus.SENT_WITH_ERRORS;
+ }
+
+ if (failedCount > 0 || skippedCount > 0) {
+ return MessageCampaignStatus.SENT_WITH_ERRORS;
+ }
+
+ return MessageCampaignStatus.SENT;
+};
diff --git a/packages/twenty-server/src/modules/emailing/utils/render-campaign-email.util.ts b/packages/twenty-server/src/modules/emailing/utils/render-campaign-email.util.ts
new file mode 100644
index 00000000000..de6b173306b
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/utils/render-campaign-email.util.ts
@@ -0,0 +1,25 @@
+import { compileCampaignEmailContent } from 'src/modules/emailing/utils/compile-campaign-email-content.util';
+import { renderCampaignTemplate } from 'src/modules/emailing/utils/render-campaign-template.util';
+
+export const renderCampaignEmail = async ({
+ subjectTemplate,
+ bodyTemplate,
+ variables,
+}: {
+ subjectTemplate: string;
+ bodyTemplate: string;
+ variables: Record<string, string>;
+}): Promise<{ subject: string; html: string; plainText: string }> => {
+ const { html, plainText } = await compileCampaignEmailContent(
+ bodyTemplate,
+ variables,
+ );
+
+ return {
+ subject: renderCampaignTemplate(subjectTemplate, variables, {
+ escapeValues: false,
+ }),
+ html,
+ plainText,
+ };
+};
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
new file mode 100644
index 00000000000..532863a48ae
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/utils/resolve-campaign-send-failure.util.ts
@@ -0,0 +1,62 @@
+import {
+ EmailingDomainDriverException,
+ EmailingDomainDriverExceptionCode,
+} from 'src/engine/core-modules/emailing-domain/drivers/exceptions/emailing-domain-driver.exception';
+import { CAMPAIGN_DELIVERY_STATE } from 'src/engine/core-modules/emailing-domain/constants/campaign-delivery-state.constant';
+import { type CampaignDeliveryState } from 'src/engine/core-modules/emailing-domain/types/campaign-delivery-state.type';
+import { CAMPAIGN_FAILURE_REASON } from 'src/engine/core-modules/emailing-domain/constants/campaign-failure-reason.constant';
+import { type CampaignFailureReason } from 'src/engine/core-modules/emailing-domain/types/campaign-failure-reason.type';
+import { CAMPAIGN_SKIP_REASON } from 'src/engine/core-modules/emailing-domain/constants/campaign-skip-reason.constant';
+import { type CampaignSkipReason } from 'src/engine/core-modules/emailing-domain/types/campaign-skip-reason.type';
+import { assertUnreachable } from 'twenty-shared/utils';
+
+type CampaignSendFailure = {
+ state: CampaignDeliveryState;
+ skipReason: CampaignSkipReason | null;
+ failureReason: CampaignFailureReason | null;
+ 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);
+ }
+
+ switch (error.code) {
+ case EmailingDomainDriverExceptionCode.ALL_RECIPIENTS_SUPPRESSED:
+ return {
+ state: CAMPAIGN_DELIVERY_STATE.SKIPPED,
+ skipReason: CAMPAIGN_SKIP_REASON.SUPPRESSED,
+ failureReason: null,
+ shouldRetry: false,
+ };
+ case EmailingDomainDriverExceptionCode.TEMPORARY_ERROR:
+ return failed(CAMPAIGN_FAILURE_REASON.TEMPORARY_ERROR, true);
+ case EmailingDomainDriverExceptionCode.UNKNOWN:
+ return failed(CAMPAIGN_FAILURE_REASON.UNKNOWN, true);
+ case EmailingDomainDriverExceptionCode.SENDING_SUSPENDED:
+ return failed(CAMPAIGN_FAILURE_REASON.SENDING_SUSPENDED, true);
+ case EmailingDomainDriverExceptionCode.UNSUBSCRIBE_NOT_READY:
+ return failed(CAMPAIGN_FAILURE_REASON.UNSUBSCRIBE_NOT_READY, 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);
+ default:
+ return assertUnreachable(error.code);
+ }
+};
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-suppression-handler.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-suppression-handler.service.ts
index a3ff16ef910..78d4cbf2d07 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-suppression-handler.service.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/handlers/outbound-suppression-handler.service.ts
@@ -2,10 +2,9 @@ import { Injectable } from '@nestjs/common';
import { isDefined } from 'twenty-shared/utils';
-import { CAMPAIGN_MESSAGE_DELIVERY_STATUS } from 'src/engine/core-modules/emailing-domain/constants/campaign.constant';
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 { MessageCampaignService } from 'src/modules/emailing/services/message-campaign.service';
+import { MessageCampaignDeliveryFeedbackService } from 'src/modules/emailing/services/message-campaign-delivery-feedback.service';
import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';
import { type NormalizedOutboundSuppressionEvent } from 'src/modules/messaging-webhooks/types/normalized-outbound-suppression-event.type';
@@ -13,19 +12,19 @@ import { type NormalizedOutboundSuppressionEvent } from 'src/modules/messaging-w
export class OutboundSuppressionHandlerService {
constructor(
private readonly messageSuppressionService: MessageSuppressionService,
- private readonly messageCampaignService: MessageCampaignService,
+ private readonly messageCampaignDeliveryFeedbackService: MessageCampaignDeliveryFeedbackService,
) {}
async handle(event: NormalizedOutboundSuppressionEvent): Promise<void> {
if (isDefined(event.providerMessageId)) {
- await this.messageCampaignService.recordDeliveryFailureByProviderMessageId(
+ await this.messageCampaignDeliveryFeedbackService.recordProviderOutcomeByProviderMessageId(
{
workspaceId: event.workspaceId,
providerMessageId: event.providerMessageId,
- deliveryStatus:
+ outcome:
event.reason === MessageSuppressionReason.COMPLAINT
- ? CAMPAIGN_MESSAGE_DELIVERY_STATUS.COMPLAINED
- : CAMPAIGN_MESSAGE_DELIVERY_STATUS.BOUNCED,
+ ? 'COMPLAINED'
+ : 'BOUNCED',
},
);
}
diff --git a/packages/twenty-server/test/integration/upgrade/suites/campaign-delivery-claim.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/campaign-delivery-claim.integration-spec.ts
new file mode 100644
index 00000000000..ce7acf3b7db
--- /dev/null
+++ b/packages/twenty-server/test/integration/upgrade/suites/campaign-delivery-claim.integration-spec.ts
@@ -0,0 +1,187 @@
+import { config } from 'dotenv';
+import { isDefined } from 'twenty-shared/utils';
+import { DataSource } from 'typeorm';
+import { v4 } from 'uuid';
+
+jest.useRealTimers();
+
+config({
+ path: process.env.NODE_ENV === 'test' ? '.env.test' : '.env',
+ override: true,
+});
+
+const CLAIM_TTL_MS = 5 * 60 * 1000;
+
+describe('campaignDelivery claim protocol (integration)', () => {
+ let dataSource: DataSource;
+ let workspaceId: string;
+ const seededDeliveryIds: string[] = [];
+
+ const claim = async (
+ deliveryId: string,
+ ): Promise<{ claimToken: string; won: boolean }> => {
+ const claimToken = v4();
+
+ const [, affected] = await dataSource.query(
+ `UPDATE "core"."campaignDelivery"
+ SET "state" = 'SENDING', "claimToken" = $1, "claimExpiresAt" = $2
+ WHERE "id" = $3 AND "state" IN ('QUEUED', 'FAILED')`,
+ [claimToken, new Date(Date.now() + CLAIM_TTL_MS), deliveryId],
+ );
+
+ return { claimToken, won: affected === 1 };
+ };
+
+ const settle = async (
+ deliveryId: string,
+ claimToken: string,
+ ): Promise<number> => {
+ const [, affected] = await dataSource.query(
+ `UPDATE "core"."campaignDelivery"
+ SET "state" = 'SENT', "claimToken" = NULL, "claimExpiresAt" = NULL
+ WHERE "id" = $1 AND "claimToken" = $2`,
+ [deliveryId, claimToken],
+ );
+
+ return affected;
+ };
+
+ const seedQueuedDelivery = async (): Promise<string> => {
+ const deliveryId = v4();
+
+ await dataSource.query(
+ `INSERT INTO "core"."campaignDelivery"
+ ("id", "workspaceId", "campaignId", "personId", "recipientEmail", "state")
+ VALUES ($1, $2, $3, $4, $5, 'QUEUED')`,
+ [deliveryId, workspaceId, v4(), v4(), `claim-test-${deliveryId}@example.com`],
+ );
+
+ seededDeliveryIds.push(deliveryId);
+
+ return deliveryId;
+ };
+
+ const readDelivery = async (
+ deliveryId: string,
+ ): Promise<{ state: string; claimToken: string | null }> => {
+ const [row] = await dataSource.query(
+ `SELECT "state", "claimToken" FROM "core"."campaignDelivery" WHERE "id" = $1`,
+ [deliveryId],
+ );
+
+ return row;
+ };
+
+ beforeAll(async () => {
+ dataSource = new DataSource({
+ type: 'postgres',
+ url: process.env.PG_DATABASE_URL,
+ schema: 'core',
+ entities: [],
+ synchronize: false,
+ });
+ await dataSource.initialize();
+
+ const [seedWorkspaceRow] = await dataSource.query(
+ `SELECT id AS "workspaceId" FROM "core"."workspace" LIMIT 1`,
+ );
+
+ if (!isDefined(seedWorkspaceRow)) {
+ throw new Error(
+ 'No seeded workspace row found; run database:reset before the integration suite.',
+ );
+ }
+
+ workspaceId = seedWorkspaceRow.workspaceId;
+ });
+
+ afterAll(async () => {
+ if (seededDeliveryIds.length > 0) {
+ await dataSource.query(
+ `DELETE FROM "core"."campaignDelivery" WHERE "id" = ANY($1)`,
+ [seededDeliveryIds],
+ );
+ }
+
+ await dataSource.destroy();
+ });
+
+ it('lets exactly one of two concurrent workers claim the same delivery', async () => {
+ const deliveryId = await seedQueuedDelivery();
+
+ const [first, second] = await Promise.all([
+ claim(deliveryId),
+ claim(deliveryId),
+ ]);
+
+ expect([first.won, second.won].filter(Boolean)).toHaveLength(1);
+ });
+
+ it('refuses the losing worker a settle, so it can neither record nor bill the send', async () => {
+ const deliveryId = await seedQueuedDelivery();
+
+ const [first, second] = await Promise.all([
+ claim(deliveryId),
+ claim(deliveryId),
+ ]);
+
+ const winner = first.won ? first : second;
+ const loser = first.won ? second : first;
+
+ expect(await settle(deliveryId, loser.claimToken)).toBe(0);
+ expect(await settle(deliveryId, winner.claimToken)).toBe(1);
+ expect(await readDelivery(deliveryId)).toEqual({
+ state: 'SENT',
+ claimToken: null,
+ });
+ });
+
+ it('refuses a stale claim token after the sweeper reclaims an expired lease', async () => {
+ const deliveryId = await seedQueuedDelivery();
+ const abandoned = await claim(deliveryId);
+
+ await dataSource.query(
+ `UPDATE "core"."campaignDelivery"
+ SET "claimExpiresAt" = $1 WHERE "id" = $2`,
+ [new Date(Date.now() - 1), deliveryId],
+ );
+
+ await dataSource.query(
+ `UPDATE "core"."campaignDelivery"
+ SET "state" = 'FAILED', "failureReason" = 'CLAIM_EXPIRED',
+ "claimToken" = NULL, "claimExpiresAt" = NULL
+ WHERE "id" = $1 AND "state" = 'SENDING' AND "claimExpiresAt" < now()`,
+ [deliveryId],
+ );
+
+ const reclaimed = await claim(deliveryId);
+
+ expect(reclaimed.won).toBe(true);
+ expect(await settle(deliveryId, abandoned.claimToken)).toBe(0);
+ expect(await settle(deliveryId, reclaimed.claimToken)).toBe(1);
+ });
+
+ it('never leaves a claim half written', async () => {
+ const deliveryId = await seedQueuedDelivery();
+
+ await expect(
+ dataSource.query(
+ `UPDATE "core"."campaignDelivery"
+ SET "claimToken" = $1, "claimExpiresAt" = NULL WHERE "id" = $2`,
+ [v4(), deliveryId],
+ ),
+ ).rejects.toThrow(/CHK_CAMPAIGN_DELIVERY_CLAIM_IS_WHOLE/);
+ });
+
+ it('never leaves a sending delivery without a lease', async () => {
+ const deliveryId = await seedQueuedDelivery();
+
+ await expect(
+ dataSource.query(
+ `UPDATE "core"."campaignDelivery"
+ SET "state" = 'SENDING' WHERE "id" = $1`,
+ [deliveryId],
+ ),
+ ).rejects.toThrow(/CHK_CAMPAIGN_DELIVERY_CLAIM_HAS_LEASE/);
+ });
+});