The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Keep non-email participant links when a person's emails change (#28694)
Félix Malfaitbc3096f1a255
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/jobs/calendar-event-participant-match-participant.job.ts b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/jobs/calendar-event-participant-match-participant.job.tsindex f5613a5e577..de5b9092595 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/jobs/calendar-event-participant-match-participant.job.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/jobs/calendar-event-participant-match-participant.job.ts@@ -13,7 +13,6 @@ import { MatchParticipantService } from 'src/modules/match-participant/match-parexport type CalendarEventParticipantMatchParticipantJobData = {workspaceId: string;participantMatching: {- personIds: string[];personEmails: string[];workspaceMemberIds: string[];};@@ -46,10 +45,7 @@ export class CalendarEventParticipantMatchParticipantJob {return;}- if (- participantMatching.personIds.length > 0 ||- participantMatching.personEmails.length > 0- ) {+ if (participantMatching.personEmails.length > 0) {await this.matchParticipantService.matchParticipantsForPeople({objectMetadataName: 'calendarEventParticipant',participantMatching,diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/listeners/calendar-event-participant-person.listener.ts b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/listeners/calendar-event-participant-person.listener.tsindex a23f19cb92c..5a358f6735b 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/listeners/calendar-event-participant-person.listener.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/listeners/calendar-event-participant-person.listener.ts@@ -42,9 +42,6 @@ export class CalendarEventParticipantPersonListener {return;}- const personIds = personWithEmails.map(- (eventPayload) => eventPayload.recordId,- );const personEmails = personWithEmails.flatMap((eventPayload) =>getPersonEmails(eventPayload.properties.after.emails),);@@ -54,7 +51,6 @@ export class CalendarEventParticipantPersonListener {{workspaceId: payload.workspaceId,participantMatching: {- personIds,personEmails,workspaceMemberIds: [],},@@ -79,19 +75,16 @@ export class CalendarEventParticipantPersonListener {return;}- const personIds = personWithUpdatedEmails.map(- (eventPayload) => eventPayload.recordId,- );- const personEmails = personWithUpdatedEmails.flatMap((eventPayload) =>- getPersonEmails(eventPayload.properties.after.emails),- );+ const personEmails = personWithUpdatedEmails.flatMap((eventPayload) => [+ ...getPersonEmails(eventPayload.properties.before.emails),+ ...getPersonEmails(eventPayload.properties.after.emails),+ ]);await this.messageQueueService.add<CalendarEventParticipantMatchParticipantJobData>(CalendarEventParticipantMatchParticipantJob.name,{workspaceId: payload.workspaceId,participantMatching: {- personIds,personEmails,workspaceMemberIds: [],},@@ -118,7 +111,6 @@ export class CalendarEventParticipantPersonListener {{workspaceId: payload.workspaceId,participantMatching: {- personIds: [],personEmails,workspaceMemberIds: [],},diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/listeners/calendar-event-participant-workspace-member.listener.ts b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/listeners/calendar-event-participant-workspace-member.listener.tsindex 879dbd77537..73242bfa05f 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/listeners/calendar-event-participant-workspace-member.listener.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/listeners/calendar-event-participant-workspace-member.listener.ts@@ -41,7 +41,6 @@ export class CalendarEventParticipantWorkspaceMemberListener {{workspaceId: payload.workspaceId,participantMatching: {- personIds: [],personEmails: [],workspaceMemberIds: [eventPayload.recordId],},@@ -68,7 +67,6 @@ export class CalendarEventParticipantWorkspaceMemberListener {{workspaceId: payload.workspaceId,participantMatching: {- personIds: [],personEmails: [],workspaceMemberIds: [eventPayload.recordId],},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.tsindex 6de776a797c..867e6e64cbe 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,12 +1,14 @@import { Module } from '@nestjs/common';+import { TypeOrmModule } from '@nestjs/typeorm';+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';import { ReconcilePersonCompanyTargetsJob } from 'src/modules/match-participant/jobs/reconcile-person-company-targets.job';import { ParticipantTargetPersonListener } from 'src/modules/match-participant/listeners/participant-target-person.listener';import { MatchParticipantService } from 'src/modules/match-participant/match-participant.service';import { ParticipantTargetReconciliationService } from 'src/modules/match-participant/participant-target-reconciliation.service';@Module({- imports: [],+ imports: [TypeOrmModule.forFeature([MessageChannelEntity])],providers: [MatchParticipantService,ParticipantTargetReconciliationService,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.tsindex 576b3eeed69..c55517a622d 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@@ -1,9 +1,12 @@import { Injectable } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';import chunk from 'lodash.chunk';-import { isDefined } from 'twenty-shared/utils';-import { Any, In } from 'typeorm';+import { MessageChannelType } from 'twenty-shared/types';+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';+import { Any, In, Repository } from 'typeorm';+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';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';@@ -12,6 +15,7 @@ import { type CalendarEventParticipantWorkspaceEntity } from 'src/modules/calendimport { 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 MessageChannelMessageAssociationWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel-message-association.workspace-entity';import { type MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';import { type PersonWorkspaceEntity } from 'src/modules/person/standard-objects/person.workspace-entity';import { WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';@@ -33,7 +37,6 @@ type MatchParticipantsForWorkspaceMembersArgs = {type MatchParticipantsForPeopleArgs = {participantMatching: {- personIds: string[];personEmails: string[];};objectMetadataName: ObjectMetadataName;@@ -71,6 +74,8 @@ export class MatchParticipantService<constructor(private readonly workspaceOrmManager: WorkspaceOrmManager,private readonly participantTargetReconciliationService: ParticipantTargetReconciliationService,+ @InjectRepository(MessageChannelEntity)+ private readonly messageChannelRepository: Repository<MessageChannelEntity>,) {}private getParticipantRepository({@@ -293,47 +298,36 @@ export class MatchParticipantService<transactionScope,});- let participantsMatchingPersonEmails: ParticipantWorkspaceEntity[] =- [];- let participantsMatchingPersonId: 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 (!isNonEmptyArray(participantMatching.personEmails)) {+ return;}- const uniqueParticipants = [- ...new Set([- ...participantsMatchingPersonId,- ...participantsMatchingPersonEmails,- ]),- ];-- const tobeRematchedParticipants = uniqueParticipants.map(- (participant) => {- return {- ...participant,- personId: null,- };- },- );+ // emails before and after the change pick candidates, so links made any other way are left alone+ const participantsWithEmailHandle = await participantRepository+ .createQueryBuilder('participant')+ .where('LOWER("participant"."handle") = ANY(:emails)', {+ emails: [+ ...new Set(+ participantMatching.personEmails.map((email) =>+ email.toLowerCase(),+ ),+ ),+ ],+ })+ .getMany<ParticipantWorkspaceEntity>();++ const participantsToRematch =+ await this.withoutAppChannelParticipants({+ participants: participantsWithEmailHandle,+ objectMetadataName,+ workspaceId,+ transactionScope,+ });await this.matchParticipants({matchWith: 'personOnly',- participants: tobeRematchedParticipants,- sourceRecordIds: this.getSourceRecordIds(tobeRematchedParticipants),+ participants: participantsToRematch,+ sourceRecordIds: this.getSourceRecordIds(participantsToRematch),objectMetadataName,transactionScope,});@@ -342,13 +336,73 @@ export class MatchParticipantService<}, authContext);}+ // apps link their own participants, even ones whose handle looks like an email+ private async withoutAppChannelParticipants({+ participants,+ objectMetadataName,+ workspaceId,+ transactionScope,+ }: {+ participants: ParticipantWorkspaceEntity[];+ objectMetadataName: ObjectMetadataName;+ workspaceId: string;+ transactionScope: WorkspaceTransactionScope;+ }): Promise<ParticipantWorkspaceEntity[]> {+ if (+ objectMetadataName !== 'messageParticipant' ||+ !isNonEmptyArray(participants)+ ) {+ return participants;+ }++ const appMessageChannels = await this.messageChannelRepository.find({+ where: { workspaceId, type: MessageChannelType.APP },+ select: { id: true },+ });++ if (!isNonEmptyArray(appMessageChannels)) {+ return participants;+ }++ const appChannelAssociations =+ await getWorkspaceRepositoryWithOptionalTransaction<MessageChannelMessageAssociationWorkspaceEntity>(+ {+ objectMetadataName: 'messageChannelMessageAssociation',+ transactionScope,+ workspaceOrmManager: this.workspaceOrmManager,+ rolePermissionConfig: { shouldBypassPermissionChecks: true },+ },+ ).find({+ where: {+ messageId: Any([...new Set(this.getSourceRecordIds(participants))]),+ messageChannelId: Any(+ appMessageChannels.map((messageChannel) => messageChannel.id),+ ),+ },+ select: { messageId: true },+ });++ const appChannelMessageIds = new Set(+ appChannelAssociations.map((association) => association.messageId),+ );++ return participants.filter(+ (participant) =>+ !appChannelMessageIds.has(this.getSourceRecordId(participant)),+ );+ }+private getSourceRecordIds(participants: ParticipantWorkspaceEntity[],): string[] {return participants.map((participant) =>- 'messageId' in participant- ? participant.messageId- : participant.calendarEventId,+ this.getSourceRecordId(participant),);}++ private getSourceRecordId(participant: ParticipantWorkspaceEntity): string {+ return 'messageId' in participant+ ? participant.messageId+ : participant.calendarEventId;+ }}diff --git a/packages/twenty-server/src/modules/messaging/message-participant-manager/jobs/message-participant-match-participant.job.ts b/packages/twenty-server/src/modules/messaging/message-participant-manager/jobs/message-participant-match-participant.job.tsindex 73558a42d75..15b1c5c1a84 100644--- a/packages/twenty-server/src/modules/messaging/message-participant-manager/jobs/message-participant-match-participant.job.ts+++ b/packages/twenty-server/src/modules/messaging/message-participant-manager/jobs/message-participant-match-participant.job.ts@@ -9,7 +9,6 @@ import { type MessageParticipantWorkspaceEntity } from 'src/modules/messaging/coexport type MessageParticipantMatchParticipantJobData = {workspaceId: string;participantMatching: {- personIds: string[];personEmails: string[];workspaceMemberIds: string[];};@@ -28,10 +27,7 @@ export class MessageParticipantMatchParticipantJob {async handle(data: MessageParticipantMatchParticipantJobData): Promise<void> {const { participantMatching, workspaceId } = data;- if (- participantMatching.personIds.length > 0 ||- participantMatching.personEmails.length > 0- ) {+ if (participantMatching.personEmails.length > 0) {await this.matchParticipantService.matchParticipantsForPeople({participantMatching,objectMetadataName: 'messageParticipant',diff --git a/packages/twenty-server/src/modules/messaging/message-participant-manager/listeners/message-participant-person.listener.ts b/packages/twenty-server/src/modules/messaging/message-participant-manager/listeners/message-participant-person.listener.tsindex 9cb5f27734c..3367b39b37b 100644--- a/packages/twenty-server/src/modules/messaging/message-participant-manager/listeners/message-participant-person.listener.ts+++ b/packages/twenty-server/src/modules/messaging/message-participant-manager/listeners/message-participant-person.listener.ts@@ -42,9 +42,6 @@ export class MessageParticipantPersonListener {return;}- const personIds = personWithEmails.map(- (eventPayload) => eventPayload.recordId,- );const personEmails = personWithEmails.flatMap((eventPayload) =>getPersonEmails(eventPayload.properties.after.emails),);@@ -54,7 +51,6 @@ export class MessageParticipantPersonListener {{workspaceId: payload.workspaceId,participantMatching: {- personIds,personEmails,workspaceMemberIds: [],},@@ -79,19 +75,16 @@ export class MessageParticipantPersonListener {return;}- const personIds = personWithUpdatedEmails.map(- (eventPayload) => eventPayload.recordId,- );- const personEmails = personWithUpdatedEmails.flatMap((eventPayload) =>- getPersonEmails(eventPayload.properties.after.emails),- );+ const personEmails = personWithUpdatedEmails.flatMap((eventPayload) => [+ ...getPersonEmails(eventPayload.properties.before.emails),+ ...getPersonEmails(eventPayload.properties.after.emails),+ ]);await this.messageQueueService.add<MessageParticipantMatchParticipantJobData>(MessageParticipantMatchParticipantJob.name,{workspaceId: payload.workspaceId,participantMatching: {- personIds,personEmails,workspaceMemberIds: [],},@@ -118,7 +111,6 @@ export class MessageParticipantPersonListener {{workspaceId: payload.workspaceId,participantMatching: {- personIds: [],personEmails,workspaceMemberIds: [],},diff --git a/packages/twenty-server/src/modules/messaging/message-participant-manager/listeners/message-participant-workspace-member.listener.ts b/packages/twenty-server/src/modules/messaging/message-participant-manager/listeners/message-participant-workspace-member.listener.tsindex d81c927aa62..888b6e416da 100644--- a/packages/twenty-server/src/modules/messaging/message-participant-manager/listeners/message-participant-workspace-member.listener.ts+++ b/packages/twenty-server/src/modules/messaging/message-participant-manager/listeners/message-participant-workspace-member.listener.ts@@ -58,7 +58,6 @@ export class MessageParticipantWorkspaceMemberListener {{workspaceId: payload.workspaceId,participantMatching: {- personIds: [],personEmails: [],workspaceMemberIds: [eventPayload.recordId],},@@ -85,7 +84,6 @@ export class MessageParticipantWorkspaceMemberListener {{workspaceId: payload.workspaceId,participantMatching: {- personIds: [],personEmails: [],workspaceMemberIds: [eventPayload.recordId],},diff --git a/packages/twenty-server/test/integration/graphql/suites/person-participant-rematch.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/person-participant-rematch.integration-spec.tsnew file mode 100644index 00000000000..f2af2316528--- /dev/null+++ b/packages/twenty-server/test/integration/graphql/suites/person-participant-rematch.integration-spec.ts@@ -0,0 +1,176 @@+import { randomUUID } from 'crypto';++import { createOneOperation } from 'test/integration/graphql/utils/create-one-operation.util';+import { destroyOneOperationFactory } from 'test/integration/graphql/utils/destroy-one-operation-factory.util';+import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';+import { updateOneOperationFactory } from 'test/integration/graphql/utils/update-one-operation-factory.util';+import { waitForAllJobsToFinish } from 'test/integration/utils/wait-for-all-jobs-to-finish.util';++type Participant = {+ id: string;+ handle: string;+ personId: string | null;+};++describe('participant rematch when a person changes', () => {+ let personId: string;+ let messageThreadId: string;+ let messageId: string;+ const fixtures: { objectName: string; id: string }[] = [];++ const create = async ({+ objectName,+ input,+ }: {+ objectName: string;+ input: object;+ }) => {+ const id = randomUUID();+ const response = await createOneOperation({+ objectMetadataSingularName: objectName,+ input: { id, ...input },+ });++ expect(response.errors).toBeUndefined();+ fixtures.push({ objectName, id });++ return id;+ };++ const updatePersonEmails = async (emails: {+ primaryEmail: string;+ additionalEmails: string[];+ }) => {+ const response = await makeGraphqlApiRequest(+ updateOneOperationFactory({+ objectMetadataSingularName: 'person',+ recordId: personId,+ gqlFields: 'id',+ data: { emails },+ }),+ );++ expect(response.body.errors).toBeUndefined();+ await waitForAllJobsToFinish();+ };++ const findParticipantPersonIdByHandle = async (): Promise<+ Record<string, string | null>+ > => {+ const response = await makeGraphqlApiRequest(+ findManyOperationFactory({+ objectMetadataSingularName: 'messageParticipant',+ objectMetadataPluralName: 'messageParticipants',+ filter: { messageId: { eq: messageId } },+ gqlFields: 'id handle personId',+ }),+ );++ expect(response.body.errors).toBeUndefined();++ return Object.fromEntries(+ response.body.data.messageParticipants.edges.map(+ ({ node }: { node: Participant }) => [node.handle, node.personId],+ ),+ );+ };++ beforeEach(async () => {+ personId = await create({+ objectName: 'person',+ input: {+ name: { firstName: 'Ada' },+ emails: { primaryEmail: '[email protected]', additionalEmails: [] },+ },+ });+ messageThreadId = await create({ objectName: 'messageThread', input: {} });+ messageId = await create({+ objectName: 'message',+ input: {+ messageThreadId,+ subject: 'Rematch',+ receivedAt: '2026-01-01T12:00:00.000Z',+ },+ });+ await create({+ objectName: 'messageParticipant',+ input: {+ messageId,+ personId,+ handle: '[email protected]',+ role: 'FROM',+ },+ });+ await create({+ objectName: 'messageParticipant',+ input: {+ messageId,+ personId,+ handle: 'urn:li:person:ada',+ role: 'TO',+ },+ });+ await waitForAllJobsToFinish();+ });++ afterEach(async () => {+ const targetsResponse = await makeGraphqlApiRequest(+ findManyOperationFactory({+ objectMetadataSingularName: 'messageThreadTarget',+ objectMetadataPluralName: 'messageThreadTargets',+ filter: { messageThreadId: { eq: messageThreadId } },+ gqlFields: 'id',+ }),+ );++ const targetEdges: { node: { id: string } }[] =+ targetsResponse.body.data.messageThreadTargets.edges;++ for (const { node } of targetEdges) {+ if (!fixtures.some(({ id }) => id === node.id)) {+ fixtures.push({ objectName: 'messageThreadTarget', id: node.id });+ }+ }++ for (const { objectName, id } of fixtures.splice(0).reverse()) {+ const response = await makeGraphqlApiRequest(+ destroyOneOperationFactory({+ objectMetadataSingularName: objectName,+ recordId: id,+ gqlFields: 'id',+ }),+ );++ expect(response.body.errors).toBeUndefined();+ }+ });++ it('keeps a non-email participant linked when the person is created and when their emails change', async () => {+ expect(await findParticipantPersonIdByHandle()).toEqual({+ '[email protected]': personId,+ 'urn:li:person:ada': personId,+ });++ await updatePersonEmails({+ primaryEmail: '[email protected]',+ additionalEmails: ['[email protected]'],+ });++ expect((await findParticipantPersonIdByHandle())['urn:li:person:ada']).toBe(+ personId,+ );+ });++ it('releases an email participant, whatever its case, when the person loses that email', async () => {+ await updatePersonEmails({+ primaryEmail: '[email protected]',+ additionalEmails: [],+ });++ expect(await findParticipantPersonIdByHandle()).toEqual({+ '[email protected]': null,+ 'urn:li:person:ada': personId,+ });+ });+});