Skip to content

The open alternative to Salesforce, designed for AI.

Expose the channel of each timeline thread (#29324)

martmull327d50bc7deb
diff --git a/packages/twenty-front/src/generated/schema.ts b/packages/twenty-front/src/generated/schema.ts
index affe2f3fad1..366a8073143 100644
--- a/packages/twenty-front/src/generated/schema.ts
+++ b/packages/twenty-front/src/generated/schema.ts
@@ -360,6 +360,13 @@ export type LinksMetadata = {
secondaryLinks?: Maybe<Array<LinkMetadata>>;
};
+export enum MessageChannelType {
+ APP = 'APP',
+ EMAIL = 'EMAIL',
+ EMAIL_GROUP = 'EMAIL_GROUP',
+ SMS = 'SMS'
+}
+
export enum MessageChannelVisibility {
METADATA = 'METADATA',
SHARE_EVERYTHING = 'SHARE_EVERYTHING',
@@ -555,6 +562,7 @@ export type Query = {
coreWorkflowsWithCurrentVersions: Array<CoreWorkflowWithCurrentVersionDto>;
dpaAgreements: Array<DpaAgreement>;
dpaPreview: DpaDocument;
+ getMessageThreadChannel?: Maybe<TimelineThreadChannel>;
/** @deprecated Use getTimelineCalendarEventsFromObjectRecord instead */
getTimelineCalendarEventsFromCompanyId: TimelineCalendarEventsWithTotal;
getTimelineCalendarEventsFromObjectRecord: TimelineCalendarEventsWithTotal;
@@ -621,6 +629,11 @@ export type QueryCoreWorkflowsWithCurrentVersionsArgs = {
};
+export type QueryGetMessageThreadChannelArgs = {
+ messageThreadId: Scalars['UUID']['input'];
+};
+
+
export type QueryGetTimelineCalendarEventsFromCompanyIdArgs = {
companyId: Scalars['UUID']['input'];
page: Scalars['Int']['input'];
@@ -838,6 +851,7 @@ export type TimelineCalendarEventsWithTotal = {
export type TimelineThread = {
__typename?: 'TimelineThread';
+ channel?: Maybe<TimelineThreadChannel>;
firstParticipant: TimelineThreadParticipant;
id: Scalars['UUID']['output'];
lastMessageBody: Scalars['String']['output'];
@@ -851,6 +865,13 @@ export type TimelineThread = {
visibility: MessageChannelVisibility;
};
+export type TimelineThreadChannel = {
+ __typename?: 'TimelineThreadChannel';
+ applicationId?: Maybe<Scalars['UUID']['output']>;
+ provider: Scalars['String']['output'];
+ type: MessageChannelType;
+};
+
export type TimelineThreadParticipant = {
__typename?: 'TimelineThreadParticipant';
avatarUrl: Scalars['String']['output'];
diff --git a/packages/twenty-server/src/engine/core-modules/messaging/dtos/timeline-thread-channel.dto.ts b/packages/twenty-server/src/engine/core-modules/messaging/dtos/timeline-thread-channel.dto.ts
new file mode 100644
index 00000000000..16d623fb4bb
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/messaging/dtos/timeline-thread-channel.dto.ts
@@ -0,0 +1,17 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+import { MessageChannelType } from 'twenty-shared/types';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+
+@ObjectType('TimelineThreadChannel')
+export class TimelineThreadChannelDTO {
+ @Field(() => MessageChannelType)
+ type: MessageChannelType;
+
+ @Field()
+ provider: string;
+
+ @Field(() => UUIDScalarType, { nullable: true })
+ applicationId: string | null;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/messaging/dtos/timeline-thread.dto.ts b/packages/twenty-server/src/engine/core-modules/messaging/dtos/timeline-thread.dto.ts
index d6c4c1cdd34..62e6827e484 100644
--- a/packages/twenty-server/src/engine/core-modules/messaging/dtos/timeline-thread.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/messaging/dtos/timeline-thread.dto.ts
@@ -2,6 +2,7 @@ import { Field, ObjectType } from '@nestjs/graphql';
import { MessageChannelVisibility } from 'twenty-shared/types';
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { TimelineThreadChannelDTO } from 'src/engine/core-modules/messaging/dtos/timeline-thread-channel.dto';
import { TimelineThreadParticipantDTO } from 'src/engine/core-modules/messaging/dtos/timeline-thread-participant.dto';
@ObjectType('TimelineThread')
@@ -38,4 +39,7 @@ export class TimelineThreadDTO {
@Field()
lastMessageIsDraft: boolean;
+
+ @Field(() => TimelineThreadChannelDTO, { nullable: true })
+ channel: TimelineThreadChannelDTO | null;
}
diff --git a/packages/twenty-server/src/engine/core-modules/messaging/services/get-messages.service.ts b/packages/twenty-server/src/engine/core-modules/messaging/services/get-messages.service.ts
index 122bfc5bfce..315a271977e 100644
--- a/packages/twenty-server/src/engine/core-modules/messaging/services/get-messages.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/messaging/services/get-messages.service.ts
@@ -175,17 +175,20 @@ export class GetMessagesService {
workspaceId,
);
- const threadVisibilityByThreadId =
- await this.timelineMessagingService.getThreadVisibilityByThreadId({
- messageThreadIds,
- userWorkspaceId,
- workspaceId,
- });
+ const { threadVisibilityByThreadId, threadChannelByThreadId } =
+ await this.timelineMessagingService.getThreadVisibilityAndChannelByThreadId(
+ {
+ messageThreadIds,
+ userWorkspaceId,
+ workspaceId,
+ },
+ );
return formatThreads(
messageThreads,
threadParticipantsByThreadId,
threadVisibilityByThreadId,
+ threadChannelByThreadId,
);
}
diff --git a/packages/twenty-server/src/engine/core-modules/messaging/services/timeline-messaging.service.ts b/packages/twenty-server/src/engine/core-modules/messaging/services/timeline-messaging.service.ts
index ac6a4b9091f..3f940eebb77 100644
--- a/packages/twenty-server/src/engine/core-modules/messaging/services/timeline-messaging.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/messaging/services/timeline-messaging.service.ts
@@ -11,6 +11,7 @@ import { In, type Repository } from 'typeorm';
import { FileUrlService } from 'src/engine/core-modules/file/file-url/file-url.service';
import { TIMELINE_THREADS_DEFAULT_PAGE_SIZE } from 'src/engine/core-modules/messaging/constants/messaging.constants';
+import { type TimelineThreadChannelDTO } from 'src/engine/core-modules/messaging/dtos/timeline-thread-channel.dto';
import { type TimelineThreadDTO } from 'src/engine/core-modules/messaging/dtos/timeline-thread.dto';
import { getEffectiveMessageChannelVisibility } from 'src/engine/core-modules/messaging/utils/get-effective-message-channel-visibility.util';
import { type TargetFilter } from 'src/engine/core-modules/target/utils/get-target-field-name-for-object-record.util';
@@ -29,6 +30,7 @@ type TimelineMessageThread = Omit<
| 'participantCount'
| 'read'
| 'visibility'
+ | 'channel'
>;
@Injectable()
@@ -414,7 +416,40 @@ export class TimelineMessagingService {
}, authContext);
}
- public async getThreadVisibilityByThreadId({
+ public async getMessageThreadChannel({
+ messageThreadId,
+ userWorkspaceId,
+ workspaceId,
+ }: {
+ messageThreadId: string;
+ userWorkspaceId: string;
+ workspaceId: string;
+ }): Promise<TimelineThreadChannelDTO | null> {
+ const allowedRecordIds =
+ await this.workspaceOrmManager.executeInWorkspaceContext(() =>
+ this.workspaceOrmManager
+ .getRepository('messageThread')
+ .findRecordIdsAllowedForOperations({
+ recordIds: [messageThreadId],
+ operationTypes: ['select'],
+ }),
+ );
+
+ if (!allowedRecordIds.select.has(messageThreadId)) {
+ return null;
+ }
+
+ const { threadChannelByThreadId } =
+ await this.getThreadVisibilityAndChannelByThreadId({
+ messageThreadIds: [messageThreadId],
+ userWorkspaceId,
+ workspaceId,
+ });
+
+ return threadChannelByThreadId[messageThreadId] ?? null;
+ }
+
+ public async getThreadVisibilityAndChannelByThreadId({
messageThreadIds,
userWorkspaceId,
workspaceId,
@@ -423,7 +458,8 @@ export class TimelineMessagingService {
userWorkspaceId: string;
workspaceId: string;
}): Promise<{
- [key: string]: MessageChannelVisibility;
+ threadVisibilityByThreadId: Record<string, MessageChannelVisibility>;
+ threadChannelByThreadId: Record<string, TimelineThreadChannelDTO>;
}> {
return this.workspaceOrmManager.executeInWorkspaceContext(async () => {
const messageThreadRepository =
@@ -446,6 +482,7 @@ export class TimelineMessagingService {
.where('messageThread.id = ANY(:messageThreadIds)', {
messageThreadIds,
})
+ .orderBy('messageChannelMessageAssociation.messageChannelId')
.getRawMany<{ id: string; messageChannelId: string | null }>();
const allMessageChannelIds = [
@@ -457,12 +494,17 @@ export class TimelineMessagingService {
];
if (allMessageChannelIds.length === 0) {
- return {};
+ return { threadVisibilityByThreadId: {}, threadChannelByThreadId: {} };
}
const messageChannels = await this.messageChannelRepository.find({
where: { id: In(allMessageChannelIds), workspaceId },
- select: { id: true, visibility: true, connectedAccountId: true },
+ select: {
+ id: true,
+ visibility: true,
+ connectedAccountId: true,
+ type: true,
+ },
});
const allConnectedAccountIds = [
@@ -471,16 +513,47 @@ export class TimelineMessagingService {
),
];
+ const connectedAccounts = await this.connectedAccountRepository.find({
+ where: { id: In(allConnectedAccountIds), workspaceId },
+ select: {
+ id: true,
+ userWorkspaceId: true,
+ provider: true,
+ applicationId: true,
+ },
+ });
+
const ownedAccountIds = new Set(
- (
- await this.connectedAccountRepository.find({
- where: {
- id: In(allConnectedAccountIds),
- userWorkspaceId,
- },
- select: { id: true },
- })
- ).map((account) => account.id),
+ connectedAccounts
+ .filter((account) => account.userWorkspaceId === userWorkspaceId)
+ .map((account) => account.id),
+ );
+
+ const connectedAccountById = new Map(
+ connectedAccounts.map((account) => [account.id, account]),
+ );
+
+ const channelById = new Map<string, TimelineThreadChannelDTO>(
+ messageChannels.flatMap((channel) => {
+ const connectedAccount = connectedAccountById.get(
+ channel.connectedAccountId,
+ );
+
+ if (!isDefined(connectedAccount)) {
+ return [];
+ }
+
+ return [
+ [
+ channel.id,
+ {
+ type: channel.type,
+ provider: connectedAccount.provider,
+ applicationId: connectedAccount.applicationId ?? null,
+ },
+ ],
+ ];
+ }),
);
const channelVisibilityMap = new Map(
@@ -497,13 +570,25 @@ export class TimelineMessagingService {
const visibilityValues = Object.values(MessageChannelVisibility);
- const threadVisibilityByThreadId: {
- [key: string]: MessageChannelVisibility;
- } = {};
+ const threadVisibilityByThreadId: Record<
+ string,
+ MessageChannelVisibility
+ > = {};
+ const threadChannelByThreadId: Record<string, TimelineThreadChannelDTO> =
+ {};
for (const { id: threadId, messageChannelId } of threadChannelRows) {
if (!messageChannelId) continue;
+ const channel = channelById.get(messageChannelId);
+
+ if (
+ isDefined(channel) &&
+ !isDefined(threadChannelByThreadId[threadId])
+ ) {
+ threadChannelByThreadId[threadId] = channel;
+ }
+
const channelVisibility = channelVisibilityMap.get(messageChannelId);
if (!channelVisibility) continue;
@@ -520,7 +605,7 @@ export class TimelineMessagingService {
];
}
- return threadVisibilityByThreadId;
+ return { threadVisibilityByThreadId, threadChannelByThreadId };
}, buildSystemAuthContext(workspaceId));
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/messaging/timeline-messaging.resolver.ts b/packages/twenty-server/src/engine/core-modules/messaging/timeline-messaging.resolver.ts
index 590f10799ca..8e72deea6cb 100644
--- a/packages/twenty-server/src/engine/core-modules/messaging/timeline-messaging.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/messaging/timeline-messaging.resolver.ts
@@ -12,9 +12,11 @@ import {
TIMELINE_THREADS_SEARCH_INPUT_MAX_LENGTH,
} from 'src/engine/core-modules/messaging/constants/messaging.constants';
import { DismissReconnectAccountBannerInput } from 'src/engine/core-modules/messaging/dtos/dismiss-reconnect-account-banner.input';
+import { TimelineThreadChannelDTO } from 'src/engine/core-modules/messaging/dtos/timeline-thread-channel.dto';
import { TimelineThreadSearchResultDTO } from 'src/engine/core-modules/messaging/dtos/timeline-thread-search-result.dto';
import { TimelineThreadsWithTotalDTO } from 'src/engine/core-modules/messaging/dtos/timeline-threads-with-total.dto';
import { GetMessagesService } from 'src/engine/core-modules/messaging/services/get-messages.service';
+import { TimelineMessagingService } from 'src/engine/core-modules/messaging/services/timeline-messaging.service';
import { type AuthContextUser } from 'src/engine/core-modules/auth/types/auth-context.type';
import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -42,6 +44,12 @@ class GetTimelineThreadsFromObjectRecordArgs {
pageSize: number;
}
+@ArgsType()
+class GetMessageThreadChannelArgs {
+ @Field(() => UUIDScalarType)
+ messageThreadId: string;
+}
+
@ArgsType()
class SearchTimelineThreadsArgs {
@Field(() => String)
@@ -113,6 +121,7 @@ class GetTimelineThreadsFromOpportunityIdArgs {
export class TimelineMessagingResolver {
constructor(
private readonly getMessagesFromPersonIdsService: GetMessagesService,
+ private readonly timelineMessagingService: TimelineMessagingService,
private readonly accountsToReconnectService: AccountsToReconnectService,
) {}
@@ -138,6 +147,19 @@ export class TimelineMessagingResolver {
});
}
+ @Query(() => TimelineThreadChannelDTO, { nullable: true })
+ async getMessageThreadChannel(
+ @AuthUserWorkspaceId() userWorkspaceId: string,
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ @Args() { messageThreadId }: GetMessageThreadChannelArgs,
+ ): Promise<TimelineThreadChannelDTO | null> {
+ return this.timelineMessagingService.getMessageThreadChannel({
+ messageThreadId,
+ userWorkspaceId,
+ workspaceId: workspace.id,
+ });
+ }
+
@Query(() => TimelineThreadSearchResultDTO)
async searchTimelineThreads(
@AuthUserWorkspaceId() userWorkspaceId: string,
diff --git a/packages/twenty-server/src/engine/core-modules/messaging/utils/format-threads.util.ts b/packages/twenty-server/src/engine/core-modules/messaging/utils/format-threads.util.ts
index f75d7d71df9..ce7a76b6baa 100644
--- a/packages/twenty-server/src/engine/core-modules/messaging/utils/format-threads.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/messaging/utils/format-threads.util.ts
@@ -2,6 +2,7 @@ import { FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED } from 'twenty-shared/
import { isDefined } from 'twenty-shared/utils';
import { MessageChannelVisibility } from 'twenty-shared/types';
+import { type TimelineThreadChannelDTO } from 'src/engine/core-modules/messaging/dtos/timeline-thread-channel.dto';
import { type TimelineThreadDTO } from 'src/engine/core-modules/messaging/dtos/timeline-thread.dto';
import { extractParticipantSummary } from 'src/engine/core-modules/messaging/utils/extract-participant-summary.util';
import { type MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';
@@ -14,13 +15,13 @@ export const formatThreads = (
| 'participantCount'
| 'read'
| 'visibility'
+ | 'channel'
>[],
threadParticipantsByThreadId: {
[key: string]: MessageParticipantWorkspaceEntity[];
},
- threadVisibilityByThreadId: {
- [key: string]: MessageChannelVisibility;
- },
+ threadVisibilityByThreadId: Record<string, MessageChannelVisibility>,
+ threadChannelByThreadId: Record<string, TimelineThreadChannelDTO>,
): TimelineThreadDTO[] => {
return threads
.filter((thread) => isDefined(threadParticipantsByThreadId[thread.id]))
@@ -42,6 +43,7 @@ export const formatThreads = (
: FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED,
...extractParticipantSummary(threadParticipantsByThreadId[thread.id]),
visibility,
+ channel: threadChannelByThreadId[thread.id] ?? null,
read: true,
};
});
diff --git a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
index d89dcadc468..3e235e24266 100644
--- a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
+++ b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
@@ -567,6 +567,7 @@ exports[`endpoint permission declarations should match the auth principals, perm
"TimelineCalendarEventResolver.getTimelineCalendarEventsFromPersonId {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"TimelineCalendarEventResolver.searchTimelineCalendarEvents {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"TimelineMessagingResolver.dismissReconnectAccountBanner {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["CONNECTED_ACCOUNTS"]}",
+ "TimelineMessagingResolver.getMessageThreadChannel {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"TimelineMessagingResolver.getTimelineThreadsFromCompanyId {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"TimelineMessagingResolver.getTimelineThreadsFromObjectRecord {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"TimelineMessagingResolver.getTimelineThreadsFromOpportunityId {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
diff --git a/packages/twenty-server/test/integration/metadata/suites/message-channel/app-message-channels.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/message-channel/app-message-channels.integration-spec.ts
index 006a1658ff9..2ef2f9403a4 100644
--- a/packages/twenty-server/test/integration/metadata/suites/message-channel/app-message-channels.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/message-channel/app-message-channels.integration-spec.ts
@@ -6,6 +6,16 @@ import { setupApplicationForSync } from 'test/integration/metadata/suites/applic
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 { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.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 { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';
+import { findManyObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/find-many-object-metadata.util';
+import { upsertObjectPermissions } from 'test/integration/metadata/suites/object-permission/utils/upsert-object-permissions.util';
+import { createOneRole } from 'test/integration/metadata/suites/role/utils/create-one-role.util';
+import { deleteOneRole } from 'test/integration/metadata/suites/role/utils/delete-one-role.util';
+import { findOneRoleByLabel } from 'test/integration/metadata/suites/role/utils/find-one-role-by-label.util';
+import { updateWorkspaceMemberRole } from 'test/integration/metadata/suites/role/utils/update-workspace-member-role.util';
import { type Manifest } from 'twenty-shared/application';
import {
ConnectedAccountProvider,
@@ -19,6 +29,7 @@ import { v4 as uuidv4 } from 'uuid';
import { INGEST_APP_MESSAGES_MAX_BATCH_SIZE } from 'src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input';
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 { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
import { MessageDirection } from 'src/modules/messaging/common/enums/message-direction.enum';
const OWNING_APP_ID = uuidv4();
@@ -47,6 +58,39 @@ const CREATE_CHANNEL_MUTATION = gql`
}
`;
+const GET_MESSAGE_THREAD_CHANNEL_QUERY = gql`
+ query GetMessageThreadChannel($messageThreadId: UUID!) {
+ getMessageThreadChannel(messageThreadId: $messageThreadId) {
+ type
+ provider
+ applicationId
+ }
+ }
+`;
+
+const GET_TIMELINE_THREADS_QUERY = gql`
+ query GetTimelineThreadsFromObjectRecord(
+ $objectNameSingular: String!
+ $recordId: UUID!
+ ) {
+ getTimelineThreadsFromObjectRecord(
+ objectNameSingular: $objectNameSingular
+ recordId: $recordId
+ page: 1
+ pageSize: 50
+ ) {
+ timelineThreads {
+ id
+ channel {
+ type
+ provider
+ applicationId
+ }
+ }
+ }
+ }
+`;
+
const LIST_CHANNELS_QUERY = gql`
query AppMessageChannels($filter: ListAppMessageChannelsInput) {
appMessageChannels(filter: $filter) {
@@ -784,6 +828,185 @@ describe('app message channels API (e2e)', () => {
});
});
+ it('exposes the app channel on the timeline threads of the matched person', async () => {
+ const channel = await createChannelOrThrow();
+ const personId = uuidv4();
+
+ await makeGraphqlApiRequest(
+ createOneOperationFactory({
+ objectMetadataSingularName: 'person',
+ gqlFields: 'id',
+ data: { id: personId },
+ }),
+ );
+
+ try {
+ const ingestResponse = await ingest({
+ messageChannelId: channel.id,
+ messages: [
+ buildMessage({
+ externalId: 'msg-1',
+ threadExternalId: `thread-${uuidv4()}`,
+ senderHandle: '[email protected]',
+ personId,
+ }),
+ ],
+ });
+
+ expect(ingestResponse.body.errors).toBeUndefined();
+
+ const [{ messageThreadId }] =
+ ingestResponse.body.data.ingestAppMessages.messages;
+
+ const timelineResponse = await makeGraphqlApiRequest({
+ query: GET_TIMELINE_THREADS_QUERY,
+ variables: { objectNameSingular: 'person', recordId: personId },
+ });
+
+ expect(timelineResponse.body.errors).toBeUndefined();
+ expect(
+ timelineResponse.body.data.getTimelineThreadsFromObjectRecord
+ .timelineThreads,
+ ).toEqual([
+ {
+ id: messageThreadId,
+ channel: {
+ type: MessageChannelType.APP,
+ provider: ConnectedAccountProvider.APP,
+ applicationId: owningApplicationDbId,
+ },
+ },
+ ]);
+
+ const threadChannelResponse = await makeGraphqlApiRequest({
+ query: GET_MESSAGE_THREAD_CHANNEL_QUERY,
+ variables: { messageThreadId },
+ });
+
+ expect(threadChannelResponse.body.errors).toBeUndefined();
+ expect(threadChannelResponse.body.data.getMessageThreadChannel).toEqual(
+ {
+ type: MessageChannelType.APP,
+ provider: ConnectedAccountProvider.APP,
+ applicationId: owningApplicationDbId,
+ },
+ );
+ } finally {
+ await makeGraphqlApiRequest(
+ destroyOneOperationFactory({
+ objectMetadataSingularName: 'person',
+ gqlFields: 'id',
+ recordId: personId,
+ }),
+ );
+ }
+ });
+
+ it('returns no channel for a message thread the user cannot read', async () => {
+ const channel = await createChannelOrThrow();
+
+ const ingestResponse = await ingest({
+ messageChannelId: channel.id,
+ messages: [
+ buildMessage({
+ externalId: 'msg-1',
+ threadExternalId: `thread-${uuidv4()}`,
+ senderHandle: '[email protected]',
+ }),
+ ],
+ });
+
+ expect(ingestResponse.body.errors).toBeUndefined();
+
+ const [{ messageThreadId }] =
+ ingestResponse.body.data.ingestAppMessages.messages;
+
+ const queryThreadChannelAsJony = () =>
+ makeGraphqlApiRequest(
+ {
+ query: GET_MESSAGE_THREAD_CHANNEL_QUERY,
+ variables: { messageThreadId },
+ },
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ const readableResponse = await queryThreadChannelAsJony();
+
+ expect(readableResponse.body.errors).toBeUndefined();
+ expect(readableResponse.body.data.getMessageThreadChannel).not.toBeNull();
+
+ const memberRoleId = (await findOneRoleByLabel({ label: 'Member' })).id;
+
+ const { objects } = await findManyObjectMetadata({
+ input: { filter: {}, paging: { first: 1000 } },
+ gqlFields: 'id nameSingular',
+ });
+
+ const messageThreadObjectMetadataId = objects.find(
+ (objectMetadata) => objectMetadata.nameSingular === 'messageThread',
+ )?.id;
+
+ jestExpectToBeDefined(messageThreadObjectMetadataId);
+
+ const { data: roleData } = await createOneRole({
+ expectToFail: false,
+ input: {
+ label: 'Message thread unreadable role',
+ canUpdateAllSettings: false,
+ canAccessAllTools: false,
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: false,
+ canSoftDeleteAllObjectRecords: false,
+ canDestroyAllObjectRecords: false,
+ },
+ });
+
+ const restrictedRoleId = roleData.createOneRole.id;
+
+ try {
+ await upsertObjectPermissions({
+ expectToFail: false,
+ input: {
+ roleId: restrictedRoleId,
+ objectPermissions: [
+ {
+ objectMetadataId: messageThreadObjectMetadataId,
+ canReadObjectRecords: false,
+ canUpdateObjectRecords: false,
+ canSoftDeleteObjectRecords: false,
+ canDestroyObjectRecords: false,
+ },
+ ],
+ },
+ });
+
+ await updateWorkspaceMemberRole({
+ expectToFail: false,
+ input: {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ roleId: restrictedRoleId,
+ },
+ });
+
+ const restrictedResponse = await queryThreadChannelAsJony();
+
+ expect(restrictedResponse.body.errors).toBeUndefined();
+ expect(restrictedResponse.body.data.getMessageThreadChannel).toBeNull();
+ } finally {
+ await updateWorkspaceMemberRole({
+ expectToFail: false,
+ input: {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ roleId: memberRoleId,
+ },
+ });
+ await deleteOneRole({
+ expectToFail: false,
+ input: { idToDelete: restrictedRoleId },
+ });
+ }
+ });
+
it('returns the same ids when a provider redelivers the same message', async () => {
const channel = await createChannelOrThrow();
const threadExternalId = `thread-${uuidv4()}`;