Skip to content

The open alternative to Salesforce, designed for AI.

Match app channel participants on a declared person field (#28696)

Félix Malfait9e2bc2ea1963
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index c37db8b83fd..88ed3f5bf0c 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -1427,6 +1427,7 @@ input CreateAppMessageChannelInput {
connectedAccountId: UUID!
displayName: String
handle: String!
+ participantHandleFieldUniversalIdentifier: UUID
visibility: MessageChannelVisibility!
}
@@ -2930,6 +2931,7 @@ type MessageChannel {
isContactAutoCreationEnabled: Boolean!
isSyncEnabled: Boolean!
messageFolderImportPolicy: MessageFolderImportPolicy!
+ participantHandleFieldUniversalIdentifier: UUID
pendingGroupEmailsAction: MessageChannelPendingGroupEmailsAction!
syncStage: MessageChannelSyncStage!
syncStageStartedAt: DateTime
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 7bdaf72d917..a0fa1d3ce46 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -2045,6 +2045,7 @@ export interface MessageChannel {
isContactAutoCreationEnabled: Scalars['Boolean']
isSyncEnabled: Scalars['Boolean']
messageFolderImportPolicy: MessageFolderImportPolicy
+ participantHandleFieldUniversalIdentifier?: Scalars['UUID']
pendingGroupEmailsAction: MessageChannelPendingGroupEmailsAction
syncStage: MessageChannelSyncStage
syncStageStartedAt?: Scalars['DateTime']
@@ -5480,7 +5481,7 @@ export interface CreateAgentInput {description?: (Scalars['String'] | null),icon
export interface CreateApiKeyInput {expiresAt: Scalars['String'],name: Scalars['String'],revokedAt?: (Scalars['String'] | null),roleId: Scalars['UUID']}
-export interface CreateAppMessageChannelInput {connectedAccountId: Scalars['UUID'],displayName?: (Scalars['String'] | null),handle: Scalars['String'],visibility: MessageChannelVisibility}
+export interface CreateAppMessageChannelInput {connectedAccountId: Scalars['UUID'],displayName?: (Scalars['String'] | null),handle: Scalars['String'],participantHandleFieldUniversalIdentifier?: (Scalars['UUID'] | null),visibility: MessageChannelVisibility}
export interface CreateApplicationFileUploadsResultGenqlSelection{
errors?: ApplicationFileUploadErrorGenqlSelection
@@ -6485,6 +6486,7 @@ export interface MessageChannelGenqlSelection{
isContactAutoCreationEnabled?: boolean | number
isSyncEnabled?: boolean | number
messageFolderImportPolicy?: boolean | number
+ participantHandleFieldUniversalIdentifier?: boolean | number
pendingGroupEmailsAction?: boolean | number
syncStage?: boolean | number
syncStageStartedAt?: boolean | number
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 73f051697ae..5a256623edb 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -3119,6 +3119,9 @@ export default {
"handle": [
1
],
+ "participantHandleFieldUniversalIdentifier": [
+ 516
+ ],
"visibility": [
343
],
@@ -6091,6 +6094,9 @@ export default {
"messageFolderImportPolicy": [
345
],
+ "participantHandleFieldUniversalIdentifier": [
+ 516
+ ],
"pendingGroupEmailsAction": [
339
],
diff --git a/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdx b/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdx
index 0f5e6b9cdea..25929003a97 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdx
@@ -128,9 +128,37 @@ A batch is all-or-nothing, and repeating one `externalId` inside a single batch
### Linking participants to People
-Twenty matches email participants to People by email address. That cannot match a LinkedIn URN or a phone number, so **an app must say who a participant is** — an unlinked thread does not appear on anyone's record page.
+An unlinked participant pulls the conversation onto no record page, so every participant should end up linked to a Person. There are two ways to get there: let Twenty match handles against a person field, or resolve the person yourself.
-Pass `personId` alongside the handle:
+#### Match on a person field
+
+When the provider's handles are values people already store on a contact — a phone number, a profile URL, a username — declare that field when you create the channel:
+
+```ts
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+
+await createMessageChannel({
+ connectedAccountId: connection.id,
+ handle: '+33612345678',
+ visibility: MessageChannelVisibility.METADATA,
+ participantHandleFieldUniversalIdentifier:
+ STANDARD_OBJECTS.person.fields.phones.universalIdentifier,
+});
+```
+
+Any active person field of type emails, phones, links or text works, including one your app added with [`defineField`](/developers/extend/apps/data/extending-objects) (an Instagram username, say). Twenty then:
+
+- **stores handles in the field's canonical form**: phones as `+` and digits (send E.164 numbers), links lowercased without scheme, `www`, fragment or trailing slash, with the query string kept as sent since it can identify the profile (`linkedin.com/in/ada`, `facebook.com/profile.php?id=111`), emails and text lowercased. The channel's own handle is stored the same way, and a handle with no usable value is rejected.
+- **links each participant you leave unlinked** to the person whose field holds that value, primary values first, then the oldest person.
+- **re-matches when people change**: adding the value to a person links their past conversations, and removing it releases them.
+
+A `personId` you pass still wins, including when someone else later gains or loses that value. The field is set once, at creation; if it is deleted or deactivated, ingestion into the channel is refused rather than storing handles Twenty can no longer normalize.
+
+Pick handles that are both stable and stored on contacts. For LinkedIn, that means the public profile URL rather than the member URN; keep your own mapping if you need the URN to call the provider.
+
+#### Resolve the person yourself
+
+Without a declared field, **your app must say who a participant is**. Pass `personId` alongside the handle:
```ts
participants: [
@@ -211,5 +239,5 @@ Deleting a channel deletes the messages ingested through it, and any thread left
- **It is not polled.** Twenty's import pipeline polls mailbox providers on a cron. App channels are push-only: nothing fetches on your behalf, so your app is responsible for getting messages in, via a webhook route or a cron logic function.
- **It does not send.** Outbound delivery is not yet routed to apps; a reply composed in Twenty cannot reach your provider. Until it is, link out to the provider's own UI for replies.
-- **It does not resolve contacts.** Twenty matches email participants to People by email address, which cannot match a LinkedIn URN, so app channels [link participants explicitly at ingestion](#linking-participants-to-people) instead.
+- **It only resolves contacts through a declared field.** Without one, Twenty cannot tell who a LinkedIn URN belongs to, so app channels [link participants explicitly at ingestion](#resolve-the-person-yourself).
- **It does not create contacts.** Twenty's auto-creation derives people and companies from email domains, which is meaningless for most providers, so it is off for app channels. Create the Person yourself, then pass its `personId`.
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 63c1d6d9abc..190c9e2a61c 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -1548,6 +1548,7 @@ export type CreateAppMessageChannelInput = {
connectedAccountId: Scalars['UUID']['input'];
displayName?: InputMaybe<Scalars['String']['input']>;
handle: Scalars['String']['input'];
+ participantHandleFieldUniversalIdentifier?: InputMaybe<Scalars['UUID']['input']>;
visibility: MessageChannelVisibility;
};
@@ -3103,6 +3104,7 @@ export type MessageChannel = {
isContactAutoCreationEnabled: Scalars['Boolean']['output'];
isSyncEnabled: Scalars['Boolean']['output'];
messageFolderImportPolicy: MessageFolderImportPolicy;
+ participantHandleFieldUniversalIdentifier?: Maybe<Scalars['UUID']['output']>;
pendingGroupEmailsAction: MessageChannelPendingGroupEmailsAction;
syncStage: MessageChannelSyncStage;
syncStageStartedAt?: Maybe<Scalars['DateTime']['output']>;
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/create-message-channel.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/create-message-channel.ts
index d5a22f5cfa0..91abe1e618f 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/messaging/create-message-channel.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/create-message-channel.ts
@@ -20,6 +20,8 @@ export type CreateMessageChannelInput = {
// Required: decides whether one member's conversations are readable by the whole workspace, and only the app
// knows how private its messages are ('METADATA' for personal inboxes, 'SHARE_EVERYTHING' for shared ones)
visibility: MessageChannelVisibility;
+ // Person field to match participant handles against (handles are then stored in its canonical form); set once
+ participantHandleFieldUniversalIdentifier?: string;
};
export const createMessageChannel = async (
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/message-channel-fields.constant.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/message-channel-fields.constant.ts
index 45ecca9a91b..876b16a1f3e 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/messaging/message-channel-fields.constant.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/message-channel-fields.constant.ts
@@ -6,4 +6,5 @@ export const APP_MESSAGE_CHANNEL_SELECTION = `
visibility
connectedAccountId
isSyncEnabled
+ participantHandleFieldUniversalIdentifier
`;
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-52/2-52-instance-command-fast-1792907887530-add-participant-handle-field-to-message-channel.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-52/2-52-instance-command-fast-1792907887530-add-participant-handle-field-to-message-channel.ts
new file mode 100644
index 00000000000..aad16474258
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-52/2-52-instance-command-fast-1792907887530-add-participant-handle-field-to-message-channel.ts
@@ -0,0 +1,19 @@
+import { QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';
+
+@RegisteredInstanceCommand('2.52.0', 1792907887530)
+export class AddParticipantHandleFieldToMessageChannelFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."messageChannel" ADD "participantHandleFieldUniversalIdentifier" uuid',
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."messageChannel" DROP COLUMN "participantHandleFieldUniversalIdentifier"',
+ );
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
index 8d343b11944..221a8ba61a1 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
@@ -256,6 +256,7 @@ import { RepairBackfillApplicationRegistrationVersionsSlowInstanceCommand } from
import { AddAgentChatChannelFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-51/2-51-instance-command-fast-1792686569823-add-agent-chat-channel';
import { BackfillRoleAgentChatChannelAccessSlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-51/2-51-instance-command-slow-1792686689823-backfill-role-agent-chat-channel-access';
import { AddAgentChatChannelNavigationMenuItemFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-51/2-51-instance-command-fast-1792686749823-add-agent-chat-channel-navigation-menu-item';
+import { AddParticipantHandleFieldToMessageChannelFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-52/2-52-instance-command-fast-1792907887530-add-participant-handle-field-to-message-channel';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -514,4 +515,5 @@ export const INSTANCE_COMMANDS = [
AddAgentChatChannelFastInstanceCommand,
BackfillRoleAgentChatChannelAccessSlowInstanceCommand,
AddAgentChatChannelNavigationMenuItemFastInstanceCommand,
+ AddParticipantHandleFieldToMessageChannelFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/create-app-message-channel.input.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/create-app-message-channel.input.ts
index d69e56a73c8..c53e32434dc 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/create-app-message-channel.input.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/create-app-message-channel.input.ts
@@ -36,4 +36,10 @@ export class CreateAppMessageChannelInput {
@IsEnum(MessageChannelVisibility)
@IsNotEmpty()
visibility: MessageChannelVisibility;
+
+ // set once: handles are stored in this field's canonical form, which a later change would leave inconsistent
+ @Field(() => UUIDScalarType, { nullable: true })
+ @IsOptional()
+ @IsUUID()
+ participantHandleFieldUniversalIdentifier?: string;
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/message-channel.dto.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/message-channel.dto.ts
index 5aa70820f83..38b3cf6bc9a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/message-channel.dto.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/message-channel.dto.ts
@@ -49,6 +49,11 @@ export class MessageChannelDTO {
@Field(() => MessageChannelType)
type: MessageChannelType;
+ @IsUUID()
+ @IsOptional()
+ @Field(() => UUIDScalarType, { nullable: true })
+ participantHandleFieldUniversalIdentifier: string | null;
+
@IsBoolean()
@Field()
isContactAutoCreationEnabled: boolean;
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/entities/message-channel.entity.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/entities/message-channel.entity.ts
index 618237e3231..b8c61e8f87b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/entities/message-channel.entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/entities/message-channel.entity.ts
@@ -24,6 +24,7 @@ import {
WebhookSubscriptionStatus,
} from 'twenty-shared/types';
+import { WasIntroducedInUpgrade } from 'src/engine/core-modules/upgrade/decorators/was-introduced-in-upgrade.decorator';
import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import { type MessageFolderEntity } from 'src/engine/metadata-modules/message-folder/entities/message-folder.entity';
import { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/workspace-related-entity.type';
@@ -171,6 +172,13 @@ export class MessageChannelEntity extends WorkspaceRelatedEntity {
@Column({ type: 'timestamptz', nullable: true })
webhookSubscriptionExpiresAt: Date | null;
+ @Column({ type: 'uuid', nullable: true })
+ @WasIntroducedInUpgrade({
+ upgradeCommandName:
+ '2.52.0_AddParticipantHandleFieldToMessageChannelFastInstanceCommand_1792907887530',
+ })
+ participantHandleFieldUniversalIdentifier: string | null;
+
@Column({ type: 'uuid', nullable: false })
connectedAccountId: string;
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.module.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.module.ts
index d88a8ac378f..c84a35272a4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.module.ts
@@ -14,6 +14,7 @@ import { ApplicationMessageChannelsService } from 'src/engine/metadata-modules/m
import { ApplicationMessageIngestionService } from 'src/engine/metadata-modules/message-channel/services/application-message-ingestion.service';
import { MessageFolderEntity } from 'src/engine/metadata-modules/message-folder/entities/message-folder.entity';
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
+import { MatchParticipantModule } from 'src/modules/match-participant/match-participant.module';
import { MessagingCommonModule } from 'src/modules/messaging/common/messaging-common.module';
import { MessagingImportManagerModule } from 'src/modules/messaging/message-import-manager/messaging-import-manager.module';
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
@@ -30,6 +31,7 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
ConnectedAccountMetadataModule,
MessagingImportManagerModule,
MessagingCommonModule,
+ MatchParticipantModule,
EmailingDomainModule,
],
providers: [
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-channels.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-channels.resolver.ts
index 483c9b868db..c4f75366070 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-channels.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-channels.resolver.ts
@@ -74,6 +74,8 @@ export class ApplicationMessageChannelsResolver {
handle: input.handle,
displayName: input.displayName,
visibility: input.visibility,
+ participantHandleFieldUniversalIdentifier:
+ input.participantHandleFieldUniversalIdentifier,
});
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.ts
index 1ddb91f7d88..b0e9194951e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.ts
@@ -25,6 +25,8 @@ import {
} from 'src/engine/metadata-modules/message-channel/message-channel.exception';
import { type MessageChannelDeletedEvent } from 'src/engine/metadata-modules/message-channel/types/message-channel-deleted.type';
import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
+import { PersonHandleFieldService } from 'src/modules/match-participant/person-handle-field/person-handle-field.service';
+import { canonicalizePersonHandle } from 'src/modules/match-participant/person-handle-field/utils/canonicalize-person-handle.util';
type ApplicationScope = {
applicationId: string;
@@ -39,6 +41,7 @@ type CreateArgs = ApplicationScope & {
handle: string;
displayName?: string;
visibility: MessageChannelVisibility;
+ participantHandleFieldUniversalIdentifier?: string;
};
type UpdateArgs = ApplicationScope & {
@@ -73,6 +76,7 @@ export class ApplicationMessageChannelsService {
@InjectRepository(ConnectedAccountEntity)
private readonly connectedAccountRepository: Repository<ConnectedAccountEntity>,
private readonly workspaceEventEmitter: WorkspaceEventEmitter,
+ private readonly personHandleFieldService: PersonHandleFieldService,
) {}
async list({
@@ -116,9 +120,10 @@ export class ApplicationMessageChannelsService {
workspaceId,
requestUserWorkspaceId,
connectedAccountId,
- handle,
+ handle: requestedHandle,
displayName,
visibility,
+ participantHandleFieldUniversalIdentifier,
}: CreateArgs): Promise<MessageChannelDTO> {
await this.assertOwnsConnectedAccount({
applicationId,
@@ -127,6 +132,12 @@ export class ApplicationMessageChannelsService {
connectedAccountId,
});
+ const handle = await this.resolveChannelHandleOrThrow({
+ workspaceId,
+ handle: requestedHandle,
+ participantHandleFieldUniversalIdentifier,
+ });
+
const existingChannel = await this.messageChannelRepository.findOne({
where: { connectedAccountId, handle, workspaceId },
});
@@ -145,6 +156,8 @@ export class ApplicationMessageChannelsService {
displayName: normalizeDisplayName(displayName),
type: MessageChannelType.APP,
visibility,
+ participantHandleFieldUniversalIdentifier:
+ participantHandleFieldUniversalIdentifier ?? null,
isSyncEnabled: true,
// inert since app channels skip the polling crons; mirrors EMAIL_GROUP so the UI reads healthy
syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
@@ -159,6 +172,47 @@ export class ApplicationMessageChannelsService {
return this.messageChannelRepository.save(entity);
}
+ // the channel's own handle shares its participants' namespace, so direction still compares like with like
+ private async resolveChannelHandleOrThrow({
+ workspaceId,
+ handle,
+ participantHandleFieldUniversalIdentifier,
+ }: Pick<
+ CreateArgs,
+ 'workspaceId' | 'handle' | 'participantHandleFieldUniversalIdentifier'
+ >): Promise<string> {
+ if (!isDefined(participantHandleFieldUniversalIdentifier)) {
+ return handle;
+ }
+
+ const personHandleField =
+ await this.personHandleFieldService.findByUniversalIdentifier({
+ workspaceId,
+ fieldUniversalIdentifier: participantHandleFieldUniversalIdentifier,
+ });
+
+ if (!isDefined(personHandleField)) {
+ throw new MessageChannelException(
+ `Field ${participantHandleFieldUniversalIdentifier} is not an active person field of type EMAILS, PHONES, LINKS or TEXT`,
+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
+ );
+ }
+
+ const canonicalHandle = canonicalizePersonHandle({
+ type: personHandleField.type,
+ value: handle,
+ });
+
+ if (!isDefined(canonicalHandle)) {
+ throw new MessageChannelException(
+ `Handle ${handle} is not a valid ${personHandleField.type} value`,
+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
+ );
+ }
+
+ return canonicalHandle;
+ }
+
async update({
applicationId,
workspaceId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-ingestion.service.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-ingestion.service.ts
index 26f439b8d91..07a38abfae5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-ingestion.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-ingestion.service.ts
@@ -16,8 +16,11 @@ import { ApplicationMessageChannelsService } from 'src/engine/metadata-modules/m
import { buildAppIngestionLockKey } from 'src/engine/metadata-modules/message-channel/utils/build-app-ingestion-lock-key.util';
import { buildAppMessageHeaderMessageId } from 'src/engine/metadata-modules/message-channel/utils/build-app-message-header-message-id.util';
import { resolveAppMessageDirection } from 'src/engine/metadata-modules/message-channel/utils/resolve-app-message-direction.util';
+import { withCanonicalParticipantHandlesOrThrow } from 'src/engine/metadata-modules/message-channel/utils/with-canonical-participant-handles-or-throw.util';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+import { PersonHandleFieldService } from 'src/modules/match-participant/person-handle-field/person-handle-field.service';
+import { type PersonHandleField } from 'src/modules/match-participant/person-handle-field/types/person-handle-field.type';
import { MessagingSaveMessagesAndEnqueueContactCreationService } from 'src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service';
import { type MessageWithParticipants } from 'src/modules/messaging/message-import-manager/types/message.type';
@@ -49,6 +52,7 @@ export class ApplicationMessageIngestionService {
private readonly saveMessagesService: MessagingSaveMessagesAndEnqueueContactCreationService,
private readonly workspaceOrmManager: WorkspaceOrmManager,
private readonly cacheLockService: CacheLockService,
+ private readonly personHandleFieldService: PersonHandleFieldService,
) {}
async ingest({
@@ -77,9 +81,20 @@ export class ApplicationMessageIngestionService {
this.assertExternalIdsAreUnique(messages);
await this.assertReferencedIdentitiesExist({ messages, workspaceId });
+ const personHandleField = await this.findPersonHandleFieldOrThrow({
+ workspaceId,
+ participantHandleFieldUniversalIdentifier:
+ messageChannel.participantHandleFieldUniversalIdentifier,
+ });
+
const messagesToSave = messages.map((message) =>
this.toMessageWithParticipants({
- message,
+ message: isDefined(personHandleField)
+ ? withCanonicalParticipantHandlesOrThrow({
+ message,
+ personHandleField,
+ })
+ : message,
applicationId,
messageChannel,
}),
@@ -89,13 +104,14 @@ export class ApplicationMessageIngestionService {
// locked per channel, the narrowest scope since dedup never spans channels
const savedMessages = await this.cacheLockService.withLock(
() =>
- this.saveMessagesService.saveMessagesAndEnqueueContactCreation(
+ this.saveMessagesService.saveMessagesAndEnqueueContactCreation({
messagesToSave,
// the save path only reads inert settings and the id off the channel
messageChannel,
connectedAccount,
workspaceId,
- ),
+ personHandleField: personHandleField ?? undefined,
+ }),
buildAppIngestionLockKey({ workspaceId, messageChannelId }),
INGESTION_LOCK_OPTIONS,
);
@@ -172,6 +188,34 @@ export class ApplicationMessageIngestionService {
};
}
+ // raw handles would mix with the canonical ones already stored and stop matching the channel's own handle
+ private async findPersonHandleFieldOrThrow({
+ workspaceId,
+ participantHandleFieldUniversalIdentifier,
+ }: {
+ workspaceId: string;
+ participantHandleFieldUniversalIdentifier: string | null;
+ }): Promise<PersonHandleField | null> {
+ if (!isDefined(participantHandleFieldUniversalIdentifier)) {
+ return null;
+ }
+
+ const personHandleField =
+ await this.personHandleFieldService.findByUniversalIdentifier({
+ workspaceId,
+ fieldUniversalIdentifier: participantHandleFieldUniversalIdentifier,
+ });
+
+ if (!isDefined(personHandleField)) {
+ throw new MessageChannelException(
+ `The person field ${participantHandleFieldUniversalIdentifier} this channel matches participants on no longer exists or is inactive`,
+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
+ );
+ }
+
+ return personHandleField;
+ }
+
// checked up front so the app gets an error rather than a dangling link that never renders
private async assertReferencedIdentitiesExist({
messages,
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/with-canonical-participant-handles-or-throw.util.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/with-canonical-participant-handles-or-throw.util.ts
new file mode 100644
index 00000000000..e683d9beff9
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/with-canonical-participant-handles-or-throw.util.ts
@@ -0,0 +1,58 @@
+import { isDefined, isNonEmptyString } from 'twenty-shared/utils';
+
+import { type AppMessageInput } from 'src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input';
+import {
+ MessageChannelException,
+ MessageChannelExceptionCode,
+} from 'src/engine/metadata-modules/message-channel/message-channel.exception';
+import { type PersonHandleField } from 'src/modules/match-participant/person-handle-field/types/person-handle-field.type';
+import { canonicalizePersonHandle } from 'src/modules/match-participant/person-handle-field/utils/canonicalize-person-handle.util';
+
+// stored canonical so a person change finds these participants by exact handle, whatever format the provider sent
+export const withCanonicalParticipantHandlesOrThrow = ({
+ message,
+ personHandleField,
+}: {
+ message: AppMessageInput;
+ personHandleField: Pick<PersonHandleField, 'type'>;
+}): AppMessageInput => {
+ // spellings of one handle collapse to the same canonical form, which must stay one participant per role
+ const participantsByRoleAndHandle = new Map<
+ string,
+ AppMessageInput['participants'][number]
+ >();
+
+ for (const participant of message.participants) {
+ const handle = canonicalizePersonHandle({
+ type: personHandleField.type,
+ value: participant.handle,
+ });
+
+ if (!isDefined(handle)) {
+ throw new MessageChannelException(
+ `Participant handle ${participant.handle} on message ${message.externalId} is not a valid ${personHandleField.type} value`,
+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
+ );
+ }
+
+ const key = `${participant.role}:${handle}`;
+ const earlierParticipant = participantsByRoleAndHandle.get(key);
+ const earlierDisplayName = earlierParticipant?.displayName;
+
+ participantsByRoleAndHandle.set(key, {
+ role: participant.role,
+ handle,
+ displayName: isNonEmptyString(earlierDisplayName)
+ ? earlierDisplayName
+ : participant.displayName,
+ personId: earlierParticipant?.personId ?? participant.personId,
+ workspaceMemberId:
+ earlierParticipant?.workspaceMemberId ?? participant.workspaceMemberId,
+ });
+ }
+
+ return {
+ ...message,
+ participants: [...participantsByRoleAndHandle.values()],
+ };
+};
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 867e6e64cbe..ed42a32bb38 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
@@ -5,16 +5,26 @@ import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channe
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 { PersonHandleFieldService } from 'src/modules/match-participant/person-handle-field/person-handle-field.service';
import { ParticipantTargetReconciliationService } from 'src/modules/match-participant/participant-target-reconciliation.service';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@Module({
- imports: [TypeOrmModule.forFeature([MessageChannelEntity])],
+ imports: [
+ TypeOrmModule.forFeature([MessageChannelEntity]),
+ WorkspaceCacheModule,
+ ],
providers: [
MatchParticipantService,
ParticipantTargetReconciliationService,
+ PersonHandleFieldService,
ReconcilePersonCompanyTargetsJob,
ParticipantTargetPersonListener,
],
- exports: [MatchParticipantService, ParticipantTargetReconciliationService],
+ exports: [
+ MatchParticipantService,
+ ParticipantTargetReconciliationService,
+ PersonHandleFieldService,
+ ],
})
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 c55517a622d..00af8030e82 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,6 +7,7 @@ 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 { type WorkspaceSelectQueryBuilder } from 'src/engine/twenty-orm/query-builder/workspace-select-query-builder';
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';
@@ -14,6 +15,9 @@ import { getWorkspaceRepositoryWithOptionalTransaction } from 'src/engine/twenty
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 { type PersonHandleField } from 'src/modules/match-participant/person-handle-field/types/person-handle-field.type';
+import { addPersonHandleFiltersToQueryBuilder } from 'src/modules/match-participant/person-handle-field/utils/add-person-handle-filters-to-query-builder.util';
+import { findPersonByCanonicalHandle } from 'src/modules/match-participant/person-handle-field/utils/find-person-by-canonical-handle.util';
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';
@@ -35,6 +39,14 @@ type MatchParticipantsForWorkspaceMembersArgs = {
workspaceId: string;
};
+type MatchParticipantsForPersonHandlesArgs = {
+ personHandleField: PersonHandleField;
+ messageChannelIds: string[];
+ handles: string[];
+ changedPersonIds: string[];
+ workspaceId: string;
+};
+
type MatchParticipantsForPeopleArgs = {
participantMatching: {
personEmails: string[];
@@ -62,6 +74,8 @@ export type MatchParticipantsArgs<
| 'personOnly'
| 'workspaceMemberAndPerson'
| 'targetsOnly';
+ // handles are canonical values of this person field
+ personHandleField?: PersonHandleField;
transactionScope?: WorkspaceTransactionScope;
};
@@ -97,6 +111,7 @@ export class MatchParticipantService<
sourceRecordIds,
objectMetadataName,
matchWith = 'workspaceMemberAndPerson',
+ personHandleField,
transactionScope,
}: MatchParticipantsArgs<ParticipantWorkspaceEntity>) {
// Targets derive from personId only, so a workspaceMemberOnly rematch cannot change them
@@ -153,6 +168,15 @@ export class MatchParticipantService<
},
);
+ const shouldMatchWithPerson =
+ matchWith === 'workspaceMemberAndPerson' || matchWith === 'personOnly';
+
+ // workspace members are only known by email
+ const shouldMatchWithWorkspaceMember =
+ (matchWith === 'workspaceMemberAndPerson' ||
+ matchWith === 'workspaceMemberOnly') &&
+ !isDefined(personHandleField);
+
const chunkSize = 200;
const chunkedParticipants = chunk(participants, chunkSize);
@@ -161,20 +185,21 @@ export class MatchParticipantService<
...new Set(participants.map((participant) => participant.handle)),
].filter(isDefined);
- const queryBuilder = addPersonEmailFiltersToQueryBuilder({
+ const people = await this.buildPersonQueryBuilder({
queryBuilder: personRepository.createQueryBuilder('person'),
- emails: uniqueParticipantsHandles,
- });
-
- const people = await queryBuilder
+ personHandleField,
+ handles: uniqueParticipantsHandles,
+ })
.orderBy('person.createdAt', 'ASC')
.getMany<PersonWorkspaceEntity>();
- const workspaceMembers = await workspaceMemberRepository.find({
- where: {
- userEmail: Any(uniqueParticipantsHandles),
- },
- });
+ const workspaceMembers = shouldMatchWithWorkspaceMember
+ ? await workspaceMemberRepository.find({
+ where: {
+ userEmail: Any(uniqueParticipantsHandles),
+ },
+ })
+ : [];
const partipantsToBeUpdated = participants
.map((participant) => ({
@@ -182,24 +207,22 @@ export class MatchParticipantService<
handle: participant.handle ?? '',
}))
.map((participant) => {
- const person = findPersonByPrimaryOrAdditionalEmail({
- people,
- email: participant.handle,
- });
+ const person = isDefined(personHandleField)
+ ? findPersonByCanonicalHandle({
+ people,
+ personHandleField,
+ handle: participant.handle,
+ })
+ : findPersonByPrimaryOrAdditionalEmail({
+ people,
+ email: participant.handle,
+ });
const workspaceMember = workspaceMembers.find(
(workspaceMember) =>
workspaceMember.userEmail === participant.handle,
);
- const shouldMatchWithPerson =
- matchWith === 'workspaceMemberAndPerson' ||
- matchWith === 'personOnly';
-
- const shouldMatchWithWorkspaceMember =
- matchWith === 'workspaceMemberAndPerson' ||
- matchWith === 'workspaceMemberOnly';
-
const newParticipant = {
...participant,
...(shouldMatchWithPerson && {
@@ -283,6 +306,68 @@ export class MatchParticipantService<
}, authContext);
}
+ // participants of channels matching on this person field, whose handle is one of the person's values before or after the change
+ public async matchParticipantsForPersonHandles({
+ personHandleField,
+ messageChannelIds,
+ handles,
+ changedPersonIds,
+ workspaceId,
+ }: MatchParticipantsForPersonHandlesArgs) {
+ if (!isNonEmptyArray(messageChannelIds) || !isNonEmptyArray(handles)) {
+ return;
+ }
+
+ const authContext = buildSystemAuthContext(workspaceId);
+
+ await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ await this.workspaceOrmManager.runInWorkspaceTransaction(
+ async (transactionScope) => {
+ const participantRepository = this.getParticipantRepository({
+ objectMetadataName: 'messageParticipant',
+ transactionScope,
+ });
+
+ const participantsWithHandle = await participantRepository
+ .createQueryBuilder('participant')
+ .where('"participant"."handle" = ANY(:handles)', { handles })
+ .getMany<ParticipantWorkspaceEntity>();
+
+ if (!isNonEmptyArray(participantsWithHandle)) {
+ return;
+ }
+
+ // the same handle can sit on a channel that matches another field, which this change does not concern
+ const messageIdsOnMatchingChannels =
+ await this.findMessageIdsOnChannels({
+ participants: participantsWithHandle,
+ messageChannelIds,
+ transactionScope,
+ });
+
+ // a link the app passed to someone else stands: only unlinked participants and those of the changed people move
+ const participantsToRematch = participantsWithHandle.filter(
+ (participant) =>
+ messageIdsOnMatchingChannels.has(
+ this.getSourceRecordId(participant),
+ ) &&
+ (!isDefined(participant.personId) ||
+ changedPersonIds.includes(participant.personId)),
+ );
+
+ await this.matchParticipants({
+ matchWith: 'personOnly',
+ participants: participantsToRematch,
+ sourceRecordIds: this.getSourceRecordIds(participantsToRematch),
+ objectMetadataName: 'messageParticipant',
+ personHandleField,
+ transactionScope,
+ });
+ },
+ );
+ }, authContext);
+ }
+
public async matchParticipantsForPeople({
participantMatching,
objectMetadataName,
@@ -364,7 +449,53 @@ export class MatchParticipantService<
return participants;
}
- const appChannelAssociations =
+ const appChannelMessageIds = await this.findMessageIdsOnChannels({
+ participants,
+ messageChannelIds: appMessageChannels.map(
+ (messageChannel) => messageChannel.id,
+ ),
+ transactionScope,
+ });
+
+ return participants.filter(
+ (participant) =>
+ !appChannelMessageIds.has(this.getSourceRecordId(participant)),
+ );
+ }
+
+ private buildPersonQueryBuilder({
+ queryBuilder,
+ personHandleField,
+ handles,
+ }: {
+ queryBuilder: WorkspaceSelectQueryBuilder;
+ personHandleField: PersonHandleField | undefined;
+ handles: string[];
+ }): WorkspaceSelectQueryBuilder {
+ if (!isDefined(personHandleField)) {
+ return addPersonEmailFiltersToQueryBuilder({
+ queryBuilder,
+ emails: handles,
+ });
+ }
+
+ return addPersonHandleFiltersToQueryBuilder({
+ queryBuilder,
+ personHandleField,
+ handles,
+ });
+ }
+
+ private async findMessageIdsOnChannels({
+ participants,
+ messageChannelIds,
+ transactionScope,
+ }: {
+ participants: ParticipantWorkspaceEntity[];
+ messageChannelIds: string[];
+ transactionScope: WorkspaceTransactionScope;
+ }): Promise<Set<string>> {
+ const associations =
await getWorkspaceRepositoryWithOptionalTransaction<MessageChannelMessageAssociationWorkspaceEntity>(
{
objectMetadataName: 'messageChannelMessageAssociation',
@@ -375,21 +506,12 @@ export class MatchParticipantService<
).find({
where: {
messageId: Any([...new Set(this.getSourceRecordIds(participants))]),
- messageChannelId: Any(
- appMessageChannels.map((messageChannel) => messageChannel.id),
- ),
+ messageChannelId: Any(messageChannelIds),
},
select: { messageId: true },
});
- const appChannelMessageIds = new Set(
- appChannelAssociations.map((association) => association.messageId),
- );
-
- return participants.filter(
- (participant) =>
- !appChannelMessageIds.has(this.getSourceRecordId(participant)),
- );
+ return new Set(associations.map((association) => association.messageId));
}
private getSourceRecordIds(
diff --git a/packages/twenty-server/src/modules/match-participant/person-handle-field/constants/person-handle-field-types.constant.ts b/packages/twenty-server/src/modules/match-participant/person-handle-field/constants/person-handle-field-types.constant.ts
new file mode 100644
index 00000000000..fdf37517809
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/person-handle-field/constants/person-handle-field-types.constant.ts
@@ -0,0 +1,8 @@
+import { FieldMetadataType } from 'twenty-shared/types';
+
+export const PERSON_HANDLE_FIELD_TYPES = [
+ FieldMetadataType.EMAILS,
+ FieldMetadataType.PHONES,
+ FieldMetadataType.LINKS,
+ FieldMetadataType.TEXT,
+] as const;
diff --git a/packages/twenty-server/src/modules/match-participant/person-handle-field/person-handle-field.service.ts b/packages/twenty-server/src/modules/match-participant/person-handle-field/person-handle-field.service.ts
new file mode 100644
index 00000000000..e91f7e2253a
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/person-handle-field/person-handle-field.service.ts
@@ -0,0 +1,83 @@
+import { Injectable } from '@nestjs/common';
+
+import { STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-shared/metadata';
+import { isDefined } from 'twenty-shared/utils';
+
+import { getFlatFieldsFromFlatObjectMetadata } from 'src/engine/api/graphql/workspace-schema-builder/utils/get-flat-fields-for-flat-object-metadata.util';
+import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';
+import { findFlatEntityByUniversalIdentifierOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier-or-throw.util';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { type PersonHandleField } from 'src/modules/match-participant/person-handle-field/types/person-handle-field.type';
+import { toPersonHandleFieldType } from 'src/modules/match-participant/person-handle-field/utils/to-person-handle-field-type.util';
+
+type PersonHandleFieldWithUniversalIdentifier = PersonHandleField & {
+ universalIdentifier: string;
+};
+
+@Injectable()
+export class PersonHandleFieldService {
+ constructor(private readonly workspaceCacheService: WorkspaceCacheService) {}
+
+ async findAll(
+ workspaceId: string,
+ ): Promise<PersonHandleFieldWithUniversalIdentifier[]> {
+ const { flatObjectMetadataMaps, flatFieldMetadataMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatObjectMetadataMaps',
+ 'flatFieldMetadataMaps',
+ ]);
+
+ const personObjectMetadata = findFlatEntityByUniversalIdentifierOrThrow({
+ flatEntityMaps: flatObjectMetadataMaps,
+ universalIdentifier: STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person,
+ });
+
+ return getFlatFieldsFromFlatObjectMetadata(
+ personObjectMetadata,
+ flatFieldMetadataMaps,
+ ).flatMap((fieldMetadata) => {
+ const type = toPersonHandleFieldType(fieldMetadata.type);
+
+ return fieldMetadata.isActive && isDefined(type)
+ ? [
+ {
+ name: fieldMetadata.name,
+ type,
+ universalIdentifier: fieldMetadata.universalIdentifier,
+ },
+ ]
+ : [];
+ });
+ }
+
+ async findByUniversalIdentifier({
+ workspaceId,
+ fieldUniversalIdentifier,
+ }: {
+ workspaceId: string;
+ fieldUniversalIdentifier: string;
+ }): Promise<PersonHandleField | null> {
+ const { flatFieldMetadataMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatFieldMetadataMaps',
+ ]);
+
+ const fieldMetadata = findFlatEntityByUniversalIdentifier({
+ flatEntityMaps: flatFieldMetadataMaps,
+ universalIdentifier: fieldUniversalIdentifier,
+ });
+
+ if (
+ !isDefined(fieldMetadata) ||
+ !fieldMetadata.isActive ||
+ fieldMetadata.objectMetadataUniversalIdentifier !==
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person
+ ) {
+ return null;
+ }
+
+ const type = toPersonHandleFieldType(fieldMetadata.type);
+
+ return isDefined(type) ? { name: fieldMetadata.name, type } : null;
+ }
+}
diff --git a/packages/twenty-server/src/modules/match-participant/person-handle-field/types/person-handle-field.type.ts b/packages/twenty-server/src/modules/match-participant/person-handle-field/types/person-handle-field.type.ts
new file mode 100644
index 00000000000..3eb8b796a7b
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/person-handle-field/types/person-handle-field.type.ts
@@ -0,0 +1,6 @@
+import { type PERSON_HANDLE_FIELD_TYPES } from 'src/modules/match-participant/person-handle-field/constants/person-handle-field-types.constant';
+
+export type PersonHandleField = {
+ name: string;
+ type: (typeof PERSON_HANDLE_FIELD_TYPES)[number];
+};
diff --git a/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/__tests__/canonicalize-person-handle.util.spec.ts b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/__tests__/canonicalize-person-handle.util.spec.ts
new file mode 100644
index 00000000000..9069a496729
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/__tests__/canonicalize-person-handle.util.spec.ts
@@ -0,0 +1,43 @@
+import { FieldMetadataType } from 'twenty-shared/types';
+
+import { canonicalizePersonHandle } from 'src/modules/match-participant/person-handle-field/utils/canonicalize-person-handle.util';
+
+describe('canonicalizePersonHandle', () => {
+ it.each([
+ [FieldMetadataType.EMAILS, ' [email protected] ', '[email protected]'],
+ [FieldMetadataType.TEXT, ' AdaLovelace ', 'adalovelace'],
+ [FieldMetadataType.PHONES, '+33 6 12-34.56 78', '+33612345678'],
+ [FieldMetadataType.PHONES, '33612345678', '+33612345678'],
+ [
+ FieldMetadataType.LINKS,
+ 'HTTPS://www.LinkedIn.com/in/ada-lovelace/#about',
+ 'linkedin.com/in/ada-lovelace',
+ ],
+ [
+ FieldMetadataType.LINKS,
+ 'https://www.facebook.com/profile.php?id=111',
+ 'facebook.com/profile.php?id=111',
+ ],
+ [
+ FieldMetadataType.LINKS,
+ 'https://Example.com/watch/?v=AbC#t=10',
+ 'example.com/watch?v=AbC',
+ ],
+ [
+ FieldMetadataType.LINKS,
+ 'linkedin.com/in/ada-lovelace',
+ 'linkedin.com/in/ada-lovelace',
+ ],
+ ] as const)('canonicalizes a %s handle %j', (type, value, expected) => {
+ expect(canonicalizePersonHandle({ type, value })).toBe(expected);
+ });
+
+ it.each([
+ [FieldMetadataType.EMAILS, ' '],
+ [FieldMetadataType.PHONES, 'no digits'],
+ [FieldMetadataType.LINKS, 'https://'],
+ [FieldMetadataType.TEXT, null],
+ ] as const)('returns null for an empty %s handle', (type, value) => {
+ expect(canonicalizePersonHandle({ type, value })).toBeNull();
+ });
+});
diff --git a/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/__tests__/get-canonical-person-handles.util.spec.ts b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/__tests__/get-canonical-person-handles.util.spec.ts
new file mode 100644
index 00000000000..133a85b556f
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/__tests__/get-canonical-person-handles.util.spec.ts
@@ -0,0 +1,70 @@
+import { FieldMetadataType } from 'twenty-shared/types';
+
+import { getCanonicalPersonHandles } from 'src/modules/match-participant/person-handle-field/utils/get-canonical-person-handles.util';
+
+describe('getCanonicalPersonHandles', () => {
+ it('splits primary and additional emails', () => {
+ expect(
+ getCanonicalPersonHandles({
+ type: FieldMetadataType.EMAILS,
+ value: {
+ primaryEmail: '[email protected]',
+ additionalEmails: ['[email protected]'],
+ },
+ }),
+ ).toEqual({
+ primary: ['[email protected]'],
+ additional: ['[email protected]'],
+ });
+ });
+
+ it('joins calling codes and numbers for phones', () => {
+ expect(
+ getCanonicalPersonHandles({
+ type: FieldMetadataType.PHONES,
+ value: {
+ primaryPhoneNumber: '612345678',
+ primaryPhoneCallingCode: '+33',
+ primaryPhoneCountryCode: 'FR',
+ additionalPhones: [
+ { number: '2025550123', callingCode: '+1', countryCode: 'US' },
+ ],
+ },
+ }),
+ ).toEqual({
+ primary: ['+33612345678'],
+ additional: ['+12025550123'],
+ });
+ });
+
+ it('reads primary and secondary links', () => {
+ expect(
+ getCanonicalPersonHandles({
+ type: FieldMetadataType.LINKS,
+ value: {
+ primaryLinkUrl: 'https://www.linkedin.com/in/ada/',
+ primaryLinkLabel: '',
+ secondaryLinks: [{ url: 'https://x.com/ada', label: 'X' }],
+ },
+ }),
+ ).toEqual({
+ primary: ['linkedin.com/in/ada'],
+ additional: ['x.com/ada'],
+ });
+ });
+
+ it('returns nothing for an empty or missing value', () => {
+ expect(
+ getCanonicalPersonHandles({
+ type: FieldMetadataType.PHONES,
+ value: null,
+ }),
+ ).toEqual({ primary: [], additional: [] });
+ expect(
+ getCanonicalPersonHandles({
+ type: FieldMetadataType.TEXT,
+ value: '',
+ }),
+ ).toEqual({ primary: [], additional: [] });
+ });
+});
diff --git a/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/__tests__/get-changed-person-handles.util.spec.ts b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/__tests__/get-changed-person-handles.util.spec.ts
new file mode 100644
index 00000000000..8791ad62eae
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/__tests__/get-changed-person-handles.util.spec.ts
@@ -0,0 +1,109 @@
+import { FieldMetadataType } from 'twenty-shared/types';
+
+import { getChangedPersonHandles } from 'src/modules/match-participant/person-handle-field/utils/get-changed-person-handles.util';
+
+const personHandleField = {
+ name: 'phones',
+ type: FieldMetadataType.PHONES,
+} as const;
+
+const buildPerson = (primaryPhoneNumber: string) => ({
+ phones: {
+ primaryPhoneNumber,
+ primaryPhoneCallingCode: '+33',
+ primaryPhoneCountryCode: 'FR',
+ additionalPhones: [],
+ },
+});
+
+describe('getChangedPersonHandles', () => {
+ it('sees a value added next to a duplicated one', () => {
+ const withAdditionalPhone = (number: string) => ({
+ phones: {
+ primaryPhoneNumber: '611111111',
+ primaryPhoneCallingCode: '+33',
+ primaryPhoneCountryCode: 'FR',
+ additionalPhones: [{ number, callingCode: '+33', countryCode: 'FR' }],
+ },
+ });
+
+ expect(
+ getChangedPersonHandles({
+ personHandleField,
+ personChanges: [
+ {
+ personId: 'person-a',
+ before: withAdditionalPhone('611111111'),
+ after: withAdditionalPhone('622222222'),
+ },
+ ],
+ }),
+ ).toEqual({
+ handles: ['+33611111111', '+33622222222'],
+ changedPersonIds: ['person-a'],
+ });
+ });
+
+ it('returns the values of a destroyed person', () => {
+ expect(
+ getChangedPersonHandles({
+ personHandleField,
+ personChanges: [
+ {
+ personId: 'person-a',
+ before: buildPerson('611111111'),
+ after: null,
+ },
+ ],
+ }),
+ ).toEqual({ handles: ['+33611111111'], changedPersonIds: ['person-a'] });
+ });
+
+ it('returns the values before and after a change', () => {
+ expect(
+ getChangedPersonHandles({
+ personHandleField,
+ personChanges: [
+ {
+ personId: 'person-a',
+ before: buildPerson('611111111'),
+ after: buildPerson('622222222'),
+ },
+ ],
+ }),
+ ).toEqual({
+ handles: ['+33611111111', '+33622222222'],
+ changedPersonIds: ['person-a'],
+ });
+ });
+
+ it('returns the values of a created person', () => {
+ expect(
+ getChangedPersonHandles({
+ personHandleField,
+ personChanges: [
+ {
+ personId: 'person-a',
+ before: null,
+ after: buildPerson('611111111'),
+ },
+ ],
+ }),
+ ).toEqual({ handles: ['+33611111111'], changedPersonIds: ['person-a'] });
+ });
+
+ it('ignores people whose values did not change', () => {
+ expect(
+ getChangedPersonHandles({
+ personHandleField,
+ personChanges: [
+ {
+ personId: 'person-a',
+ before: buildPerson('611111111'),
+ after: buildPerson('611111111'),
+ },
+ ],
+ }),
+ ).toEqual({ handles: [], changedPersonIds: [] });
+ });
+});
diff --git a/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/add-person-handle-filters-to-query-builder.util.ts b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/add-person-handle-filters-to-query-builder.util.ts
new file mode 100644
index 00000000000..a2b7878ae69
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/add-person-handle-filters-to-query-builder.util.ts
@@ -0,0 +1,84 @@
+import { FieldMetadataType } from 'twenty-shared/types';
+
+import { type WorkspaceSelectQueryBuilder } from 'src/engine/twenty-orm/query-builder/workspace-select-query-builder';
+import { type PersonHandleField } from 'src/modules/match-participant/person-handle-field/types/person-handle-field.type';
+
+// TRIM only strips spaces; the canonical form strips any leading and trailing whitespace
+const trimmedSql = (expression: string) =>
+ `regexp_replace(${expression}, '^\\s+|\\s+$', '', 'g')`;
+
+const canonicalTextSql = (expression: string) =>
+ `LOWER(${trimmedSql(expression)})`;
+
+const canonicalPhoneSql = ({
+ callingCode,
+ number,
+}: {
+ callingCode: string;
+ number: string;
+}) =>
+ `('+' || regexp_replace(COALESCE(${callingCode}, '') || COALESCE(${number}, ''), '[^0-9]', '', 'g'))`;
+
+const canonicalLinkSql = (expression: string) => {
+ const withoutFragment = `regexp_replace(${trimmedSql(expression)}, '#.*$', '')`;
+ const location = `regexp_replace(regexp_replace(LOWER(split_part(${withoutFragment}, '?', 1)), '^([a-z][a-z0-9+.-]*://)?(www\\.)?', ''), '/+$', '')`;
+ const query = `COALESCE(substring(${withoutFragment} from '\\?(.*)$'), '')`;
+
+ return `(${location} || CASE WHEN ${query} <> '' THEN '?' || ${query} ELSE '' END)`;
+};
+
+const jsonbArrayElementsSql = (column: string) =>
+ `jsonb_array_elements(CASE WHEN jsonb_typeof(${column}) = 'array' THEN ${column} ELSE '[]'::jsonb END)`;
+
+const buildCanonicalHandleConditions = ({
+ personHandleField,
+ alias,
+}: {
+ personHandleField: PersonHandleField;
+ alias: string;
+}): string[] => {
+ const column = (property: string) =>
+ `"${alias}"."${personHandleField.name}${property}"`;
+
+ switch (personHandleField.type) {
+ case FieldMetadataType.EMAILS:
+ return [
+ `${canonicalTextSql(column('PrimaryEmail'))} = ANY(:handles)`,
+ `EXISTS (SELECT 1 FROM ${jsonbArrayElementsSql(column('AdditionalEmails'))} AS "email"("value") WHERE ${canonicalTextSql(`"email"."value" #>> '{}'`)} = ANY(:handles))`,
+ ];
+ case FieldMetadataType.PHONES:
+ return [
+ `${canonicalPhoneSql({ callingCode: column('PrimaryPhoneCallingCode'), number: column('PrimaryPhoneNumber') })} = ANY(:handles)`,
+ `EXISTS (SELECT 1 FROM ${jsonbArrayElementsSql(column('AdditionalPhones'))} AS "phone"("value") WHERE ${canonicalPhoneSql({ callingCode: `"phone"."value" ->> 'callingCode'`, number: `"phone"."value" ->> 'number'` })} = ANY(:handles))`,
+ ];
+ case FieldMetadataType.LINKS:
+ return [
+ `${canonicalLinkSql(column('PrimaryLinkUrl'))} = ANY(:handles)`,
+ `EXISTS (SELECT 1 FROM ${jsonbArrayElementsSql(column('SecondaryLinks'))} AS "link"("value") WHERE ${canonicalLinkSql(`"link"."value" ->> 'url'`)} = ANY(:handles))`,
+ ];
+ case FieldMetadataType.TEXT:
+ return [
+ `${canonicalTextSql(`"${alias}"."${personHandleField.name}"`)} = ANY(:handles)`,
+ ];
+ }
+};
+
+// expects handles already canonical, as participant handles on a channel with a person handle field are stored
+export const addPersonHandleFiltersToQueryBuilder = ({
+ queryBuilder,
+ personHandleField,
+ handles,
+}: {
+ queryBuilder: WorkspaceSelectQueryBuilder;
+ personHandleField: PersonHandleField;
+ handles: string[];
+}): WorkspaceSelectQueryBuilder =>
+ queryBuilder
+ .where(
+ `(${buildCanonicalHandleConditions({
+ personHandleField,
+ alias: queryBuilder.alias,
+ }).join(' OR ')})`,
+ { handles },
+ )
+ .withDeleted();
diff --git a/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/canonicalize-person-handle.util.ts b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/canonicalize-person-handle.util.ts
new file mode 100644
index 00000000000..b4ee4d99391
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/canonicalize-person-handle.util.ts
@@ -0,0 +1,48 @@
+import { FieldMetadataType } from 'twenty-shared/types';
+import { isNonEmptyString } from 'twenty-shared/utils';
+
+import { type PersonHandleField } from 'src/modules/match-participant/person-handle-field/types/person-handle-field.type';
+
+// mirrored in SQL by add-person-handle-filters-to-query-builder.util.ts; the two must stay equivalent
+export const canonicalizePersonHandle = ({
+ type,
+ value,
+}: {
+ type: PersonHandleField['type'];
+ value: string | null | undefined;
+}): string | null => {
+ if (!isNonEmptyString(value)) {
+ return null;
+ }
+
+ const lowercased = value.trim().toLowerCase();
+
+ switch (type) {
+ case FieldMetadataType.EMAILS:
+ case FieldMetadataType.TEXT:
+ return isNonEmptyString(lowercased) ? lowercased : null;
+ case FieldMetadataType.PHONES: {
+ const digits = value.replace(/[^0-9]/g, '');
+
+ return isNonEmptyString(digits) ? `+${digits}` : null;
+ }
+ case FieldMetadataType.LINKS: {
+ // the query can carry the identity (profile.php?id=...), so it is kept as typed
+ const [location, ...queryParts] = value
+ .trim()
+ .replace(/#.*$/, '')
+ .split('?');
+ const query = queryParts.join('?');
+ const link = location
+ .toLowerCase()
+ .replace(/^([a-z][a-z0-9+.-]*:\/\/)?(www\.)?/, '')
+ .replace(/\/+$/, '');
+
+ if (!isNonEmptyString(link)) {
+ return null;
+ }
+
+ return isNonEmptyString(query) ? `${link}?${query}` : link;
+ }
+ }
+};
diff --git a/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/find-person-by-canonical-handle.util.ts b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/find-person-by-canonical-handle.util.ts
new file mode 100644
index 00000000000..5794a590669
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/find-person-by-canonical-handle.util.ts
@@ -0,0 +1,28 @@
+import { type PersonWorkspaceEntity } from 'src/modules/person/standard-objects/person.workspace-entity';
+import { type PersonHandleField } from 'src/modules/match-participant/person-handle-field/types/person-handle-field.type';
+import { getCanonicalPersonHandles } from 'src/modules/match-participant/person-handle-field/utils/get-canonical-person-handles.util';
+import { getPersonFieldValue } from 'src/modules/match-participant/person-handle-field/utils/get-person-field-value.util';
+
+// people must come oldest first: a primary value wins over an additional one, then the oldest person, as for emails
+export const findPersonByCanonicalHandle = ({
+ people,
+ personHandleField,
+ handle,
+}: {
+ people: PersonWorkspaceEntity[];
+ personHandleField: PersonHandleField;
+ handle: string;
+}): PersonWorkspaceEntity | undefined => {
+ const peopleWithHandles = people.map((person) => ({
+ person,
+ handles: getCanonicalPersonHandles({
+ type: personHandleField.type,
+ value: getPersonFieldValue({ person, fieldName: personHandleField.name }),
+ }),
+ }));
+
+ return (
+ peopleWithHandles.find(({ handles }) => handles.primary.includes(handle)) ??
+ peopleWithHandles.find(({ handles }) => handles.additional.includes(handle))
+ )?.person;
+};
diff --git a/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/get-canonical-person-handles.util.ts b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/get-canonical-person-handles.util.ts
new file mode 100644
index 00000000000..d4ef151130d
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/get-canonical-person-handles.util.ts
@@ -0,0 +1,96 @@
+import { FieldMetadataType } from 'twenty-shared/types';
+import {
+ isDefined,
+ isNonEmptyString,
+ isPlainObject,
+} from 'twenty-shared/utils';
+
+import { type PersonHandleField } from 'src/modules/match-participant/person-handle-field/types/person-handle-field.type';
+import { canonicalizePersonHandle } from 'src/modules/match-participant/person-handle-field/utils/canonicalize-person-handle.util';
+
+type CanonicalPersonHandles = {
+ primary: string[];
+ additional: string[];
+};
+
+type RawPersonHandles = {
+ primary: (string | null)[];
+ additional: (string | null)[];
+};
+
+const toRecord = (value: unknown): Record<string, unknown> =>
+ isPlainObject(value) ? value : {};
+
+const toList = (value: unknown): unknown[] =>
+ Array.isArray(value) ? value : [];
+
+const toStringOrNull = (value: unknown): string | null =>
+ typeof value === 'string' ? value : null;
+
+const toPhoneValue = (phone: Record<string, unknown>): string | null => {
+ const number = toStringOrNull(phone.number);
+
+ return isNonEmptyString(number)
+ ? `${toStringOrNull(phone.callingCode) ?? ''}${number}`
+ : null;
+};
+
+// person records come from events and raw queries, so composite values are read defensively
+const getRawPersonHandles = ({
+ type,
+ value,
+}: {
+ type: PersonHandleField['type'];
+ value: unknown;
+}): RawPersonHandles => {
+ const record = toRecord(value);
+
+ switch (type) {
+ case FieldMetadataType.EMAILS:
+ return {
+ primary: [toStringOrNull(record.primaryEmail)],
+ additional: toList(record.additionalEmails).map(toStringOrNull),
+ };
+ case FieldMetadataType.PHONES:
+ return {
+ primary: [
+ toPhoneValue({
+ number: record.primaryPhoneNumber,
+ callingCode: record.primaryPhoneCallingCode,
+ }),
+ ],
+ additional: toList(record.additionalPhones).map((phone) =>
+ toPhoneValue(toRecord(phone)),
+ ),
+ };
+ case FieldMetadataType.LINKS:
+ return {
+ primary: [toStringOrNull(record.primaryLinkUrl)],
+ additional: toList(record.secondaryLinks).map((link) =>
+ toStringOrNull(toRecord(link).url),
+ ),
+ };
+ case FieldMetadataType.TEXT:
+ return { primary: [toStringOrNull(value)], additional: [] };
+ }
+};
+
+export const getCanonicalPersonHandles = ({
+ type,
+ value,
+}: {
+ type: PersonHandleField['type'];
+ value: unknown;
+}): CanonicalPersonHandles => {
+ const { primary, additional } = getRawPersonHandles({ type, value });
+
+ const canonicalize = (values: (string | null)[]) =>
+ values
+ .map((rawValue) => canonicalizePersonHandle({ type, value: rawValue }))
+ .filter(isDefined);
+
+ return {
+ primary: canonicalize(primary),
+ additional: canonicalize(additional),
+ };
+};
diff --git a/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/get-changed-person-handles.util.ts b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/get-changed-person-handles.util.ts
new file mode 100644
index 00000000000..b5acb5dad86
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/get-changed-person-handles.util.ts
@@ -0,0 +1,65 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type PersonHandleField } from 'src/modules/match-participant/person-handle-field/types/person-handle-field.type';
+import { getCanonicalPersonHandles } from 'src/modules/match-participant/person-handle-field/utils/get-canonical-person-handles.util';
+import { getPersonFieldValue } from 'src/modules/match-participant/person-handle-field/utils/get-person-field-value.util';
+
+const getHandles = ({
+ personHandleField,
+ person,
+}: {
+ personHandleField: PersonHandleField;
+ person: object | null;
+}): string[] => {
+ if (!isDefined(person)) {
+ return [];
+ }
+
+ const { primary, additional } = getCanonicalPersonHandles({
+ type: personHandleField.type,
+ value: getPersonFieldValue({ person, fieldName: personHandleField.name }),
+ });
+
+ return [...primary, ...additional];
+};
+
+type PersonChange = {
+ personId: string;
+ before: object | null;
+ after: object | null;
+};
+
+export const getChangedPersonHandles = ({
+ personHandleField,
+ personChanges,
+}: {
+ personHandleField: PersonHandleField;
+ personChanges: PersonChange[];
+}): { handles: string[]; changedPersonIds: string[] } => {
+ const handles = new Set<string>();
+ const changedPersonIds = new Set<string>();
+
+ for (const { personId, before, after } of personChanges) {
+ const handlesBefore = new Set(
+ getHandles({ personHandleField, person: before }),
+ );
+ const handlesAfter = new Set(
+ getHandles({ personHandleField, person: after }),
+ );
+ const isUnchanged =
+ handlesBefore.size === handlesAfter.size &&
+ [...handlesBefore].every((handle) => handlesAfter.has(handle));
+
+ if (isUnchanged) {
+ continue;
+ }
+
+ changedPersonIds.add(personId);
+
+ for (const handle of [...handlesBefore, ...handlesAfter]) {
+ handles.add(handle);
+ }
+ }
+
+ return { handles: [...handles], changedPersonIds: [...changedPersonIds] };
+};
diff --git a/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/get-person-field-value.util.ts b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/get-person-field-value.util.ts
new file mode 100644
index 00000000000..2ba771a3df4
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/get-person-field-value.util.ts
@@ -0,0 +1,10 @@
+import { isPlainObject } from 'twenty-shared/utils';
+
+// read by name: the declared field can be one an app added, which the standard entity type does not list
+export const getPersonFieldValue = ({
+ person,
+ fieldName,
+}: {
+ person: object;
+ fieldName: string;
+}): unknown => (isPlainObject(person) ? person[fieldName] : undefined);
diff --git a/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/to-person-handle-field-type.util.ts b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/to-person-handle-field-type.util.ts
new file mode 100644
index 00000000000..9577c7934f5
--- /dev/null
+++ b/packages/twenty-server/src/modules/match-participant/person-handle-field/utils/to-person-handle-field-type.util.ts
@@ -0,0 +1,7 @@
+import { PERSON_HANDLE_FIELD_TYPES } from 'src/modules/match-participant/person-handle-field/constants/person-handle-field-types.constant';
+import { type PersonHandleField } from 'src/modules/match-participant/person-handle-field/types/person-handle-field.type';
+
+export const toPersonHandleFieldType = (
+ type: string,
+): PersonHandleField['type'] | undefined =>
+ PERSON_HANDLE_FIELD_TYPES.find((handleFieldType) => handleFieldType === type);
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/services/inbound-email-import.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/services/inbound-email-import.service.ts
index 5a74fdbb8e1..7704f3cb736 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/services/inbound-email-import.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/services/inbound-email-import.service.ts
@@ -136,10 +136,12 @@ export class InboundEmailImportService {
}
await this.messagingSaveMessagesAndEnqueueContactCreationService.saveMessagesAndEnqueueContactCreation(
- [message],
- messageChannel,
- connectedAccount,
- workspaceId,
+ {
+ messagesToSave: [message],
+ messageChannel,
+ connectedAccount,
+ workspaceId,
+ },
);
},
buildSystemAuthContext(workspaceId),
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-messages-import.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-messages-import.service.ts
index 67c38d234c6..cf1e0863fe2 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-messages-import.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-messages-import.service.ts
@@ -203,10 +203,12 @@ export class MessagingMessagesImportService {
if (messagesToSave.length > 0) {
await this.saveMessagesAndEnqueueContactCreationService.saveMessagesAndEnqueueContactCreation(
- messagesToSave,
- messageChannel,
- connectedAccount,
- workspaceId,
+ {
+ messagesToSave,
+ messageChannel,
+ connectedAccount,
+ workspaceId,
+ },
);
}
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts
index 0154e9b1a32..b2a4f6cae4e 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts
@@ -7,6 +7,7 @@ import {
MessageParticipantRole,
} from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
+import { Any, IsNull } from 'typeorm';
import { type MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
@@ -26,9 +27,11 @@ import {
import { MessagingMessageFolderAssociationService } from 'src/modules/messaging/message-import-manager/services/messaging-message-folder-association.service';
import { MessagingMessageService } from 'src/modules/messaging/message-import-manager/services/messaging-message.service';
import { type MessageChannelMessageAssociationFolderAssociation } from 'src/modules/messaging/message-import-manager/types/message-channel-message-association-folder-association.type';
+import { type MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';
import { type MessageWithParticipants } from 'src/modules/messaging/message-import-manager/types/message.type';
import { isGroupEmail } from 'src/modules/messaging/message-import-manager/utils/is-group-email';
import { MessagingMessageParticipantService } from 'src/modules/messaging/message-participant-manager/services/messaging-message-participant.service';
+import { type PersonHandleField } from 'src/modules/match-participant/person-handle-field/types/person-handle-field.type';
import { isWorkEmail } from 'src/utils/is-work-email';
@Injectable()
@@ -42,12 +45,19 @@ export class MessagingSaveMessagesAndEnqueueContactCreationService {
private readonly workspaceOrmManager: WorkspaceOrmManager,
) {}
- async saveMessagesAndEnqueueContactCreation(
- messagesToSave: MessageWithParticipants[],
- messageChannel: MessageChannelEntity,
- connectedAccount: ConnectedAccountEntity,
- workspaceId: string,
- ): Promise<
+ async saveMessagesAndEnqueueContactCreation({
+ messagesToSave,
+ messageChannel,
+ connectedAccount,
+ workspaceId,
+ personHandleField,
+ }: {
+ messagesToSave: MessageWithParticipants[];
+ messageChannel: MessageChannelEntity;
+ connectedAccount: ConnectedAccountEntity;
+ workspaceId: string;
+ personHandleField?: PersonHandleField;
+ }): Promise<
| {
messageExternalIdsAndIdsMap: Map<string, string>;
messageExternalIdToMessageThreadIdMap: Map<string, string>;
@@ -205,16 +215,20 @@ export class MessagingSaveMessagesAndEnqueueContactCreationService {
),
];
- // Matching non-email handles as emails would null out caller-supplied identities, so those channels only reconcile targets
- await this.messageParticipantService.matchMessageParticipants({
- participants: savedMessagesResult.savedMessageParticipants,
- messageIds,
- workspaceId,
- matchWith:
- messageChannel.type === MessageChannelType.APP
- ? 'targetsOnly'
- : 'workspaceMemberAndPerson',
- });
+ if (messageChannel.type !== MessageChannelType.APP) {
+ await this.messageParticipantService.matchMessageParticipants({
+ participants: savedMessagesResult.savedMessageParticipants,
+ messageIds,
+ workspaceId,
+ matchWith: 'workspaceMemberAndPerson',
+ });
+ } else {
+ await this.matchAppChannelParticipants({
+ personHandleField,
+ messageIds,
+ workspaceId,
+ });
+ }
return {
messageExternalIdsAndIdsMap:
@@ -223,4 +237,58 @@ export class MessagingSaveMessagesAndEnqueueContactCreationService {
savedMessagesResult.messageExternalIdToMessageThreadIdMap,
};
}
+
+ // matching non-email handles as emails would null out app-supplied identities, so only the declared field is used
+ private async matchAppChannelParticipants({
+ personHandleField,
+ messageIds,
+ workspaceId,
+ }: {
+ personHandleField: PersonHandleField | undefined;
+ messageIds: string[];
+ workspaceId: string;
+ }): Promise<void> {
+ if (!isDefined(personHandleField)) {
+ await this.messageParticipantService.matchMessageParticipants({
+ participants: [],
+ messageIds,
+ workspaceId,
+ matchWith: 'targetsOnly',
+ });
+
+ return;
+ }
+
+ await this.messageParticipantService.matchMessageParticipants({
+ participants: await this.findUnlinkedParticipants({
+ messageIds,
+ workspaceId,
+ }),
+ messageIds,
+ workspaceId,
+ matchWith: 'personOnly',
+ personHandleField,
+ });
+ }
+
+ // read back rather than taken from the save, so a retry after a failed match still links rows an earlier attempt stored
+ private async findUnlinkedParticipants({
+ messageIds,
+ workspaceId,
+ }: {
+ messageIds: string[];
+ workspaceId: string;
+ }): Promise<MessageParticipantWorkspaceEntity[]> {
+ return this.workspaceOrmManager.executeInWorkspaceContext(
+ async () =>
+ this.workspaceOrmManager
+ .getRepository<MessageParticipantWorkspaceEntity>(
+ 'messageParticipant',
+ { shouldBypassPermissionChecks: true },
+ )
+ .find({ where: { messageId: Any(messageIds), personId: IsNull() } }),
+ buildSystemAuthContext(workspaceId),
+ { lite: true },
+ );
+ }
}
diff --git a/packages/twenty-server/src/modules/messaging/message-outbound-manager/services/sent-message-persistence.service.ts b/packages/twenty-server/src/modules/messaging/message-outbound-manager/services/sent-message-persistence.service.ts
index c5805ad7f57..d23a104b5b6 100644
--- a/packages/twenty-server/src/modules/messaging/message-outbound-manager/services/sent-message-persistence.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-outbound-manager/services/sent-message-persistence.service.ts
@@ -33,10 +33,12 @@ export class SentMessagePersistenceService {
const savedMessagesResult =
await this.saveMessagesAndEnqueueContactCreationService.saveMessagesAndEnqueueContactCreation(
- [messageToSave],
- messageChannel,
- messageChannel.connectedAccount,
- input.workspaceId,
+ {
+ messagesToSave: [messageToSave],
+ messageChannel,
+ connectedAccount: messageChannel.connectedAccount,
+ workspaceId: input.workspaceId,
+ },
);
const messageId = savedMessagesResult?.messageExternalIdsAndIdsMap.get(
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.ts
index 15b1c5c1a84..b8bb63230bb 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
@@ -1,17 +1,28 @@
import { Scope } from '@nestjs/common';
+import { isDefined } from 'twenty-shared/utils';
+
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 { MatchParticipantService } from 'src/modules/match-participant/match-participant.service';
+import { PersonHandleFieldService } from 'src/modules/match-participant/person-handle-field/person-handle-field.service';
import { type MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';
+export type PersonHandleMatching = {
+ fieldUniversalIdentifier: string;
+ messageChannelIds: string[];
+ handles: string[];
+ changedPersonIds: string[];
+};
+
export type MessageParticipantMatchParticipantJobData = {
workspaceId: string;
participantMatching: {
personEmails: string[];
workspaceMemberIds: string[];
};
+ personHandleMatching?: PersonHandleMatching[];
};
@Processor({
@@ -21,11 +32,12 @@ export type MessageParticipantMatchParticipantJobData = {
export class MessageParticipantMatchParticipantJob {
constructor(
private readonly matchParticipantService: MatchParticipantService<MessageParticipantWorkspaceEntity>,
+ private readonly personHandleFieldService: PersonHandleFieldService,
) {}
@Process(MessageParticipantMatchParticipantJob.name)
async handle(data: MessageParticipantMatchParticipantJobData): Promise<void> {
- const { participantMatching, workspaceId } = data;
+ const { participantMatching, personHandleMatching, workspaceId } = data;
if (participantMatching.personEmails.length > 0) {
await this.matchParticipantService.matchParticipantsForPeople({
@@ -35,6 +47,29 @@ export class MessageParticipantMatchParticipantJob {
});
}
+ for (const {
+ fieldUniversalIdentifier,
+ messageChannelIds,
+ handles,
+ changedPersonIds,
+ } of personHandleMatching ?? []) {
+ const personHandleField =
+ await this.personHandleFieldService.findByUniversalIdentifier({
+ workspaceId,
+ fieldUniversalIdentifier,
+ });
+
+ if (isDefined(personHandleField)) {
+ await this.matchParticipantService.matchParticipantsForPersonHandles({
+ personHandleField,
+ messageChannelIds,
+ handles,
+ changedPersonIds,
+ workspaceId,
+ });
+ }
+ }
+
if (participantMatching.workspaceMemberIds.length > 0) {
await this.matchParticipantService.matchParticipantsForWorkspaceMembers({
participantMatching,
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.ts
index 3367b39b37b..60cb5c202dd 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
@@ -1,10 +1,14 @@
import { Injectable } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
import {
type ObjectRecordCreateEvent,
type ObjectRecordDeleteEvent,
type ObjectRecordUpdateEvent,
} from 'twenty-shared/database-events';
+import { MessageChannelType } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { In, Repository } from 'typeorm';
import { OnDatabaseBatchEvent } from 'src/engine/api/graphql/graphql-query-runner/decorators/on-database-batch-event.decorator';
import { DatabaseEventAction } from 'src/engine/api/graphql/graphql-query-runner/enums/database-event-action';
@@ -12,11 +16,15 @@ import { objectRecordChangedProperties as objectRecordUpdateEventChangedProperti
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 { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import { WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';
+import { PersonHandleFieldService } from 'src/modules/match-participant/person-handle-field/person-handle-field.service';
+import { getChangedPersonHandles } from 'src/modules/match-participant/person-handle-field/utils/get-changed-person-handles.util';
import { getPersonEmails } from 'src/modules/match-participant/utils/get-person-emails.util';
import {
MessageParticipantMatchParticipantJob,
type MessageParticipantMatchParticipantJobData,
+ type PersonHandleMatching,
} from 'src/modules/messaging/message-participant-manager/jobs/message-participant-match-participant.job';
import { type PersonWorkspaceEntity } from 'src/modules/person/standard-objects/person.workspace-entity';
@@ -25,6 +33,9 @@ export class MessageParticipantPersonListener {
constructor(
@InjectMessageQueue(MessageQueue.messagingQueue)
private readonly messageQueueService: MessageQueueService,
+ @InjectRepository(MessageChannelEntity)
+ private readonly messageChannelRepository: Repository<MessageChannelEntity>,
+ private readonly personHandleFieldService: PersonHandleFieldService,
) {}
@OnDatabaseBatchEvent('person', DatabaseEventAction.CREATED)
@@ -38,24 +49,25 @@ export class MessageParticipantPersonListener {
getPersonEmails(eventPayload.properties.after.emails).length > 0,
);
- if (personWithEmails.length === 0) {
- return;
- }
+ const personHandleMatching = await this.buildPersonHandleMatching({
+ workspaceId: payload.workspaceId,
+ personChanges: payload.events.map((eventPayload) => ({
+ personId: eventPayload.recordId,
+ before: null,
+ after: eventPayload.properties.after,
+ })),
+ });
- const personEmails = personWithEmails.flatMap((eventPayload) =>
- getPersonEmails(eventPayload.properties.after.emails),
- );
-
- await this.messageQueueService.add<MessageParticipantMatchParticipantJobData>(
- MessageParticipantMatchParticipantJob.name,
- {
- workspaceId: payload.workspaceId,
- participantMatching: {
- personEmails,
- workspaceMemberIds: [],
- },
+ await this.enqueueMatching({
+ workspaceId: payload.workspaceId,
+ participantMatching: {
+ personEmails: personWithEmails.flatMap((eventPayload) =>
+ getPersonEmails(eventPayload.properties.after.emails),
+ ),
+ workspaceMemberIds: [],
},
- );
+ personHandleMatching,
+ });
}
@OnDatabaseBatchEvent('person', DatabaseEventAction.UPDATED)
@@ -64,30 +76,129 @@ export class MessageParticipantPersonListener {
ObjectRecordUpdateEvent<PersonWorkspaceEntity>
>,
) {
- const personWithUpdatedEmails = payload.events.filter((eventPayload) =>
- objectRecordUpdateEventChangedProperties(
+ const personChanges = payload.events.map((eventPayload) => ({
+ personId: eventPayload.recordId,
+ before: eventPayload.properties.before,
+ after: eventPayload.properties.after,
+ changedFieldNames: objectRecordUpdateEventChangedProperties(
eventPayload.properties.before,
eventPayload.properties.after,
- ).includes('emails'),
- );
+ ),
+ }));
+
+ const personHandleMatching = await this.buildPersonHandleMatching({
+ workspaceId: payload.workspaceId,
+ personChanges,
+ });
- if (personWithUpdatedEmails.length === 0) {
+ await this.enqueueMatching({
+ workspaceId: payload.workspaceId,
+ participantMatching: {
+ personEmails: personChanges
+ .filter(({ changedFieldNames }) =>
+ changedFieldNames.includes('emails'),
+ )
+ .flatMap(({ before, after }) => [
+ ...getPersonEmails(before.emails),
+ ...getPersonEmails(after.emails),
+ ]),
+ workspaceMemberIds: [],
+ },
+ personHandleMatching,
+ });
+ }
+
+ private async enqueueMatching(
+ data: MessageParticipantMatchParticipantJobData,
+ ): Promise<void> {
+ if (
+ data.participantMatching.personEmails.length === 0 &&
+ (data.personHandleMatching ?? []).length === 0
+ ) {
return;
}
- 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: {
- personEmails,
- workspaceMemberIds: [],
- },
+ data,
+ );
+ }
+
+ private async buildPersonHandleMatching({
+ workspaceId,
+ personChanges,
+ }: {
+ workspaceId: string;
+ personChanges: {
+ personId: string;
+ before: PersonWorkspaceEntity | null;
+ after: PersonWorkspaceEntity | null;
+ changedFieldNames?: string[];
+ }[];
+ }): Promise<PersonHandleMatching[]> {
+ const changedHandlesByFieldUniversalIdentifier = new Map<
+ string,
+ { handles: string[]; changedPersonIds: string[] }
+ >();
+
+ for (const personHandleField of await this.personHandleFieldService.findAll(
+ workspaceId,
+ )) {
+ const changedHandles = getChangedPersonHandles({
+ personHandleField,
+ personChanges: personChanges.filter(
+ ({ changedFieldNames }) =>
+ !isDefined(changedFieldNames) ||
+ changedFieldNames.includes(personHandleField.name),
+ ),
+ });
+
+ if (changedHandles.handles.length > 0) {
+ changedHandlesByFieldUniversalIdentifier.set(
+ personHandleField.universalIdentifier,
+ changedHandles,
+ );
+ }
+ }
+
+ // most person writes stop here, before any channel lookup
+ if (changedHandlesByFieldUniversalIdentifier.size === 0) {
+ return [];
+ }
+
+ const messageChannels = await this.messageChannelRepository.find({
+ where: {
+ workspaceId,
+ type: MessageChannelType.APP,
+ participantHandleFieldUniversalIdentifier: In([
+ ...changedHandlesByFieldUniversalIdentifier.keys(),
+ ]),
+ },
+ select: { id: true, participantHandleFieldUniversalIdentifier: true },
+ });
+
+ return [...changedHandlesByFieldUniversalIdentifier].flatMap(
+ ([fieldUniversalIdentifier, { handles, changedPersonIds }]) => {
+ const messageChannelIds = messageChannels
+ .filter(
+ (messageChannel) =>
+ messageChannel.participantHandleFieldUniversalIdentifier ===
+ fieldUniversalIdentifier,
+ )
+ .map((messageChannel) => messageChannel.id);
+
+ if (messageChannelIds.length === 0) {
+ return [];
+ }
+
+ return [
+ {
+ fieldUniversalIdentifier,
+ messageChannelIds,
+ handles,
+ changedPersonIds,
+ },
+ ];
},
);
}
@@ -98,23 +209,24 @@ export class MessageParticipantPersonListener {
ObjectRecordDeleteEvent<PersonWorkspaceEntity>
>,
) {
- const personEmails = payload.events.flatMap((eventPayload) =>
- getPersonEmails(eventPayload.properties.before.emails),
- );
-
- if (personEmails.length === 0) {
- return;
- }
+ const personHandleMatching = await this.buildPersonHandleMatching({
+ workspaceId: payload.workspaceId,
+ personChanges: payload.events.map((eventPayload) => ({
+ personId: eventPayload.recordId,
+ before: eventPayload.properties.before,
+ after: null,
+ })),
+ });
- await this.messageQueueService.add<MessageParticipantMatchParticipantJobData>(
- MessageParticipantMatchParticipantJob.name,
- {
- workspaceId: payload.workspaceId,
- participantMatching: {
- personEmails,
- workspaceMemberIds: [],
- },
+ await this.enqueueMatching({
+ workspaceId: payload.workspaceId,
+ participantMatching: {
+ personEmails: payload.events.flatMap((eventPayload) =>
+ getPersonEmails(eventPayload.properties.before.emails),
+ ),
+ workspaceMemberIds: [],
},
- );
+ personHandleMatching,
+ });
}
}
diff --git a/packages/twenty-server/src/modules/messaging/message-participant-manager/message-participant-manager.module.ts b/packages/twenty-server/src/modules/messaging/message-participant-manager/message-participant-manager.module.ts
index 466fadae556..979123582e0 100644
--- a/packages/twenty-server/src/modules/messaging/message-participant-manager/message-participant-manager.module.ts
+++ b/packages/twenty-server/src/modules/messaging/message-participant-manager/message-participant-manager.module.ts
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import { ContactCreationManagerModule } from 'src/modules/contact-creation-manager/contact-creation-manager.module';
import { MatchParticipantModule } from 'src/modules/match-participant/match-participant.module';
import { MessageParticipantMatchParticipantJob } from 'src/modules/messaging/message-participant-manager/jobs/message-participant-match-participant.job';
@@ -11,7 +12,7 @@ import { MessagingMessageParticipantService } from 'src/modules/messaging/messag
@Module({
imports: [
- TypeOrmModule.forFeature([WorkspaceEntity]),
+ TypeOrmModule.forFeature([WorkspaceEntity, MessageChannelEntity]),
ContactCreationManagerModule,
MatchParticipantModule,
],
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 b6c47035a0a..fd3eb7c131b 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
@@ -156,11 +156,13 @@ export class MessagingMessageParticipantService {
messageIds,
workspaceId,
matchWith = 'workspaceMemberAndPerson',
+ personHandleField,
}: {
participants: MessageParticipantWorkspaceEntity[];
messageIds: string[];
workspaceId: string;
matchWith?: MatchParticipantsArgs<MessageParticipantWorkspaceEntity>['matchWith'];
+ personHandleField?: MatchParticipantsArgs<MessageParticipantWorkspaceEntity>['personHandleField'];
}): Promise<void> {
const authContext = buildSystemAuthContext(workspaceId);
@@ -171,6 +173,7 @@ export class MessagingMessageParticipantService {
sourceRecordIds: messageIds,
objectMetadataName: 'messageParticipant',
matchWith,
+ personHandleField,
});
},
authContext,
diff --git a/packages/twenty-server/test/integration/metadata/suites/message-channel/app-message-channel-participant-matching.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/message-channel/app-message-channel-participant-matching.integration-spec.ts
new file mode 100644
index 00000000000..cfbd6caa407
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/message-channel/app-message-channel-participant-matching.integration-spec.ts
@@ -0,0 +1,614 @@
+import { gql } from 'graphql-tag';
+import { createOneOperation } from 'test/integration/graphql/utils/create-one-operation.util';
+import { destroyOneOperationFactory } from 'test/integration/graphql/utils/destroy-one-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 { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';
+import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';
+import { findConnectionProvidersByApplication } from 'test/integration/metadata/suites/connection-provider/utils/find-connection-providers-by-application.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';
+import { waitForAllJobsToFinish } from 'test/integration/utils/wait-for-all-jobs-to-finish.util';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import {
+ ConnectedAccountProvider,
+ MessageChannelVisibility,
+ MessageParticipantRole,
+} from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { v4 } from 'uuid';
+
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+
+const APPLICATION_IDENTIFIER = v4();
+const PROVIDER_IDENTIFIER = v4();
+
+const WORKSPACE_SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
+
+const PHONES_FIELD_UNIVERSAL_IDENTIFIER =
+ STANDARD_OBJECTS.person.fields.phones.universalIdentifier;
+
+const CREATE_CHANNEL_MUTATION = gql`
+ mutation CreateAppMessageChannel($input: CreateAppMessageChannelInput!) {
+ createAppMessageChannel(input: $input) {
+ id
+ handle
+ participantHandleFieldUniversalIdentifier
+ }
+ }
+`;
+
+const INGEST_MESSAGES_MUTATION = gql`
+ mutation IngestAppMessages($input: IngestAppMessagesInput!) {
+ ingestAppMessages(input: $input) {
+ messages {
+ messageId
+ messageThreadId
+ }
+ }
+ }
+`;
+
+type FrenchPhone = { nationalNumber: string } | null;
+
+describe('app message channel participant matching (e2e)', () => {
+ let applicationToken: string;
+ let applicationDbId: string;
+ let connectedAccountId: string;
+ let messageChannelId: string;
+ const personIds: string[] = [];
+
+ const asApplication = (
+ operation: Parameters<typeof makeMetadataApiRequest>[0],
+ ) => makeMetadataApiRequest(operation, applicationToken);
+
+ const toPhones = (phone: FrenchPhone) => ({
+ primaryPhoneNumber: phone?.nationalNumber ?? '',
+ primaryPhoneCallingCode: isDefined(phone) ? '+33' : '',
+ primaryPhoneCountryCode: isDefined(phone) ? 'FR' : '',
+ additionalPhones: [],
+ });
+
+ const createPerson = async ({
+ firstName,
+ phone,
+ }: {
+ firstName: string;
+ phone: FrenchPhone;
+ }) => {
+ const id = v4();
+ const response = await createOneOperation({
+ objectMetadataSingularName: 'person',
+ input: { id, name: { firstName }, phones: toPhones(phone) },
+ });
+
+ expect(response.errors).toBeUndefined();
+ personIds.push(id);
+
+ return id;
+ };
+
+ const updatePersonPhone = async ({
+ personId,
+ phone,
+ }: {
+ personId: string;
+ phone: FrenchPhone;
+ }) => {
+ const response = await makeGraphqlApiRequest(
+ updateOneOperationFactory({
+ objectMetadataSingularName: 'person',
+ recordId: personId,
+ gqlFields: 'id',
+ data: { phones: toPhones(phone) },
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ await waitForAllJobsToFinish();
+ };
+
+ const ingestFrom = async ({
+ externalId,
+ senderHandle,
+ personId,
+ channelId = messageChannelId,
+ }: {
+ externalId: string;
+ senderHandle: string;
+ personId?: string;
+ channelId?: string;
+ }) => {
+ const response = await asApplication({
+ query: INGEST_MESSAGES_MUTATION,
+ variables: {
+ input: {
+ messageChannelId: channelId,
+ messages: [
+ {
+ externalId,
+ threadExternalId: `thread-${externalId}`,
+ text: 'Hello',
+ receivedAt: '2026-10-20T10:00:00.000Z',
+ participants: [
+ {
+ role: MessageParticipantRole.FROM,
+ handle: senderHandle,
+ personId,
+ },
+ {
+ role: MessageParticipantRole.TO,
+ handle: '+33 6 00 00 00 00',
+ },
+ ],
+ },
+ ],
+ },
+ },
+ });
+
+ await waitForAllJobsToFinish();
+
+ return response;
+ };
+
+ const findSender = async (
+ messageId: string,
+ ): Promise<{ handle: string; personId: string | null }> => {
+ const [sender] = await globalThis.testDataSource.query(
+ `SELECT handle, "personId" FROM "${WORKSPACE_SCHEMA}"."messageParticipant"
+ WHERE "messageId" = $1 AND role = $2`,
+ [messageId, MessageParticipantRole.FROM],
+ );
+
+ return sender;
+ };
+
+ const ingestFromOrThrow = async (args: Parameters<typeof ingestFrom>[0]) => {
+ const response = await ingestFrom(args);
+
+ expect(response.body.errors).toBeUndefined();
+
+ const [ingestedMessage]: { messageId: string; messageThreadId: string }[] =
+ response.body.data.ingestAppMessages.messages;
+
+ return ingestedMessage;
+ };
+
+ beforeAll(async () => {
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ name: 'App channel participant matching',
+ description: 'Participant matching on a declared person field',
+ sourcePath: 'app-channel-participant-matching',
+ });
+
+ const { errors } = await syncApplication({
+ manifest: buildBaseManifest({
+ appId: APPLICATION_IDENTIFIER,
+ roleId: v4(),
+ overrides: {
+ connectionProviders: [
+ {
+ universalIdentifier: PROVIDER_IDENTIFIER,
+ name: 'whatsapp',
+ displayName: 'WhatsApp',
+ type: 'oauth',
+ oauth: {
+ authorizationEndpoint: 'https://provider.example.com/authorize',
+ tokenEndpoint: 'https://provider.example.com/token',
+ scopes: [],
+ clientIdVariable: 'CLIENT_ID',
+ clientSecretVariable: 'CLIENT_SECRET',
+ },
+ },
+ ],
+ },
+ }),
+ });
+
+ expect(errors).toBeUndefined();
+ jest.useRealTimers();
+
+ const [provider] = await findConnectionProvidersByApplication(
+ APPLICATION_IDENTIFIER,
+ );
+
+ applicationDbId = provider.applicationId;
+ applicationToken = (
+ await generateAppleAdminApplicationTokenPair({
+ applicationId: applicationDbId,
+ })
+ ).applicationAccessToken.token;
+
+ connectedAccountId = v4();
+ await globalThis.testDataSource.query(
+ `INSERT INTO core."connectedAccount"
+ (id, handle, provider, scope, "workspaceId", "userWorkspaceId",
+ "applicationId", "connectionProviderId")
+ VALUES ($1, $2, $3, 'WORKSPACE', $4, $5, $6, $7)`,
+ [
+ connectedAccountId,
+ '+33600000000',
+ ConnectedAccountProvider.APP,
+ SEED_APPLE_WORKSPACE_ID,
+ USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ applicationDbId,
+ provider.id,
+ ],
+ );
+
+ const channelResponse = await asApplication({
+ query: CREATE_CHANNEL_MUTATION,
+ variables: {
+ input: {
+ connectedAccountId,
+ handle: '+33 6 00 00 00 00',
+ visibility: MessageChannelVisibility.SHARE_EVERYTHING,
+ participantHandleFieldUniversalIdentifier:
+ PHONES_FIELD_UNIVERSAL_IDENTIFIER,
+ },
+ },
+ });
+
+ expect(channelResponse.body.errors).toBeUndefined();
+ expect(channelResponse.body.data.createAppMessageChannel).toMatchObject({
+ handle: '+33600000000',
+ participantHandleFieldUniversalIdentifier:
+ PHONES_FIELD_UNIVERSAL_IDENTIFIER,
+ });
+
+ messageChannelId = channelResponse.body.data.createAppMessageChannel.id;
+ }, 180000);
+
+ afterAll(async () => {
+ const messages: { id: string; messageThreadId: string | null }[] =
+ await globalThis.testDataSource.query(
+ `SELECT id, "messageThreadId" FROM "${WORKSPACE_SCHEMA}"."message"
+ WHERE "headerMessageId" LIKE $1`,
+ [`app:${applicationDbId}:%`],
+ );
+ const messageIds = messages.map((message) => message.id);
+ const messageThreadIds = [
+ ...new Set(
+ messages.map((message) => message.messageThreadId).filter(isDefined),
+ ),
+ ];
+
+ for (const table of [
+ 'messageChannelMessageAssociation',
+ 'messageParticipant',
+ ]) {
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${WORKSPACE_SCHEMA}"."${table}" WHERE "messageId" = ANY($1)`,
+ [messageIds],
+ );
+ }
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${WORKSPACE_SCHEMA}"."message" WHERE id = ANY($1)`,
+ [messageIds],
+ );
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${WORKSPACE_SCHEMA}"."messageThreadTarget" WHERE "messageThreadId" = ANY($1)`,
+ [messageThreadIds],
+ );
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${WORKSPACE_SCHEMA}"."messageThread" WHERE id = ANY($1)`,
+ [messageThreadIds],
+ );
+
+ for (const personId of personIds) {
+ await makeGraphqlApiRequest(
+ destroyOneOperationFactory({
+ objectMetadataSingularName: 'person',
+ recordId: personId,
+ gqlFields: 'id',
+ }),
+ );
+ }
+
+ await globalThis.testDataSource.query(
+ `DELETE FROM core."connectedAccount" WHERE id = $1`,
+ [connectedAccountId],
+ );
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ });
+ }, 120000);
+
+ it('stores the handle in canonical form and links it to the person with that phone', async () => {
+ const adaId = await createPerson({
+ firstName: 'Ada',
+ phone: { nationalNumber: '612345678' },
+ });
+
+ const { messageId, messageThreadId } = await ingestFromOrThrow({
+ externalId: 'from-ada',
+ senderHandle: '+33 6 12 34 56 78',
+ });
+
+ expect(await findSender(messageId)).toEqual({
+ handle: '+33612345678',
+ personId: adaId,
+ });
+
+ const targets = await globalThis.testDataSource.query(
+ `SELECT "targetPersonId" FROM "${WORKSPACE_SCHEMA}"."messageThreadTarget"
+ WHERE "messageThreadId" = $1`,
+ [messageThreadId],
+ );
+
+ expect(targets).toEqual(
+ expect.arrayContaining([{ targetPersonId: adaId }]),
+ );
+ });
+
+ it('links past conversations when a person gains the value and releases them when they lose it', async () => {
+ const graceId = await createPerson({ firstName: 'Grace', phone: null });
+
+ const { messageId } = await ingestFromOrThrow({
+ externalId: 'from-grace',
+ senderHandle: '+33699999999',
+ });
+
+ expect((await findSender(messageId)).personId).toBeNull();
+
+ await updatePersonPhone({
+ personId: graceId,
+ phone: { nationalNumber: '699999999' },
+ });
+ expect((await findSender(messageId)).personId).toBe(graceId);
+
+ await updatePersonPhone({ personId: graceId, phone: null });
+ expect((await findSender(messageId)).personId).toBeNull();
+ });
+
+ it('keeps a personId the app passes, even when another person gains or loses that value', async () => {
+ const katherineId = await createPerson({
+ firstName: 'Katherine',
+ phone: null,
+ });
+ const dorothyId = await createPerson({
+ firstName: 'Dorothy',
+ phone: { nationalNumber: '688888888' },
+ });
+
+ const { messageId } = await ingestFromOrThrow({
+ externalId: 'from-dorothy-number',
+ senderHandle: '+33688888888',
+ personId: katherineId,
+ });
+
+ expect((await findSender(messageId)).personId).toBe(katherineId);
+
+ await updatePersonPhone({ personId: dorothyId, phone: null });
+ expect((await findSender(messageId)).personId).toBe(katherineId);
+ });
+
+ it('relinks to the next person with that value when the linked person is destroyed', async () => {
+ const hedyId = await createPerson({
+ firstName: 'Hedy',
+ phone: { nationalNumber: '677777777' },
+ });
+ const radiaId = await createPerson({
+ firstName: 'Radia',
+ phone: { nationalNumber: '677777777' },
+ });
+
+ const { messageId } = await ingestFromOrThrow({
+ externalId: 'from-shared-number',
+ senderHandle: '+33677777777',
+ });
+
+ expect((await findSender(messageId)).personId).toBe(hedyId);
+
+ const response = await makeGraphqlApiRequest(
+ destroyOneOperationFactory({
+ objectMetadataSingularName: 'person',
+ recordId: hedyId,
+ gqlFields: 'id',
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ personIds.splice(personIds.indexOf(hedyId), 1);
+ await waitForAllJobsToFinish();
+
+ expect((await findSender(messageId)).personId).toBe(radiaId);
+ });
+
+ it('keeps a personId the app passes when a person gains that handle as an email', async () => {
+ const channelResponse = await asApplication({
+ query: CREATE_CHANNEL_MUTATION,
+ variables: {
+ input: {
+ connectedAccountId,
+ handle: '[email protected]',
+ visibility: MessageChannelVisibility.SHARE_EVERYTHING,
+ },
+ },
+ });
+
+ expect(channelResponse.body.errors).toBeUndefined();
+
+ const katherineId = await createPerson({
+ firstName: 'Katherine',
+ phone: null,
+ });
+
+ const { messageId } = await ingestFromOrThrow({
+ externalId: 'from-mary-email',
+ senderHandle: '[email protected]',
+ personId: katherineId,
+ channelId: channelResponse.body.data.createAppMessageChannel.id,
+ });
+
+ expect((await findSender(messageId)).personId).toBe(katherineId);
+
+ const maryId = await createPerson({ firstName: 'Mary', phone: null });
+ const response = await makeGraphqlApiRequest(
+ updateOneOperationFactory({
+ objectMetadataSingularName: 'person',
+ recordId: maryId,
+ gqlFields: 'id',
+ data: {
+ emails: { primaryEmail: '[email protected]', additionalEmails: [] },
+ },
+ }),
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ await waitForAllJobsToFinish();
+
+ expect((await findSender(messageId)).personId).toBe(katherineId);
+ });
+
+ it('links a sender stored before a matching person existed when the message is ingested again', async () => {
+ const { messageId } = await ingestFromOrThrow({
+ externalId: 'from-before-match',
+ senderHandle: '+33655555555',
+ });
+
+ expect((await findSender(messageId)).personId).toBeNull();
+
+ const maryId = await createPerson({ firstName: 'Mary', phone: null });
+
+ // written straight to the table so no person event rematches it
+ await globalThis.testDataSource.query(
+ `UPDATE "${WORKSPACE_SCHEMA}"."person"
+ SET "phonesPrimaryPhoneNumber" = '655555555',
+ "phonesPrimaryPhoneCallingCode" = '+33'
+ WHERE id = $1`,
+ [maryId],
+ );
+
+ await ingestFromOrThrow({
+ externalId: 'from-before-match',
+ senderHandle: '+33655555555',
+ });
+
+ expect((await findSender(messageId)).personId).toBe(maryId);
+ });
+
+ it('keeps links that differ only by their query apart', async () => {
+ const channelResponse = await asApplication({
+ query: CREATE_CHANNEL_MUTATION,
+ variables: {
+ input: {
+ connectedAccountId,
+ handle: 'https://www.facebook.com/profile.php?id=999',
+ visibility: MessageChannelVisibility.SHARE_EVERYTHING,
+ participantHandleFieldUniversalIdentifier:
+ STANDARD_OBJECTS.person.fields.linkedinLink.universalIdentifier,
+ },
+ },
+ });
+
+ expect(channelResponse.body.errors).toBeUndefined();
+
+ const createPersonWithLink = async (primaryLinkUrl: string) => {
+ const id = v4();
+ const response = await createOneOperation({
+ objectMetadataSingularName: 'person',
+ input: {
+ id,
+ name: { firstName: 'Linked' },
+ linkedinLink: { primaryLinkUrl },
+ },
+ });
+
+ expect(response.errors).toBeUndefined();
+ personIds.push(id);
+
+ return id;
+ };
+
+ await createPersonWithLink('https://www.facebook.com/profile.php?id=111');
+ const secondId = await createPersonWithLink(
+ 'https://www.facebook.com/profile.php?id=222',
+ );
+
+ const { messageId } = await ingestFromOrThrow({
+ externalId: 'from-profile-222',
+ senderHandle: 'https://facebook.com/profile.php?id=222',
+ channelId: channelResponse.body.data.createAppMessageChannel.id,
+ });
+
+ expect(await findSender(messageId)).toEqual({
+ handle: 'facebook.com/profile.php?id=222',
+ personId: secondId,
+ });
+ });
+
+ it('stores one participant when a message lists two spellings of the same handle', async () => {
+ const response = await asApplication({
+ query: INGEST_MESSAGES_MUTATION,
+ variables: {
+ input: {
+ messageChannelId,
+ messages: [
+ {
+ externalId: 'two-spellings',
+ threadExternalId: 'thread-two-spellings',
+ text: 'Hello',
+ receivedAt: '2026-10-20T10:00:00.000Z',
+ participants: [
+ {
+ role: MessageParticipantRole.FROM,
+ handle: '+33 6 22 22 22 22',
+ },
+ {
+ role: MessageParticipantRole.TO,
+ handle: '+33 6 44 44 44 44',
+ },
+ { role: MessageParticipantRole.TO, handle: '+33644444444' },
+ ],
+ },
+ ],
+ },
+ },
+ });
+
+ expect(response.body.errors).toBeUndefined();
+ await waitForAllJobsToFinish();
+
+ const [{ messageId }] = response.body.data.ingestAppMessages.messages;
+ const recipients = await globalThis.testDataSource.query(
+ `SELECT handle FROM "${WORKSPACE_SCHEMA}"."messageParticipant"
+ WHERE "messageId" = $1 AND role = $2`,
+ [messageId, MessageParticipantRole.TO],
+ );
+
+ expect(recipients).toEqual([{ handle: '+33644444444' }]);
+ });
+
+ it('rejects a handle that has no phone digits', async () => {
+ const response = await ingestFrom({
+ externalId: 'from-nobody',
+ senderHandle: 'not a number',
+ });
+
+ expect(response.body.errors).toBeDefined();
+ });
+
+ it('refuses a field that cannot hold handles', async () => {
+ const response = await asApplication({
+ query: CREATE_CHANNEL_MUTATION,
+ variables: {
+ input: {
+ connectedAccountId,
+ handle: '+33 6 11 11 11 11',
+ visibility: MessageChannelVisibility.SHARE_EVERYTHING,
+ participantHandleFieldUniversalIdentifier:
+ STANDARD_OBJECTS.person.fields.company.universalIdentifier,
+ },
+ },
+ });
+
+ expect(response.body.errors).toBeDefined();
+ });
+});
diff --git a/packages/twenty-shared/src/application/appMessageChannelType.ts b/packages/twenty-shared/src/application/appMessageChannelType.ts
index c4d7c0cc552..555bbe3369e 100644
--- a/packages/twenty-shared/src/application/appMessageChannelType.ts
+++ b/packages/twenty-shared/src/application/appMessageChannelType.ts
@@ -12,4 +12,6 @@ export type AppMessageChannel = {
connectedAccountId: string;
// False rejects ingestion without deleting the channel; existing messages stay readable.
isSyncEnabled: boolean;
+ // Person field participant handles are matched against; null when the app links participants itself.
+ participantHandleFieldUniversalIdentifier: string | null;
};