Skip to content

The open alternative to Salesforce, designed for AI.

Reconcile message and calendar targets in participant transactions (#24778)

Félix Malfait633ab6aaee49
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 ba3f8c77eb5..1456f1c17c3 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
@@ -542,6 +542,7 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
async insert(
entityOrEntities: Partial<ObjectRecord> | Partial<ObjectRecord>[],
+ options?: { onConflictDoNothing?: boolean },
): Promise<InsertResult> {
const records = Array.isArray(entityOrEntities)
? entityOrEntities
@@ -552,6 +553,7 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
columnsToReturn: this.options.shouldBypassPermissionChecks
? Object.keys(this.options.tableShape.columnShapeByColumnName)
: ['id'],
+ onConflictDoNothing: options?.onConflictDoNothing,
});
const insertResult = new InsertResult();
@@ -872,9 +874,11 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
async runInsert({
records,
columnsToReturn,
+ onConflictDoNothing,
}: {
records: Partial<ObjectRecord>[];
columnsToReturn: string[];
+ onConflictDoNothing?: boolean;
}): Promise<{
identifiers: { id: string }[];
generatedMaps: ObjectRecord[];
@@ -923,6 +927,7 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
columnNames,
rows,
returningColumns: columnsToReturn,
+ onConflictDoNothing,
});
const rawRows = await this.executeRaw<ObjectRecord>(sql, parameters);
diff --git a/packages/twenty-server/src/engine/twenty-orm/sql/utils/__tests__/build-insert-statement.util.spec.ts b/packages/twenty-server/src/engine/twenty-orm/sql/utils/__tests__/build-insert-statement.util.spec.ts
index d2713761d2e..b61cbdff517 100644
--- a/packages/twenty-server/src/engine/twenty-orm/sql/utils/__tests__/build-insert-statement.util.spec.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/sql/utils/__tests__/build-insert-statement.util.spec.ts
@@ -86,6 +86,21 @@ describe('buildInsertStatement', () => {
);
});
+ it('should support conflict-safe inserts', () => {
+ expect(
+ buildInsertStatement({
+ tableShape: personTableShape,
+ columnNames: ['id'],
+ rows: [[{ kind: 'parameter', parameterName: 'ormInsert_0' }]],
+ returningColumns: ['id'],
+ onConflictDoNothing: true,
+ }),
+ ).toBe(
+ `INSERT INTO "${SCHEMA_NAME}"."person" ("id") ` +
+ 'VALUES (:ormInsert_0) ON CONFLICT DO NOTHING RETURNING "id"',
+ );
+ });
+
it('should reject an insert with no rows', () => {
expect(() =>
buildInsertStatement({
diff --git a/packages/twenty-server/src/engine/twenty-orm/sql/utils/build-insert-statement.util.ts b/packages/twenty-server/src/engine/twenty-orm/sql/utils/build-insert-statement.util.ts
index bcf2ca94ccb..debb2baf483 100644
--- a/packages/twenty-server/src/engine/twenty-orm/sql/utils/build-insert-statement.util.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/sql/utils/build-insert-statement.util.ts
@@ -14,6 +14,7 @@ export type InsertStatementState = {
columnNames: string[];
rows: InsertRowValue[][];
returningColumns: string[];
+ onConflictDoNothing?: boolean;
};
const buildReturningClause = (returningColumns: string[]): string => {
@@ -56,6 +57,7 @@ export const buildInsertStatement = (state: InsertStatementState): string => {
state.tableShape.tableName,
)} (${columnList})`,
`VALUES ${valuesList}`,
+ state.onConflictDoNothing ? 'ON CONFLICT DO NOTHING' : '',
buildReturningClause(state.returningColumns),
]
.filter((part) => part.length > 0)
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/get-workspace-repository-with-optional-transaction.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/get-workspace-repository-with-optional-transaction.util.ts
new file mode 100644
index 00000000000..5e61bdf0b21
--- /dev/null
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/get-workspace-repository-with-optional-transaction.util.ts
@@ -0,0 +1,30 @@
+import { isDefined } from 'twenty-shared/utils';
+import { type ObjectLiteral } from 'typeorm';
+
+import { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace-repository';
+import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';
+import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/types/workspace-transaction-scope.type';
+import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+
+export const getWorkspaceRepositoryWithOptionalTransaction = <
+ Entity extends ObjectLiteral,
+>({
+ objectMetadataName,
+ transactionScope,
+ workspaceOrmManager,
+ rolePermissionConfig,
+}: {
+ objectMetadataName: string;
+ transactionScope?: WorkspaceTransactionScope;
+ workspaceOrmManager: WorkspaceOrmManager;
+ rolePermissionConfig?: RolePermissionConfig;
+}): WorkspaceRepository<Entity> =>
+ isDefined(transactionScope)
+ ? transactionScope.getRepository<Entity>(
+ objectMetadataName,
+ rolePermissionConfig,
+ )
+ : workspaceOrmManager.getRepository<Entity>(
+ objectMetadataName,
+ rolePermissionConfig,
+ );
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/services/calendar-save-events.service.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/services/calendar-save-events.service.ts
index c3718160052..3174265daf6 100644
--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/services/calendar-save-events.service.ts
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/services/calendar-save-events.service.ts
@@ -1,5 +1,6 @@
import { Injectable } from '@nestjs/common';
+import { isDefined } from 'twenty-shared/utils';
import { Any } from 'typeorm';
import { v4 as uuid } from 'uuid';
@@ -286,6 +287,14 @@ export class CalendarSaveEventsService {
);
});
+ const calendarEventIds =
+ fetchedCalendarEventsWithDBEventsEnrichedWithSavedEvents
+ .map(
+ ({ newlyCreatedCalendarEvent, existingCalendarEvent }) =>
+ newlyCreatedCalendarEvent?.id ?? existingCalendarEvent?.id,
+ )
+ .filter(isDefined);
+
await this.calendarEventParticipantService.upsertAndDeleteCalendarEventParticipants(
{
participantsToCreate,
@@ -294,6 +303,7 @@ export class CalendarSaveEventsService {
calendarChannel,
connectedAccount,
workspaceId,
+ calendarEventIds,
},
);
},
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/services/calendar-event-participant.service.ts b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/services/calendar-event-participant.service.ts
index a2833889d6c..2dd7f2dee72 100644
--- a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/services/calendar-event-participant.service.ts
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/services/calendar-event-participant.service.ts
@@ -48,6 +48,7 @@ export class CalendarEventParticipantService {
calendarChannel,
connectedAccount,
workspaceId,
+ calendarEventIds,
}: {
participantsToCreate: FetchedCalendarEventParticipantWithCalendarEventId[];
participantsToUpdate: FetchedCalendarEventParticipantWithCalendarEventId[];
@@ -55,6 +56,7 @@ export class CalendarEventParticipantService {
calendarChannel: CalendarChannelEntity;
connectedAccount: ConnectedAccountEntity;
workspaceId: string;
+ calendarEventIds: string[];
}): Promise<void> {
const authContext = buildSystemAuthContext(workspaceId);
@@ -175,6 +177,7 @@ export class CalendarEventParticipantService {
await this.matchParticipantService.matchParticipants({
participants: savedParticipants,
+ sourceRecordIds: calendarEventIds,
objectMetadataName: 'calendarEventParticipant',
matchWith: 'workspaceMemberAndPerson',
transactionScope,
diff --git a/packages/twenty-server/src/modules/match-participant/match-participant.module.ts b/packages/twenty-server/src/modules/match-participant/match-participant.module.ts
index 4e3331c67e5..f1fbe3eabbd 100644
--- a/packages/twenty-server/src/modules/match-participant/match-participant.module.ts
+++ b/packages/twenty-server/src/modules/match-participant/match-participant.module.ts
@@ -1,10 +1,11 @@
import { Module } from '@nestjs/common';
import { MatchParticipantService } from 'src/modules/match-participant/match-participant.service';
+import { ParticipantTargetReconciliationService } from 'src/modules/match-participant/participant-target-reconciliation.service';
@Module({
imports: [],
- providers: [MatchParticipantService],
- exports: [MatchParticipantService],
+ providers: [MatchParticipantService, ParticipantTargetReconciliationService],
+ exports: [MatchParticipantService, ParticipantTargetReconciliationService],
})
export class MatchParticipantModule {}
diff --git a/packages/twenty-server/src/modules/match-participant/match-participant.service.ts b/packages/twenty-server/src/modules/match-participant/match-participant.service.ts
index a1d8318ffc2..c550b767c97 100644
--- a/packages/twenty-server/src/modules/match-participant/match-participant.service.ts
+++ b/packages/twenty-server/src/modules/match-participant/match-participant.service.ts
@@ -7,7 +7,9 @@ import { Any, In } from 'typeorm';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/types/workspace-transaction-scope.type';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+import { getWorkspaceRepositoryWithOptionalTransaction } from 'src/engine/twenty-orm/utils/get-workspace-repository-with-optional-transaction.util';
import { type CalendarEventParticipantWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-event-participant.workspace-entity';
+import { ParticipantTargetReconciliationService } from 'src/modules/match-participant/participant-target-reconciliation.service';
import { addPersonEmailFiltersToQueryBuilder } from 'src/modules/match-participant/utils/add-person-email-filters-to-query-builder';
import { findPersonByPrimaryOrAdditionalEmail } from 'src/modules/match-participant/utils/find-person-by-primary-or-additional-email';
import { type MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';
@@ -50,6 +52,7 @@ type MatchParticipantsArgs<
>,
> = {
participants: ParticipantWorkspaceEntity[];
+ sourceRecordIds: string[];
objectMetadataName: ObjectMetadataName;
matchWith: 'workspaceMemberOnly' | 'personOnly' | 'workspaceMemberAndPerson';
transactionScope?: WorkspaceTransactionScope;
@@ -61,59 +64,70 @@ export class MatchParticipantService<
| CalendarEventParticipantWorkspaceEntity
| MessageParticipantWorkspaceEntity,
> {
- constructor(private readonly workspaceOrmManager: WorkspaceOrmManager) {}
+ constructor(
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly participantTargetReconciliationService: ParticipantTargetReconciliationService,
+ ) {}
- private async getParticipantRepository({
+ private getParticipantRepository({
objectMetadataName,
transactionScope,
}: GetParticipantRepositoryArgs) {
- if (objectMetadataName === 'messageParticipant') {
- if (isDefined(transactionScope)) {
- return transactionScope.getRepository<MessageParticipantWorkspaceEntity>(
- objectMetadataName,
- );
- }
-
- return this.workspaceOrmManager.getRepository<MessageParticipantWorkspaceEntity>(
- objectMetadataName,
- );
- }
-
- if (isDefined(transactionScope)) {
- return transactionScope.getRepository<CalendarEventParticipantWorkspaceEntity>(
+ return getWorkspaceRepositoryWithOptionalTransaction<ParticipantWorkspaceEntity>(
+ {
objectMetadataName,
- );
- }
-
- return this.workspaceOrmManager.getRepository<CalendarEventParticipantWorkspaceEntity>(
- objectMetadataName,
+ transactionScope,
+ workspaceOrmManager: this.workspaceOrmManager,
+ },
);
}
public async matchParticipants({
participants,
+ sourceRecordIds,
objectMetadataName,
matchWith = 'workspaceMemberAndPerson',
transactionScope,
}: MatchParticipantsArgs<ParticipantWorkspaceEntity>) {
+ // Desired targets derive from personId only, so a workspaceMemberOnly
+ // rematch can never change them; skip the recompute in that case.
+ const shouldReconcileTargets = matchWith !== 'workspaceMemberOnly';
+
if (participants.length === 0) {
+ if (shouldReconcileTargets) {
+ await this.participantTargetReconciliationService.reconcileParticipantTargets(
+ {
+ sourceRecordIds,
+ objectMetadataName,
+ transactionScope,
+ },
+ );
+ }
+
return;
}
const personRepository =
- this.workspaceOrmManager.getRepository<PersonWorkspaceEntity>('person', {
- shouldBypassPermissionChecks: true,
+ getWorkspaceRepositoryWithOptionalTransaction<PersonWorkspaceEntity>({
+ objectMetadataName: 'person',
+ transactionScope,
+ workspaceOrmManager: this.workspaceOrmManager,
+ rolePermissionConfig: { shouldBypassPermissionChecks: true },
});
- const participantRepository = await this.getParticipantRepository({
+ const participantRepository = this.getParticipantRepository({
objectMetadataName,
transactionScope,
});
const workspaceMemberRepository =
- this.workspaceOrmManager.getRepository<WorkspaceMemberWorkspaceEntity>(
- 'workspaceMember',
- { shouldBypassPermissionChecks: true },
+ getWorkspaceRepositoryWithOptionalTransaction<WorkspaceMemberWorkspaceEntity>(
+ {
+ objectMetadataName: 'workspaceMember',
+ transactionScope,
+ workspaceOrmManager: this.workspaceOrmManager,
+ rolePermissionConfig: { shouldBypassPermissionChecks: true },
+ },
);
const chunkSize = 200;
@@ -196,6 +210,16 @@ export class MatchParticipantService<
})),
);
}
+
+ if (shouldReconcileTargets) {
+ await this.participantTargetReconciliationService.reconcileParticipantTargets(
+ {
+ sourceRecordIds,
+ objectMetadataName,
+ transactionScope,
+ },
+ );
+ }
}
public async matchParticipantsForWorkspaceMembers({
@@ -206,28 +230,33 @@ export class MatchParticipantService<
const authContext = buildSystemAuthContext(workspaceId);
await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const participantRepository = await this.getParticipantRepository({
- objectMetadataName,
- });
-
- const participants = await participantRepository.find({
- where: {
- workspaceMemberId: In(participantMatching.workspaceMemberIds),
- },
- });
+ await this.workspaceOrmManager.runInWorkspaceTransaction(
+ async (transactionScope) => {
+ const participantRepository = this.getParticipantRepository({
+ objectMetadataName,
+ transactionScope,
+ });
- const tobeRematchedParticipants = participants.map((participant) => {
- return {
- ...participant,
- workspaceMemberId: null,
- };
- });
+ const participants = await participantRepository.find({
+ where: {
+ workspaceMemberId: In(participantMatching.workspaceMemberIds),
+ },
+ });
- await this.matchParticipants({
- matchWith: 'workspaceMemberOnly',
- participants: tobeRematchedParticipants as ParticipantWorkspaceEntity[],
- objectMetadataName,
- });
+ const rematchedParticipants = participants.map((participant) => ({
+ ...participant,
+ workspaceMemberId: null,
+ })) as ParticipantWorkspaceEntity[];
+
+ await this.matchParticipants({
+ matchWith: 'workspaceMemberOnly',
+ participants: rematchedParticipants,
+ sourceRecordIds: this.getSourceRecordIds(rematchedParticipants),
+ objectMetadataName,
+ transactionScope,
+ });
+ },
+ );
}, authContext);
}
@@ -239,50 +268,69 @@ export class MatchParticipantService<
const authContext = buildSystemAuthContext(workspaceId);
await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const participantRepository = await this.getParticipantRepository({
- objectMetadataName,
- });
+ await this.workspaceOrmManager.runInWorkspaceTransaction(
+ async (transactionScope) => {
+ const participantRepository = this.getParticipantRepository({
+ objectMetadataName,
+ transactionScope,
+ });
- let participantsMatchingPersonEmails: ParticipantWorkspaceEntity[] = [];
- let participantsMatchingPersonId: ParticipantWorkspaceEntity[] = [];
+ let participantsMatchingPersonEmails: ParticipantWorkspaceEntity[] =
+ [];
+ let participantsMatchingPersonId: ParticipantWorkspaceEntity[] = [];
- if (participantMatching.personIds.length > 0) {
- participantsMatchingPersonId = (await participantRepository.find({
- where: {
- personId: In(participantMatching.personIds),
- },
- })) as ParticipantWorkspaceEntity[];
- }
+ if (participantMatching.personIds.length > 0) {
+ participantsMatchingPersonId = (await participantRepository.find({
+ where: {
+ personId: In(participantMatching.personIds),
+ },
+ })) as ParticipantWorkspaceEntity[];
+ }
- if (participantMatching.personEmails.length > 0) {
- participantsMatchingPersonEmails = (await participantRepository.find({
- where: {
- handle: In(participantMatching.personEmails),
- },
- })) as ParticipantWorkspaceEntity[];
- }
+ if (participantMatching.personEmails.length > 0) {
+ participantsMatchingPersonEmails =
+ (await participantRepository.find({
+ where: {
+ handle: In(participantMatching.personEmails),
+ },
+ })) as ParticipantWorkspaceEntity[];
+ }
- const uniqueParticipants = [
- ...new Set([
- ...participantsMatchingPersonId,
- ...participantsMatchingPersonEmails,
- ]),
- ];
+ const uniqueParticipants = [
+ ...new Set([
+ ...participantsMatchingPersonId,
+ ...participantsMatchingPersonEmails,
+ ]),
+ ];
+
+ const tobeRematchedParticipants = uniqueParticipants.map(
+ (participant) => {
+ return {
+ ...participant,
+ personId: null,
+ };
+ },
+ );
- const tobeRematchedParticipants = uniqueParticipants.map(
- (participant) => {
- return {
- ...participant,
- personId: null,
- };
+ await this.matchParticipants({
+ matchWith: 'personOnly',
+ participants: tobeRematchedParticipants,
+ sourceRecordIds: this.getSourceRecordIds(tobeRematchedParticipants),
+ objectMetadataName,
+ transactionScope,
+ });
},
);
-
- await this.matchParticipants({
- matchWith: 'personOnly',
- participants: tobeRematchedParticipants,
- objectMetadataName,
- });
}, authContext);
}
+
+ private getSourceRecordIds(
+ participants: ParticipantWorkspaceEntity[],
+ ): string[] {
+ return participants.map((participant) =>
+ 'messageId' in participant
+ ? participant.messageId
+ : participant.calendarEventId,
+ );
+ }
}
diff --git a/packages/twenty-server/src/modules/match-participant/participant-target-reconciliation.service.ts b/packages/twenty-server/src/modules/match-participant/participant-target-reconciliation.service.ts
new file mode 100644
index 00000000000..b228b15904f
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/participant-target-reconciliation.service.ts
@@ -0,0 +1,450 @@
+import { Injectable } from '@nestjs/common';
+
+import chunk from 'lodash.chunk';
+import { QUERY_MAX_RECORDS } from 'twenty-shared/constants';
+import { isDefined } from 'twenty-shared/utils';
+import { In, type ObjectLiteral } from 'typeorm';
+
+import { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace-repository';
+import { getWorkspaceContext } from 'src/engine/twenty-orm/storage/orm-workspace-context.storage';
+import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/types/workspace-transaction-scope.type';
+import { getWorkspaceRepositoryWithOptionalTransaction } from 'src/engine/twenty-orm/utils/get-workspace-repository-with-optional-transaction.util';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { type CalendarEventParticipantWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-event-participant.workspace-entity';
+import { type MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';
+import { type MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
+import {
+ computeTargetReconciliationOperations,
+ type ExistingTarget,
+ type TargetIdentity,
+} from 'src/modules/match-participant/utils/compute-target-reconciliation-operations.util';
+import { type OpportunityWorkspaceEntity } from 'src/modules/opportunity/standard-objects/opportunity.workspace-entity';
+import { type PersonWorkspaceEntity } from 'src/modules/person/standard-objects/person.workspace-entity';
+
+type TargetParentFieldName = 'calendarEventId' | 'messageThreadId';
+
+type TargetWorkspaceEntity = Omit<ExistingTarget, 'parentId' | 'deletedAt'> & {
+ calendarEventId?: string | null;
+ messageThreadId?: string | null;
+ deletedAt: string | null;
+};
+
+@Injectable()
+export class ParticipantTargetReconciliationService {
+ constructor(private readonly workspaceOrmManager: WorkspaceOrmManager) {}
+
+ public async reconcileParticipantTargets({
+ sourceRecordIds,
+ objectMetadataName,
+ transactionScope,
+ }: {
+ sourceRecordIds: string[];
+ objectMetadataName: 'messageParticipant' | 'calendarEventParticipant';
+ transactionScope?: WorkspaceTransactionScope;
+ }): Promise<void> {
+ if (objectMetadataName === 'messageParticipant') {
+ await this.reconcileMessageThreadTargetsFromMessageIds({
+ messageIds: sourceRecordIds,
+ transactionScope,
+ });
+
+ return;
+ }
+
+ await this.reconcileCalendarEventTargets({
+ calendarEventIds: sourceRecordIds,
+ transactionScope,
+ });
+ }
+
+ public async reconcileCalendarEventTargets({
+ calendarEventIds,
+ transactionScope,
+ }: {
+ calendarEventIds: string[];
+ transactionScope?: WorkspaceTransactionScope;
+ }): Promise<void> {
+ for (const calendarEventIdChunk of chunk(
+ [...new Set(calendarEventIds)],
+ QUERY_MAX_RECORDS,
+ )) {
+ const participantRepository =
+ await this.getRepository<CalendarEventParticipantWorkspaceEntity>(
+ 'calendarEventParticipant',
+ transactionScope,
+ );
+
+ const participants = await participantRepository.find({
+ where: { calendarEventId: In(calendarEventIdChunk) },
+ select: { calendarEventId: true, personId: true },
+ });
+
+ await this.reconcileTargets({
+ parentIds: calendarEventIdChunk,
+ parentFieldName: 'calendarEventId',
+ participantPersonIdsByParentId: this.groupParticipantPersonIds({
+ participants,
+ getParentId: (participant) => participant.calendarEventId,
+ }),
+ targetObjectName: 'calendarEventTarget',
+ transactionScope,
+ });
+ }
+ }
+
+ public async reconcileMessageThreadTargetsFromMessageIds({
+ messageIds,
+ transactionScope,
+ }: {
+ messageIds: string[];
+ transactionScope?: WorkspaceTransactionScope;
+ }): Promise<void> {
+ if (messageIds.length === 0) {
+ return;
+ }
+
+ const messageRepository = await this.getRepository<MessageWorkspaceEntity>(
+ 'message',
+ transactionScope,
+ );
+ const changedMessages: Pick<
+ MessageWorkspaceEntity,
+ 'id' | 'messageThreadId'
+ >[] = [];
+
+ for (const messageIdChunk of chunk(
+ [...new Set(messageIds)],
+ QUERY_MAX_RECORDS,
+ )) {
+ changedMessages.push(
+ ...(await messageRepository.find({
+ where: { id: In(messageIdChunk) },
+ select: { id: true, messageThreadId: true },
+ })),
+ );
+ }
+ const messageThreadIds = [
+ ...new Set(
+ changedMessages
+ .map(({ messageThreadId }) => messageThreadId)
+ .filter(isDefined),
+ ),
+ ];
+
+ await this.reconcileMessageThreadTargets({
+ messageThreadIds,
+ transactionScope,
+ });
+ }
+
+ public async reconcileMessageThreadTargets({
+ messageThreadIds,
+ transactionScope,
+ }: {
+ messageThreadIds: string[];
+ transactionScope?: WorkspaceTransactionScope;
+ }): Promise<void> {
+ const messageRepository = await this.getRepository<MessageWorkspaceEntity>(
+ 'message',
+ transactionScope,
+ );
+
+ for (const messageThreadIdChunk of chunk(
+ [...new Set(messageThreadIds)],
+ QUERY_MAX_RECORDS,
+ )) {
+ const threadMessages = await messageRepository.find({
+ where: { messageThreadId: In(messageThreadIdChunk) },
+ select: { id: true, messageThreadId: true },
+ });
+ const messageThreadIdByMessageId = new Map<string, string>();
+
+ for (const { id, messageThreadId } of threadMessages) {
+ if (isDefined(messageThreadId)) {
+ messageThreadIdByMessageId.set(id, messageThreadId);
+ }
+ }
+
+ const participantRepository =
+ await this.getRepository<MessageParticipantWorkspaceEntity>(
+ 'messageParticipant',
+ transactionScope,
+ );
+ const messageIds = [...messageThreadIdByMessageId.keys()];
+ const participants: Pick<
+ MessageParticipantWorkspaceEntity,
+ 'messageId' | 'personId'
+ >[] = [];
+
+ for (const messageIdChunk of chunk(messageIds, QUERY_MAX_RECORDS)) {
+ participants.push(
+ ...(await participantRepository.find({
+ where: { messageId: In(messageIdChunk) },
+ select: { messageId: true, personId: true },
+ })),
+ );
+ }
+
+ await this.reconcileTargets({
+ parentIds: messageThreadIdChunk,
+ parentFieldName: 'messageThreadId',
+ participantPersonIdsByParentId: this.groupParticipantPersonIds({
+ participants,
+ getParentId: (participant) =>
+ messageThreadIdByMessageId.get(participant.messageId),
+ }),
+ targetObjectName: 'messageThreadTarget',
+ transactionScope,
+ });
+ }
+ }
+
+ private async reconcileTargets({
+ parentIds,
+ parentFieldName,
+ participantPersonIdsByParentId,
+ targetObjectName,
+ transactionScope,
+ }: {
+ parentIds: string[];
+ parentFieldName: TargetParentFieldName;
+ participantPersonIdsByParentId: Map<string, Set<string>>;
+ targetObjectName: 'calendarEventTarget' | 'messageThreadTarget';
+ transactionScope?: WorkspaceTransactionScope;
+ }): Promise<void> {
+ if (parentIds.length === 0) {
+ return;
+ }
+
+ // Existing workspaces only gain the target junction objects once the
+ // upgrade metadata sync has run; until then reconciliation must no-op so
+ // message and calendar imports keep succeeding. The backfill that follows
+ // the sync covers rows imported during that window.
+ if (
+ !isDefined(getWorkspaceContext().objectIdByNameSingular[targetObjectName])
+ ) {
+ return;
+ }
+
+ const desiredTargets = await this.buildDesiredTargets({
+ parentIds,
+ participantPersonIdsByParentId,
+ transactionScope,
+ });
+ const targetRepository = await this.getRepository<TargetWorkspaceEntity>(
+ targetObjectName,
+ transactionScope,
+ );
+ const existingTargetRows = await targetRepository.find({
+ where: { [parentFieldName]: In(parentIds) },
+ withDeleted: true,
+ });
+ const existingTargets = existingTargetRows
+ .map((target): ExistingTarget | null => {
+ const parentId = target[parentFieldName];
+
+ if (!isDefined(parentId)) {
+ return null;
+ }
+
+ return {
+ ...target,
+ parentId,
+ };
+ })
+ .filter(isDefined);
+ const operations = computeTargetReconciliationOperations({
+ desiredTargets,
+ existingTargets,
+ });
+
+ // Targets per parent are unbounded, so write batches are re-chunked to
+ // stay under the ORM's per-call record cap.
+ for (const targetsToCreateChunk of chunk(
+ operations.targetsToCreate,
+ QUERY_MAX_RECORDS,
+ )) {
+ await targetRepository.insert(
+ targetsToCreateChunk.map(({ parentId, ...target }) => ({
+ ...target,
+ [parentFieldName]: parentId,
+ isAutomaticallyAssigned: true,
+ isManuallyAssigned: false,
+ })),
+ { onConflictDoNothing: true },
+ );
+ }
+
+ for (const targetIdsToMarkAutomaticChunk of chunk(
+ operations.targetsToMarkAutomatic,
+ QUERY_MAX_RECORDS,
+ )) {
+ await targetRepository.updateMany(
+ targetIdsToMarkAutomaticChunk.map((id) => ({
+ criteria: id,
+ partialEntity: { isAutomaticallyAssigned: true },
+ })),
+ );
+ }
+
+ for (const targetIdsToMarkNotAutomaticChunk of chunk(
+ operations.targetsToMarkNotAutomatic,
+ QUERY_MAX_RECORDS,
+ )) {
+ await targetRepository.updateMany(
+ targetIdsToMarkNotAutomaticChunk.map((id) => ({
+ criteria: id,
+ partialEntity: { isAutomaticallyAssigned: false },
+ })),
+ );
+ }
+
+ for (const targetIdsToDeleteChunk of chunk(
+ operations.targetIdsToDelete,
+ QUERY_MAX_RECORDS,
+ )) {
+ await targetRepository.delete({
+ id: In(targetIdsToDeleteChunk),
+ });
+ }
+ }
+
+ private async buildDesiredTargets({
+ parentIds,
+ participantPersonIdsByParentId,
+ transactionScope,
+ }: {
+ parentIds: string[];
+ participantPersonIdsByParentId: Map<string, Set<string>>;
+ transactionScope?: WorkspaceTransactionScope;
+ }): Promise<TargetIdentity[]> {
+ const personIds = [
+ ...new Set(
+ [...participantPersonIdsByParentId.values()].flatMap((ids) => [...ids]),
+ ),
+ ];
+
+ if (personIds.length === 0) {
+ return [];
+ }
+
+ const personRepository = await this.getRepository<PersonWorkspaceEntity>(
+ 'person',
+ transactionScope,
+ );
+ const people = await personRepository.find({
+ where: { id: In(personIds) },
+ select: { id: true, companyId: true },
+ });
+ // find() excludes soft-deleted people, so this set keeps desired targets
+ // aligned with the backfill, which only joins live people.
+ const livePersonIds = new Set(people.map(({ id }) => id));
+ const companyIdByPersonId = new Map(
+ people.map(({ id, companyId }) => [id, companyId]),
+ );
+
+ const opportunityRepository =
+ await this.getRepository<OpportunityWorkspaceEntity>(
+ 'opportunity',
+ transactionScope,
+ );
+ const opportunities = await opportunityRepository.find({
+ where: { pointOfContactId: In(personIds) },
+ select: { id: true, pointOfContactId: true },
+ });
+ const opportunityIdsByPersonId = new Map<string, string[]>();
+
+ for (const opportunity of opportunities) {
+ if (!isDefined(opportunity.pointOfContactId)) {
+ continue;
+ }
+
+ const opportunityIds =
+ opportunityIdsByPersonId.get(opportunity.pointOfContactId) ?? [];
+
+ opportunityIds.push(opportunity.id);
+ opportunityIdsByPersonId.set(
+ opportunity.pointOfContactId,
+ opportunityIds,
+ );
+ }
+
+ return parentIds.flatMap((parentId) =>
+ [...(participantPersonIdsByParentId.get(parentId) ?? [])].flatMap(
+ (personId): TargetIdentity[] => {
+ if (!livePersonIds.has(personId)) {
+ return [];
+ }
+
+ const companyId = companyIdByPersonId.get(personId);
+ const opportunityIds = opportunityIdsByPersonId.get(personId) ?? [];
+
+ return [
+ {
+ parentId,
+ targetPersonId: personId,
+ targetCompanyId: null,
+ targetOpportunityId: null,
+ },
+ ...(isDefined(companyId)
+ ? [
+ {
+ parentId,
+ targetPersonId: null,
+ targetCompanyId: companyId,
+ targetOpportunityId: null,
+ },
+ ]
+ : []),
+ ...opportunityIds.map((opportunityId) => ({
+ parentId,
+ targetPersonId: null,
+ targetCompanyId: null,
+ targetOpportunityId: opportunityId,
+ })),
+ ];
+ },
+ ),
+ );
+ }
+
+ private groupParticipantPersonIds<
+ Participant extends { personId: string | null },
+ >({
+ participants,
+ getParentId,
+ }: {
+ participants: Participant[];
+ getParentId: (participant: Participant) => string | undefined;
+ }): Map<string, Set<string>> {
+ const personIdsByParentId = new Map<string, Set<string>>();
+
+ for (const participant of participants) {
+ const parentId = getParentId(participant);
+ const personId = participant.personId;
+
+ if (!isDefined(parentId) || !isDefined(personId)) {
+ continue;
+ }
+
+ const personIds = personIdsByParentId.get(parentId) ?? new Set<string>();
+
+ personIds.add(personId);
+ personIdsByParentId.set(parentId, personIds);
+ }
+
+ return personIdsByParentId;
+ }
+
+ private async getRepository<T extends ObjectLiteral>(
+ objectMetadataName: string,
+ transactionScope?: WorkspaceTransactionScope,
+ ): Promise<WorkspaceRepository<T>> {
+ return getWorkspaceRepositoryWithOptionalTransaction<T>({
+ objectMetadataName,
+ transactionScope,
+ workspaceOrmManager: this.workspaceOrmManager,
+ rolePermissionConfig: { shouldBypassPermissionChecks: true },
+ });
+ }
+}
diff --git a/packages/twenty-server/src/modules/match-participant/utils/__tests__/compute-target-reconciliation-operations.util.spec.ts b/packages/twenty-server/src/modules/match-participant/utils/__tests__/compute-target-reconciliation-operations.util.spec.ts
new file mode 100644
index 00000000000..dbdd1c76afb
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/utils/__tests__/compute-target-reconciliation-operations.util.spec.ts
@@ -0,0 +1,106 @@
+import { computeTargetReconciliationOperations } from 'src/modules/match-participant/utils/compute-target-reconciliation-operations.util';
+
+const personTarget = {
+ parentId: 'parent-1',
+ targetPersonId: 'person-1',
+ targetCompanyId: null,
+ targetOpportunityId: null,
+};
+
+describe('computeTargetReconciliationOperations', () => {
+ it('creates missing automatic targets', () => {
+ expect(
+ computeTargetReconciliationOperations({
+ desiredTargets: [personTarget],
+ existingTargets: [],
+ }),
+ ).toEqual({
+ targetsToCreate: [personTarget],
+ targetsToMarkAutomatic: [],
+ targetsToMarkNotAutomatic: [],
+ targetIdsToDelete: [],
+ });
+ });
+
+ it('does not recreate an explicitly deleted target', () => {
+ expect(
+ computeTargetReconciliationOperations({
+ desiredTargets: [personTarget],
+ existingTargets: [
+ {
+ ...personTarget,
+ id: 'target-1',
+ deletedAt: new Date('2026-01-01'),
+ isAutomaticallyAssigned: true,
+ isManuallyAssigned: false,
+ },
+ ],
+ }),
+ ).toEqual({
+ targetsToCreate: [],
+ targetsToMarkAutomatic: [],
+ targetsToMarkNotAutomatic: [],
+ targetIdsToDelete: [],
+ });
+ });
+
+ it('adds automatic provenance to an existing manual target', () => {
+ expect(
+ computeTargetReconciliationOperations({
+ desiredTargets: [personTarget],
+ existingTargets: [
+ {
+ ...personTarget,
+ id: 'target-1',
+ deletedAt: null,
+ isAutomaticallyAssigned: false,
+ isManuallyAssigned: true,
+ },
+ ],
+ }).targetsToMarkAutomatic,
+ ).toEqual(['target-1']);
+ });
+
+ it('keeps a manual target when its automatic reason disappears', () => {
+ expect(
+ computeTargetReconciliationOperations({
+ desiredTargets: [],
+ existingTargets: [
+ {
+ ...personTarget,
+ id: 'target-1',
+ deletedAt: null,
+ isAutomaticallyAssigned: true,
+ isManuallyAssigned: true,
+ },
+ ],
+ }).targetsToMarkNotAutomatic,
+ ).toEqual(['target-1']);
+ });
+
+ it('hard-deletes an obsolete automatic-only target', () => {
+ expect(
+ computeTargetReconciliationOperations({
+ desiredTargets: [],
+ existingTargets: [
+ {
+ ...personTarget,
+ id: 'target-1',
+ deletedAt: null,
+ isAutomaticallyAssigned: true,
+ isManuallyAssigned: false,
+ },
+ ],
+ }).targetIdsToDelete,
+ ).toEqual(['target-1']);
+ });
+
+ it('deduplicates desired targets', () => {
+ expect(
+ computeTargetReconciliationOperations({
+ desiredTargets: [personTarget, personTarget],
+ existingTargets: [],
+ }).targetsToCreate,
+ ).toEqual([personTarget]);
+ });
+});
diff --git a/packages/twenty-server/src/modules/match-participant/utils/compute-target-reconciliation-operations.util.ts b/packages/twenty-server/src/modules/match-participant/utils/compute-target-reconciliation-operations.util.ts
new file mode 100644
index 00000000000..6499d267393
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/utils/compute-target-reconciliation-operations.util.ts
@@ -0,0 +1,84 @@
+import { isDefined } from 'twenty-shared/utils';
+
+export type TargetIdentity = {
+ parentId: string;
+ targetPersonId: string | null;
+ targetCompanyId: string | null;
+ targetOpportunityId: string | null;
+};
+
+export type ExistingTarget = TargetIdentity & {
+ id: string;
+ deletedAt: Date | string | null;
+ isAutomaticallyAssigned: boolean;
+ isManuallyAssigned: boolean;
+};
+
+type TargetReconciliationOperations = {
+ targetsToCreate: TargetIdentity[];
+ targetsToMarkAutomatic: string[];
+ targetsToMarkNotAutomatic: string[];
+ targetIdsToDelete: string[];
+};
+
+const getTargetIdentityKey = ({
+ parentId,
+ targetPersonId,
+ targetCompanyId,
+ targetOpportunityId,
+}: TargetIdentity) =>
+ [
+ parentId,
+ targetPersonId ?? '',
+ targetCompanyId ?? '',
+ targetOpportunityId ?? '',
+ ].join(':');
+
+export const computeTargetReconciliationOperations = ({
+ desiredTargets,
+ existingTargets,
+}: {
+ desiredTargets: TargetIdentity[];
+ existingTargets: ExistingTarget[];
+}): TargetReconciliationOperations => {
+ const desiredTargetByKey = new Map(
+ desiredTargets.map((target) => [getTargetIdentityKey(target), target]),
+ );
+ const liveTargetByKey = new Map(
+ existingTargets
+ .filter((target) => !isDefined(target.deletedAt))
+ .map((target) => [getTargetIdentityKey(target), target]),
+ );
+ const tombstoneKeys = new Set(
+ existingTargets
+ .filter((target) => isDefined(target.deletedAt))
+ .map(getTargetIdentityKey),
+ );
+
+ const targetsToCreate = [...desiredTargetByKey.entries()]
+ .filter(([key]) => !liveTargetByKey.has(key) && !tombstoneKeys.has(key))
+ .map(([, target]) => target);
+
+ const targetsToMarkAutomatic = [...desiredTargetByKey.keys()]
+ .map((key) => liveTargetByKey.get(key))
+ .filter(isDefined)
+ .filter((target) => !target.isAutomaticallyAssigned)
+ .map((target) => target.id);
+
+ const obsoleteLiveTargets = [...liveTargetByKey.entries()]
+ .filter(([key]) => !desiredTargetByKey.has(key))
+ .map(([, target]) => target);
+
+ return {
+ targetsToCreate,
+ targetsToMarkAutomatic,
+ targetsToMarkNotAutomatic: obsoleteLiveTargets
+ .filter(
+ (target) => target.isAutomaticallyAssigned && target.isManuallyAssigned,
+ )
+ .map((target) => target.id),
+ targetIdsToDelete: obsoleteLiveTargets
+ .filter((target) => !target.isManuallyAssigned)
+ .map((target) => target.id),
+ };
+};
diff --git a/packages/twenty-server/src/modules/messaging/message-cleaner/messaging-message-cleaner.module.ts b/packages/twenty-server/src/modules/messaging/message-cleaner/messaging-message-cleaner.module.ts
index 6f7836eaea0..192934b11cd 100644
--- a/packages/twenty-server/src/modules/messaging/message-cleaner/messaging-message-cleaner.module.ts
+++ b/packages/twenty-server/src/modules/messaging/message-cleaner/messaging-message-cleaner.module.ts
@@ -6,6 +6,7 @@ import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import { MessagingCommonModule } from 'src/modules/messaging/common/messaging-common.module';
+import { MatchParticipantModule } from 'src/modules/match-participant/match-participant.module';
import { MessagingMessageCleanerRemoveOrphansCommand } from 'src/modules/messaging/message-cleaner/commands/messaging-message-clearner-remove-orphans.command';
import { MessagingResetChannelCommand } from 'src/modules/messaging/message-cleaner/commands/messaging-reset-channel.command';
import { MessagingConnectedAccountDeletionCleanupJob } from 'src/modules/messaging/message-cleaner/jobs/messaging-connected-account-deletion-cleanup.job';
@@ -20,6 +21,7 @@ import { MessagingMessageCleanerService } from 'src/modules/messaging/message-cl
TypeOrmModule.forFeature([WorkspaceEntity, MessageChannelEntity]),
FeatureFlagModule,
MessagingCommonModule,
+ MatchParticipantModule,
WorkspaceIteratorModule,
],
providers: [
diff --git a/packages/twenty-server/src/modules/messaging/message-cleaner/services/messaging-message-cleaner.service.ts b/packages/twenty-server/src/modules/messaging/message-cleaner/services/messaging-message-cleaner.service.ts
index 3e227970654..010d9707c23 100644
--- a/packages/twenty-server/src/modules/messaging/message-cleaner/services/messaging-message-cleaner.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-cleaner/services/messaging-message-cleaner.service.ts
@@ -7,6 +7,7 @@ import { In, MoreThan } from 'typeorm';
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 { ParticipantTargetReconciliationService } from 'src/modules/match-participant/participant-target-reconciliation.service';
import { type MessageChannelMessageAssociationWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel-message-association.workspace-entity';
import { type MessageThreadWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-thread.workspace-entity';
import { type MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
@@ -16,7 +17,10 @@ const ORPHAN_CLEANUP_PAGE_SIZE = 500;
@Injectable()
export class MessagingMessageCleanerService {
private readonly logger = new Logger(MessagingMessageCleanerService.name);
- constructor(private readonly workspaceOrmManager: WorkspaceOrmManager) {}
+ constructor(
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly participantTargetReconciliationService: ParticipantTargetReconciliationService,
+ ) {}
async deleteMessagesChannelMessageAssociationsAndRelatedOrphans({
workspaceId,
@@ -107,11 +111,18 @@ export class MessagingMessageCleanerService {
this.findReferencedThreadIds(messageRepository, threadIds),
);
- if (orphanThreadIds.length <= 0) {
- continue;
+ if (orphanThreadIds.length > 0) {
+ await messageThreadRepository.delete(orphanThreadIds);
}
- await messageThreadRepository.delete(orphanThreadIds);
+ await this.participantTargetReconciliationService.reconcileMessageThreadTargets(
+ {
+ messageThreadIds: candidateThreadIds.filter(
+ (threadId) => !orphanThreadIds.includes(threadId),
+ ),
+ transactionScope,
+ },
+ );
}
},
);
@@ -196,7 +207,33 @@ export class MessagingMessageCleanerService {
return page.map(({ id }) => id);
},
- (ids) => messageRepository.delete(ids),
+ async (ids) => {
+ const messagesToDelete = await messageRepository.find({
+ where: { id: In(ids) },
+ select: { messageThreadId: true },
+ });
+ const candidateThreadIds = [
+ ...new Set(
+ messagesToDelete
+ .map(({ messageThreadId }) => messageThreadId)
+ .filter(isDefined),
+ ),
+ ];
+
+ await messageRepository.delete(ids);
+
+ const survivingThreadIds = await this.findReferencedThreadIds(
+ messageRepository,
+ candidateThreadIds,
+ );
+
+ await this.participantTargetReconciliationService.reconcileMessageThreadTargets(
+ {
+ messageThreadIds: survivingThreadIds,
+ transactionScope,
+ },
+ );
+ },
(pageIds) =>
this.filterOrphans(pageIds, (ids) =>
this.findReferencedMessageIds(
@@ -247,6 +284,10 @@ export class MessagingMessageCleanerService {
messageRepository: WorkspaceRepository<MessageWorkspaceEntity>,
threadIds: string[],
): Promise<string[]> {
+ if (threadIds.length === 0) {
+ return [];
+ }
+
const messages = await messageRepository.find({
where: { messageThreadId: In(threadIds) },
select: { messageThreadId: true },
diff --git a/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts b/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts
index a894e20536f..1217657d835 100644
--- a/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts
@@ -71,6 +71,9 @@ export class MessagingMessageParticipantService {
await this.matchParticipantService.matchParticipants({
participants: createdParticipants,
+ sourceRecordIds: [
+ ...new Set(participants.map(({ messageId }) => messageId)),
+ ],
objectMetadataName: 'messageParticipant',
matchWith: 'workspaceMemberAndPerson',
transactionScope,