Skip to content

The open alternative to Salesforce, designed for AI.

Show import progress on connected accounts (#27491)

neo773f8436a8bd8fc
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 82221403821..168ed05c280 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -2770,6 +2770,7 @@ type MessageChannel {
excludeNonProfessionalEmails: Boolean!
handle: String!
id: UUID!
+ importProgress: Int
isContactAutoCreationEnabled: Boolean!
isSyncEnabled: Boolean!
messageFolderImportPolicy: MessageFolderImportPolicy!
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index ab0f781e889..2d982eef733 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1890,6 +1890,7 @@ export interface MessageChannel {
excludeNonProfessionalEmails: Scalars['Boolean']
handle: Scalars['String']
id: Scalars['UUID']
+ importProgress?: Scalars['Int']
isContactAutoCreationEnabled: Scalars['Boolean']
isSyncEnabled: Scalars['Boolean']
messageFolderImportPolicy: MessageFolderImportPolicy
@@ -6140,6 +6141,7 @@ export interface MessageChannelGenqlSelection{
excludeNonProfessionalEmails?: boolean | number
handle?: boolean | number
id?: boolean | number
+ importProgress?: boolean | number
isContactAutoCreationEnabled?: boolean | number
isSyncEnabled?: boolean | number
messageFolderImportPolicy?: 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 7b17eb4f7bd..7613da1bf44 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -5722,6 +5722,9 @@ export default {
"id": [
494
],
+ "importProgress": [
+ 8
+ ],
"isContactAutoCreationEnabled": [
4
],
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 069ed2a014f..616f8130cb6 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -2927,6 +2927,7 @@ export type MessageChannel = {
excludeNonProfessionalEmails: Scalars['Boolean']['output'];
handle: Scalars['String']['output'];
id: Scalars['UUID']['output'];
+ importProgress?: Maybe<Scalars['Int']['output']>;
isContactAutoCreationEnabled: Scalars['Boolean']['output'];
isSyncEnabled: Scalars['Boolean']['output'];
messageFolderImportPolicy: MessageFolderImportPolicy;
@@ -9812,7 +9813,7 @@ export type MyMessageChannelsQueryVariables = Exact<{
}>;
-export type MyMessageChannelsQuery = { __typename?: 'Query', myMessageChannels: Array<{ __typename?: 'MessageChannel', id: string, handle: string, displayName?: string | null, visibility: MessageChannelVisibility, type: MessageChannelType, isContactAutoCreationEnabled: boolean, contactAutoCreationPolicy: MessageChannelContactAutoCreationPolicy, messageFolderImportPolicy: MessageFolderImportPolicy, excludeNonProfessionalEmails: boolean, excludeGroupEmails: boolean, isSyncEnabled: boolean, syncStatus: MessageChannelSyncStatus, syncStage: MessageChannelSyncStage, syncStageStartedAt?: string | null, connectedAccountId: string, createdAt: string, updatedAt: string, connectedAccount?: { __typename?: 'ConnectedAccountPublicDTO', id: string, handle: string } | null }> };
+export type MyMessageChannelsQuery = { __typename?: 'Query', myMessageChannels: Array<{ __typename?: 'MessageChannel', id: string, handle: string, displayName?: string | null, visibility: MessageChannelVisibility, type: MessageChannelType, isContactAutoCreationEnabled: boolean, contactAutoCreationPolicy: MessageChannelContactAutoCreationPolicy, messageFolderImportPolicy: MessageFolderImportPolicy, excludeNonProfessionalEmails: boolean, excludeGroupEmails: boolean, isSyncEnabled: boolean, syncStatus: MessageChannelSyncStatus, syncStage: MessageChannelSyncStage, syncStageStartedAt?: string | null, importProgress?: number | null, connectedAccountId: string, createdAt: string, updatedAt: string, connectedAccount?: { __typename?: 'ConnectedAccountPublicDTO', id: string, handle: string } | null }> };
export type MyMessageFoldersQueryVariables = Exact<{
messageChannelId?: InputMaybe<Scalars['UUID']['input']>;
@@ -11125,7 +11126,7 @@ export const UpdateMessageFoldersDocument = {"kind":"Document","definitions":[{"
export const GetConnectedImapSmtpCaldavAccountDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetConnectedImapSmtpCaldavAccount"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getConnectedImapSmtpCaldavAccount"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"provider"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"connectionParameters"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"IMAP"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"port"}},{"kind":"Field","name":{"kind":"Name","value":"connectionSecurity"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}},{"kind":"Field","name":{"kind":"Name","value":"SMTP"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"username"}},{"kind":"Field","name":{"kind":"Name","value":"port"}},{"kind":"Field","name":{"kind":"Name","value":"connectionSecurity"}}]}},{"kind":"Field","name":{"kind":"Name","value":"CALDAV"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"port"}},{"kind":"Field","name":{"kind":"Name","value":"connectionSecurity"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}}]}}]}}]}}]} as unknown as DocumentNode<GetConnectedImapSmtpCaldavAccountQuery, GetConnectedImapSmtpCaldavAccountQueryVariables>;
export const MyCalendarChannelsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MyCalendarChannels"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"myCalendarChannels"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"connectedAccountId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"syncStatus"}},{"kind":"Field","name":{"kind":"Name","value":"syncStage"}},{"kind":"Field","name":{"kind":"Name","value":"syncStageStartedAt"}},{"kind":"Field","name":{"kind":"Name","value":"isContactAutoCreationEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"contactAutoCreationPolicy"}},{"kind":"Field","name":{"kind":"Name","value":"isSyncEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"connectedAccountId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<MyCalendarChannelsQuery, MyCalendarChannelsQueryVariables>;
export const MyConnectedAccountsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MyConnectedAccounts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"myConnectedAccounts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"provider"}},{"kind":"Field","name":{"kind":"Name","value":"authFailedAt"}},{"kind":"Field","name":{"kind":"Name","value":"authFailedReason"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"scopes"}},{"kind":"Field","name":{"kind":"Name","value":"handleAliases"}},{"kind":"Field","name":{"kind":"Name","value":"lastSignedInAt"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"connectionProviderId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"lastCredentialsRefreshedAt"}},{"kind":"Field","name":{"kind":"Name","value":"connectionParameters"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"IMAP"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"port"}},{"kind":"Field","name":{"kind":"Name","value":"connectionSecurity"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}},{"kind":"Field","name":{"kind":"Name","value":"SMTP"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"port"}},{"kind":"Field","name":{"kind":"Name","value":"connectionSecurity"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}},{"kind":"Field","name":{"kind":"Name","value":"CALDAV"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<MyConnectedAccountsQuery, MyConnectedAccountsQueryVariables>;
-export const MyMessageChannelsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MyMessageChannels"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"myMessageChannels"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"connectedAccountId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"isContactAutoCreationEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"contactAutoCreationPolicy"}},{"kind":"Field","name":{"kind":"Name","value":"messageFolderImportPolicy"}},{"kind":"Field","name":{"kind":"Name","value":"excludeNonProfessionalEmails"}},{"kind":"Field","name":{"kind":"Name","value":"excludeGroupEmails"}},{"kind":"Field","name":{"kind":"Name","value":"isSyncEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"syncStatus"}},{"kind":"Field","name":{"kind":"Name","value":"syncStage"}},{"kind":"Field","name":{"kind":"Name","value":"syncStageStartedAt"}},{"kind":"Field","name":{"kind":"Name","value":"connectedAccountId"}},{"kind":"Field","name":{"kind":"Name","value":"connectedAccount"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}}]}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<MyMessageChannelsQuery, MyMessageChannelsQueryVariables>;
+export const MyMessageChannelsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MyMessageChannels"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"myMessageChannels"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"connectedAccountId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"isContactAutoCreationEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"contactAutoCreationPolicy"}},{"kind":"Field","name":{"kind":"Name","value":"messageFolderImportPolicy"}},{"kind":"Field","name":{"kind":"Name","value":"excludeNonProfessionalEmails"}},{"kind":"Field","name":{"kind":"Name","value":"excludeGroupEmails"}},{"kind":"Field","name":{"kind":"Name","value":"isSyncEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"syncStatus"}},{"kind":"Field","name":{"kind":"Name","value":"syncStage"}},{"kind":"Field","name":{"kind":"Name","value":"syncStageStartedAt"}},{"kind":"Field","name":{"kind":"Name","value":"importProgress"}},{"kind":"Field","name":{"kind":"Name","value":"connectedAccountId"}},{"kind":"Field","name":{"kind":"Name","value":"connectedAccount"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}}]}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<MyMessageChannelsQuery, MyMessageChannelsQueryVariables>;
export const MyMessageFoldersDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MyMessageFolders"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"messageChannelId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"myMessageFolders"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"messageChannelId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"messageChannelId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"isSynced"}},{"kind":"Field","name":{"kind":"Name","value":"isSentFolder"}},{"kind":"Field","name":{"kind":"Name","value":"parentFolderId"}},{"kind":"Field","name":{"kind":"Name","value":"externalId"}},{"kind":"Field","name":{"kind":"Name","value":"pendingSyncAction"}},{"kind":"Field","name":{"kind":"Name","value":"messageChannelId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<MyMessageFoldersQuery, MyMessageFoldersQueryVariables>;
export const ClaimApplicationRegistrationOwnershipDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ClaimApplicationRegistrationOwnership"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"applicationRegistrationId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"claimApplicationRegistrationOwnership"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"applicationRegistrationId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"applicationRegistrationId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}}]} as unknown as DocumentNode<ClaimApplicationRegistrationOwnershipMutation, ClaimApplicationRegistrationOwnershipMutationVariables>;
export const DeleteApplicationRegistrationDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteApplicationRegistration"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteApplicationRegistration"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}]}]}}]} as unknown as DocumentNode<DeleteApplicationRegistrationMutation, DeleteApplicationRegistrationMutationVariables>;
diff --git a/packages/twenty-front/src/modules/accounts/types/MessageChannel.ts b/packages/twenty-front/src/modules/accounts/types/MessageChannel.ts
index 917d295f974..47049d7b3ca 100644
--- a/packages/twenty-front/src/modules/accounts/types/MessageChannel.ts
+++ b/packages/twenty-front/src/modules/accounts/types/MessageChannel.ts
@@ -22,6 +22,7 @@ export type MessageChannel = {
syncStatus: MessageChannelSyncStatus;
syncStage: MessageChannelSyncStage;
syncStageStartedAt: string | null;
+ importProgress: number | null;
connectedAccountId: string;
connectedAccount: {
id: string;
diff --git a/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts b/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts
index f77f3bd79c3..96f9cd4ce09 100644
--- a/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts
+++ b/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts
@@ -4,6 +4,7 @@ import { type AllMetadataName } from 'twenty-shared/metadata';
const ALL_NON_SYNCABLE_BROADCAST_ENTITY_NAME = {
application: 'application',
applicationRegistration: 'applicationRegistration',
+ messageChannel: 'messageChannel',
} as const;
type NonSyncableBroadcastEntityName =
diff --git a/packages/twenty-front/src/modules/settings/accounts/components/SettingsAccountsMessageChannelsSSEEffect.tsx b/packages/twenty-front/src/modules/settings/accounts/components/SettingsAccountsMessageChannelsSSEEffect.tsx
new file mode 100644
index 00000000000..a72316cd3de
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/accounts/components/SettingsAccountsMessageChannelsSSEEffect.tsx
@@ -0,0 +1,26 @@
+import { useListenToBrowserEvent } from '@/browser-event/hooks/useListenToBrowserEvent';
+import { useListenToMetadataOperationBrowserEvent } from '@/browser-event/hooks/useListenToMetadataOperationBrowserEvent';
+import { GET_MY_MESSAGE_CHANNELS } from '@/settings/accounts/graphql/queries/getMyMessageChannels';
+import { useUpdateMessageChannelApolloCache } from '@/settings/accounts/hooks/useUpdateMessageChannelApolloCache';
+import { SSE_CLIENT_RECONNECTED_EVENT_NAME } from '@/sse-db-event/constants/SseClientReconnectedEventName';
+import { useApolloClient } from '@apollo/client/react';
+
+export const SettingsAccountsMessageChannelsSSEEffect = () => {
+ const apolloClient = useApolloClient();
+
+ const { updateMessageChannelApolloCache } =
+ useUpdateMessageChannelApolloCache();
+
+ useListenToMetadataOperationBrowserEvent({
+ metadataName: 'messageChannel',
+ onMetadataOperationBrowserEvent: updateMessageChannelApolloCache,
+ });
+
+ useListenToBrowserEvent({
+ eventName: SSE_CLIENT_RECONNECTED_EVENT_NAME,
+ onBrowserEvent: () =>
+ apolloClient.refetchQueries({ include: [GET_MY_MESSAGE_CHANNELS] }),
+ });
+
+ return null;
+};
diff --git a/packages/twenty-front/src/modules/settings/accounts/graphql/queries/getMyMessageChannels.ts b/packages/twenty-front/src/modules/settings/accounts/graphql/queries/getMyMessageChannels.ts
index bb9de2bfbdf..606ddf93f7f 100644
--- a/packages/twenty-front/src/modules/settings/accounts/graphql/queries/getMyMessageChannels.ts
+++ b/packages/twenty-front/src/modules/settings/accounts/graphql/queries/getMyMessageChannels.ts
@@ -17,6 +17,7 @@ export const GET_MY_MESSAGE_CHANNELS = gql`
syncStatus
syncStage
syncStageStartedAt
+ importProgress
connectedAccountId
connectedAccount {
id
diff --git a/packages/twenty-front/src/modules/settings/accounts/hooks/useUpdateMessageChannelApolloCache.ts b/packages/twenty-front/src/modules/settings/accounts/hooks/useUpdateMessageChannelApolloCache.ts
new file mode 100644
index 00000000000..8b75138bbf1
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/accounts/hooks/useUpdateMessageChannelApolloCache.ts
@@ -0,0 +1,45 @@
+import { type MessageChannel } from '@/accounts/types/MessageChannel';
+import { type MetadataOperationBrowserEventDetail } from '@/browser-event/types/MetadataOperationBrowserEventDetail';
+import { GET_MY_MESSAGE_CHANNELS } from '@/settings/accounts/graphql/queries/getMyMessageChannels';
+import { useApolloClient } from '@apollo/client/react';
+import { isDefined } from 'twenty-shared/utils';
+
+type MessageChannelSyncBroadcastRecord = Pick<
+ MessageChannel,
+ 'id' | 'syncStatus' | 'syncStage' | 'importProgress'
+>;
+
+export const useUpdateMessageChannelApolloCache = () => {
+ const apolloClient = useApolloClient();
+
+ const updateMessageChannelApolloCache = (
+ detail: MetadataOperationBrowserEventDetail<MessageChannelSyncBroadcastRecord>,
+ ) => {
+ if (detail.operation.type !== 'update') {
+ return;
+ }
+
+ const { updatedRecord } = detail.operation;
+
+ apolloClient.cache.updateQuery<{ myMessageChannels: MessageChannel[] }>(
+ { query: GET_MY_MESSAGE_CHANNELS },
+ (existingData) => {
+ if (!isDefined(existingData?.myMessageChannels)) {
+ return existingData;
+ }
+
+ return {
+ ...existingData,
+ myMessageChannels: existingData.myMessageChannels.map(
+ (messageChannel) =>
+ messageChannel.id === updatedRecord.id
+ ? { ...messageChannel, ...updatedRecord }
+ : messageChannel,
+ ),
+ };
+ },
+ );
+ };
+
+ return { updateMessageChannelApolloCache };
+};
diff --git a/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsConnectedAccountSyncStatus.tsx b/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsConnectedAccountSyncStatus.tsx
index 6b3714fa894..af939385959 100644
--- a/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsConnectedAccountSyncStatus.tsx
+++ b/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsConnectedAccountSyncStatus.tsx
@@ -22,9 +22,10 @@ export const SettingsConnectedAccountSyncStatus = ({
return <Status color="gray" weight="medium">{t`Sync paused`}</Status>;
}
- switch (
- computeSyncStatus(account.messageChannels[0], account.calendarChannels[0])
- ) {
+ const messageChannel = account.messageChannels[0];
+ const importProgress = messageChannel?.importProgress;
+
+ switch (computeSyncStatus(messageChannel, account.calendarChannels[0])) {
case SyncStatus.FAILED:
return account.authFailedReason ===
MAIL_SERVER_CERTIFICATE_INVALID_AUTH_FAILED_REASON ? (
@@ -39,7 +40,9 @@ export const SettingsConnectedAccountSyncStatus = ({
case SyncStatus.IMPORTING:
return (
<Status color="turquoise" weight="medium" loading>
- {t`Importing`}
+ {isDefined(importProgress)
+ ? t`Importing ${importProgress}%`
+ : t`Importing`}
</Status>
);
case SyncStatus.PENDING_CONFIGURATION:
diff --git a/packages/twenty-front/src/pages/settings/accounts/SettingsAccounts.tsx b/packages/twenty-front/src/pages/settings/accounts/SettingsAccounts.tsx
index e2244a5a3f5..2d5d492a822 100644
--- a/packages/twenty-front/src/pages/settings/accounts/SettingsAccounts.tsx
+++ b/packages/twenty-front/src/pages/settings/accounts/SettingsAccounts.tsx
@@ -1,4 +1,5 @@
import { SettingsAccountsLegacySections } from '@/settings/accounts/components/SettingsAccountsLegacySections';
+import { SettingsAccountsMessageChannelsSSEEffect } from '@/settings/accounts/components/SettingsAccountsMessageChannelsSSEEffect';
import { SettingsAppPreferencesSections } from '@/settings/app-preferences/components/SettingsAppPreferencesSections';
import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
@@ -27,6 +28,7 @@ export const SettingsAccounts = () => {
{ children: pageTitle },
]}
>
+ <SettingsAccountsMessageChannelsSSEEffect />
<SettingsPageContainer>
{isAppPreferencesEnabled ? (
<SettingsAppPreferencesSections />
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 24d9cc93c17..d88a8ac378f 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 { 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';
@@ -28,6 +29,7 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
PermissionsModule,
ConnectedAccountMetadataModule,
MessagingImportManagerModule,
+ MessagingCommonModule,
EmailingDomainModule,
],
providers: [
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.service.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.service.ts
index 88921fe539c..dc2636d1919 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.service.ts
@@ -34,6 +34,7 @@ import { type MessageChannelDeletedEvent } from 'src/engine/metadata-modules/mes
import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
import { INBOUND_EMAIL_LOCAL_PART_PREFIX } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/constants/inbound-email-local-part-prefix.constant';
import { INBOUND_EMAIL_LOCAL_PART_RANDOM_BYTES } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/constants/inbound-email-local-part-random-bytes.constant';
+import { MessageChannelSyncStatusService } from 'src/modules/messaging/common/services/message-channel-sync-status.service';
import { getDomainFromEmail } from 'src/utils/get-domain-from-email';
@Injectable()
@@ -45,8 +46,22 @@ export class MessageChannelMetadataService {
private readonly twentyConfigService: TwentyConfigService,
private readonly emailingDomainService: EmailingDomainService,
private readonly workspaceEventEmitter: WorkspaceEventEmitter,
+ private readonly messageChannelSyncStatusService: MessageChannelSyncStatusService,
) {}
+ async getImportProgress({
+ messageChannelId,
+ workspaceId,
+ }: {
+ messageChannelId: string;
+ workspaceId: string;
+ }): Promise<number | null> {
+ return this.messageChannelSyncStatusService.getImportProgress({
+ messageChannelId,
+ workspaceId,
+ });
+ }
+
async findAll(workspaceId: string): Promise<MessageChannelDTO[]> {
return this.repository.find({ where: { workspaceId } });
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/message-channel.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/message-channel.resolver.ts
index 06b7f04a51c..d0367799573 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/message-channel.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/message-channel.resolver.ts
@@ -1,5 +1,12 @@
import { UseGuards, UseInterceptors, UseFilters } from '@nestjs/common';
-import { Args, Mutation, Parent, Query, ResolveField } from '@nestjs/graphql';
+import {
+ Args,
+ Int,
+ Mutation,
+ Parent,
+ Query,
+ ResolveField,
+} from '@nestjs/graphql';
import { PermissionFlagType } from 'twenty-shared/constants';
import { isDefined } from 'twenty-shared/utils';
@@ -72,6 +79,17 @@ export class MessageChannelResolver {
private readonly messagingProcessGroupEmailActionsService: MessagingProcessGroupEmailActionsService,
) {}
+ @ResolveField('importProgress', () => Int, { nullable: true })
+ async importProgress(
+ @Parent() messageChannel: MessageChannelDTO,
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ ): Promise<number | null> {
+ return this.messageChannelMetadataService.getImportProgress({
+ messageChannelId: messageChannel.id,
+ workspaceId: workspace.id,
+ });
+ }
+
@ResolveField('connectedAccount', () => ConnectedAccountPublicDTO, {
nullable: true,
})
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/compute-message-import-progress.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/compute-message-import-progress.util.spec.ts
new file mode 100644
index 00000000000..4c4811a6969
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/compute-message-import-progress.util.spec.ts
@@ -0,0 +1,48 @@
+import { computeMessageImportProgress } from 'src/engine/metadata-modules/message-channel/utils/compute-message-import-progress.util';
+
+describe('computeMessageImportProgress', () => {
+ it('has no progress before a total is known', () => {
+ expect(
+ computeMessageImportProgress({
+ importedMessagesCount: 50,
+ totalMessagesToImportCount: undefined,
+ }),
+ ).toBeNull();
+ });
+
+ it('has no progress when there is nothing to import', () => {
+ expect(
+ computeMessageImportProgress({
+ importedMessagesCount: 0,
+ totalMessagesToImportCount: 0,
+ }),
+ ).toBeNull();
+ });
+
+ it('starts at zero before the first batch is saved', () => {
+ expect(
+ computeMessageImportProgress({
+ importedMessagesCount: undefined,
+ totalMessagesToImportCount: 445,
+ }),
+ ).toBe(0);
+ });
+
+ it('rounds down so an unfinished import never shows 100', () => {
+ expect(
+ computeMessageImportProgress({
+ importedMessagesCount: 444,
+ totalMessagesToImportCount: 445,
+ }),
+ ).toBe(99);
+ });
+
+ it('caps at 100 when more messages were imported than counted', () => {
+ expect(
+ computeMessageImportProgress({
+ importedMessagesCount: 460,
+ totalMessagesToImportCount: 445,
+ }),
+ ).toBe(100);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/compute-message-import-progress.util.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/compute-message-import-progress.util.ts
new file mode 100644
index 00000000000..60404c29785
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/compute-message-import-progress.util.ts
@@ -0,0 +1,25 @@
+import { isDefined } from 'twenty-shared/utils';
+
+export const computeMessageImportProgress = ({
+ importedMessagesCount,
+ totalMessagesToImportCount,
+}: {
+ importedMessagesCount: number | undefined;
+ totalMessagesToImportCount: number | undefined;
+}): number | null => {
+ if (
+ !isDefined(totalMessagesToImportCount) ||
+ totalMessagesToImportCount === 0
+ ) {
+ return null;
+ }
+
+ const cappedImportedMessagesCount = Math.min(
+ importedMessagesCount ?? 0,
+ totalMessagesToImportCount,
+ );
+
+ return Math.floor(
+ (cappedImportedMessagesCount / totalMessagesToImportCount) * 100,
+ );
+};
diff --git a/packages/twenty-server/src/modules/messaging/common/services/message-channel-sync-status.service.ts b/packages/twenty-server/src/modules/messaging/common/services/message-channel-sync-status.service.ts
index 2e73dad8fc0..08b6c3a19ef 100644
--- a/packages/twenty-server/src/modules/messaging/common/services/message-channel-sync-status.service.ts
+++ b/packages/twenty-server/src/modules/messaging/common/services/message-channel-sync-status.service.ts
@@ -2,6 +2,7 @@ import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Any, In, Repository } from 'typeorm';
+import { type QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import {
MessageChannelPendingGroupEmailsAction,
@@ -25,6 +26,14 @@ import { AccountsToReconnectKeys } from 'src/modules/connected-account/types/acc
import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+import { type WorkspaceBroadcastEvent } from 'src/engine/subscriptions/workspace-event-broadcaster/types/workspace-broadcast-event.type';
+import { WorkspaceEventBroadcaster } from 'src/engine/subscriptions/workspace-event-broadcaster/workspace-event-broadcaster.service';
+import { computeMessageImportProgress } from 'src/engine/metadata-modules/message-channel/utils/compute-message-import-progress.util';
+
+type UpdatedMessageChannel = Pick<
+ MessageChannelEntity,
+ 'id' | 'syncStatus' | 'syncStage'
+> & { userWorkspaceId: string };
@Injectable()
export class MessageChannelSyncStatusService {
@@ -44,6 +53,7 @@ export class MessageChannelSyncStatusService {
private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
private readonly accountsToReconnectService: AccountsToReconnectService,
private readonly metricsService: MetricsService,
+ private readonly workspaceEventBroadcaster: WorkspaceEventBroadcaster,
) {}
public async markAsMessagesListFetchPending(
@@ -55,23 +65,10 @@ export class MessageChannelSyncStatusService {
return;
}
- const authContext = buildSystemAuthContext(workspaceId);
-
- await this.workspaceOrmManager.executeInWorkspaceContext(
- async () => {
- await this.messageChannelRepository.update(
- { id: In(messageChannelIds), workspaceId },
- {
- syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
- ...(!preserveSyncStageStartedAt
- ? { syncStageStartedAt: null }
- : {}),
- },
- );
- },
- authContext,
- { lite: true },
- );
+ await this.updateMessageChannels(messageChannelIds, workspaceId, {
+ syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
+ ...(!preserveSyncStageStartedAt ? { syncStageStartedAt: null } : {}),
+ });
}
public async markAsMessagesImportPending(
@@ -83,23 +80,10 @@ export class MessageChannelSyncStatusService {
return;
}
- const authContext = buildSystemAuthContext(workspaceId);
-
- await this.workspaceOrmManager.executeInWorkspaceContext(
- async () => {
- await this.messageChannelRepository.update(
- { id: In(messageChannelIds), workspaceId },
- {
- syncStage: MessageChannelSyncStage.MESSAGES_IMPORT_PENDING,
- ...(!preserveSyncStageStartedAt
- ? { syncStageStartedAt: null }
- : {}),
- },
- );
- },
- authContext,
- { lite: true },
- );
+ await this.updateMessageChannels(messageChannelIds, workspaceId, {
+ syncStage: MessageChannelSyncStage.MESSAGES_IMPORT_PENDING,
+ ...(!preserveSyncStageStartedAt ? { syncStageStartedAt: null } : {}),
+ });
}
public async resetAndMarkAsMessagesListFetchPending(
@@ -111,9 +95,11 @@ export class MessageChannelSyncStatusService {
}
for (const messageChannelId of messageChannelIds) {
- await this.cacheStorage.del(
+ await this.cacheStorage.mdel([
`messages-to-import:${workspaceId}:${messageChannelId}`,
- );
+ `messages-to-import-total:${workspaceId}:${messageChannelId}`,
+ `messages-imported:${workspaceId}:${messageChannelId}`,
+ ]);
}
const authContext = buildSystemAuthContext(workspaceId);
@@ -178,22 +164,11 @@ export class MessageChannelSyncStatusService {
return;
}
- const authContext = buildSystemAuthContext(workspaceId);
-
- await this.workspaceOrmManager.executeInWorkspaceContext(
- async () => {
- await this.messageChannelRepository.update(
- { id: In(messageChannelIds), workspaceId },
- {
- syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_SCHEDULED,
- syncStatus: MessageChannelSyncStatus.ONGOING,
- syncStageStartedAt: new Date().toISOString(),
- },
- );
- },
- authContext,
- { lite: true },
- );
+ await this.updateMessageChannels(messageChannelIds, workspaceId, {
+ syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_SCHEDULED,
+ syncStatus: MessageChannelSyncStatus.ONGOING,
+ syncStageStartedAt: new Date().toISOString(),
+ });
}
public async markAsMessagesListFetchScheduledIfPending(
@@ -231,22 +206,11 @@ export class MessageChannelSyncStatusService {
return;
}
- const authContext = buildSystemAuthContext(workspaceId);
-
- await this.workspaceOrmManager.executeInWorkspaceContext(
- async () => {
- await this.messageChannelRepository.update(
- { id: In(messageChannelIds), workspaceId },
- {
- syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_ONGOING,
- syncStatus: MessageChannelSyncStatus.ONGOING,
- syncStageStartedAt: new Date().toISOString(),
- },
- );
- },
- authContext,
- { lite: true },
- );
+ await this.updateMessageChannels(messageChannelIds, workspaceId, {
+ syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_ONGOING,
+ syncStatus: MessageChannelSyncStatus.ONGOING,
+ syncStageStartedAt: new Date().toISOString(),
+ });
}
public async markAsMessageSyncCompleted(
@@ -257,25 +221,16 @@ export class MessageChannelSyncStatusService {
return;
}
- const authContext = buildSystemAuthContext(workspaceId);
+ await this.clearImportProgress(messageChannelIds, workspaceId);
- await this.workspaceOrmManager.executeInWorkspaceContext(
- async () => {
- await this.messageChannelRepository.update(
- { id: In(messageChannelIds), workspaceId },
- {
- syncStatus: MessageChannelSyncStatus.ACTIVE,
- syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
- throttleFailureCount: 0,
- throttleRetryAfter: null,
- syncStageStartedAt: null,
- syncedAt: new Date().toISOString(),
- },
- );
- },
- authContext,
- { lite: true },
- );
+ await this.updateMessageChannels(messageChannelIds, workspaceId, {
+ syncStatus: MessageChannelSyncStatus.ACTIVE,
+ syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
+ throttleFailureCount: 0,
+ throttleRetryAfter: null,
+ syncStageStartedAt: null,
+ syncedAt: new Date().toISOString(),
+ });
await this.metricsService.incrementCounterForEvents({
key: MetricsKeys.MessageChannelSyncJobActive,
@@ -291,20 +246,9 @@ export class MessageChannelSyncStatusService {
return;
}
- const authContext = buildSystemAuthContext(workspaceId);
-
- await this.workspaceOrmManager.executeInWorkspaceContext(
- async () => {
- await this.messageChannelRepository.update(
- { id: In(messageChannelIds), workspaceId },
- {
- syncStage: MessageChannelSyncStage.MESSAGES_IMPORT_SCHEDULED,
- },
- );
- },
- authContext,
- { lite: true },
- );
+ await this.updateMessageChannels(messageChannelIds, workspaceId, {
+ syncStage: MessageChannelSyncStage.MESSAGES_IMPORT_SCHEDULED,
+ });
}
public async markAsMessagesImportOngoing(
@@ -315,22 +259,11 @@ export class MessageChannelSyncStatusService {
return;
}
- const authContext = buildSystemAuthContext(workspaceId);
-
- await this.workspaceOrmManager.executeInWorkspaceContext(
- async () => {
- await this.messageChannelRepository.update(
- { id: In(messageChannelIds), workspaceId },
- {
- syncStage: MessageChannelSyncStage.MESSAGES_IMPORT_ONGOING,
- syncStatus: MessageChannelSyncStatus.ONGOING,
- syncStageStartedAt: new Date().toISOString(),
- },
- );
- },
- authContext,
- { lite: true },
- );
+ await this.updateMessageChannels(messageChannelIds, workspaceId, {
+ syncStage: MessageChannelSyncStage.MESSAGES_IMPORT_ONGOING,
+ syncStatus: MessageChannelSyncStatus.ONGOING,
+ syncStageStartedAt: new Date().toISOString(),
+ });
}
public async markAsFailed({
@@ -354,19 +287,18 @@ export class MessageChannelSyncStatusService {
`Marking message channels [${messageChannelIds.join(', ')}] as ${syncStatus} in workspace ${workspaceId}`,
);
+ await this.clearImportProgress(messageChannelIds, workspaceId);
+
+ await this.updateMessageChannels(messageChannelIds, workspaceId, {
+ syncStage: MessageChannelSyncStage.FAILED,
+ syncStatus: syncStatus,
+ throttleRetryAfter: null,
+ });
+
const authContext = buildSystemAuthContext(workspaceId);
await this.workspaceOrmManager.executeInWorkspaceContext(
async () => {
- await this.messageChannelRepository.update(
- { id: In(messageChannelIds), workspaceId },
- {
- syncStage: MessageChannelSyncStage.FAILED,
- syncStatus: syncStatus,
- throttleRetryAfter: null,
- },
- );
-
const metricsKey =
syncStatus ===
MessageChannelSyncStatus.FAILED_INSUFFICIENT_PERMISSIONS
@@ -409,6 +341,105 @@ export class MessageChannelSyncStatusService {
);
}
+ public async getImportProgress({
+ messageChannelId,
+ workspaceId,
+ }: {
+ messageChannelId: string;
+ workspaceId: string;
+ }): Promise<number | null> {
+ const [totalMessagesToImportCount, importedMessagesCount] =
+ await this.cacheStorage.mget<number>([
+ `messages-to-import-total:${workspaceId}:${messageChannelId}`,
+ `messages-imported:${workspaceId}:${messageChannelId}`,
+ ]);
+
+ return computeMessageImportProgress({
+ importedMessagesCount,
+ totalMessagesToImportCount,
+ });
+ }
+
+ private async clearImportProgress(
+ messageChannelIds: string[],
+ workspaceId: string,
+ ) {
+ await this.cacheStorage.mdel(
+ messageChannelIds.flatMap((messageChannelId) => [
+ `messages-to-import-total:${workspaceId}:${messageChannelId}`,
+ `messages-imported:${workspaceId}:${messageChannelId}`,
+ ]),
+ );
+ }
+
+ private async updateMessageChannels(
+ messageChannelIds: string[],
+ workspaceId: string,
+ values: QueryDeepPartialEntity<MessageChannelEntity>,
+ ) {
+ const authContext = buildSystemAuthContext(workspaceId);
+
+ const updatedMessageChannels =
+ await this.workspaceOrmManager.executeInWorkspaceContext(
+ async () => {
+ const updateResult = await this.messageChannelRepository
+ .createQueryBuilder()
+ .update()
+ .set(values)
+ .where({ id: In(messageChannelIds), workspaceId })
+ .returning(
+ `id, "syncStatus", "syncStage", (SELECT "userWorkspaceId" FROM core."connectedAccount" WHERE core."connectedAccount".id = "messageChannel"."connectedAccountId") AS "userWorkspaceId"`,
+ )
+ .execute();
+
+ return updateResult.raw as UpdatedMessageChannel[];
+ },
+ authContext,
+ { lite: true },
+ );
+
+ await this.broadcastMessageChannelsUpdated(
+ updatedMessageChannels,
+ workspaceId,
+ );
+ }
+
+ private async broadcastMessageChannelsUpdated(
+ updatedMessageChannels: UpdatedMessageChannel[],
+ workspaceId: string,
+ ): Promise<void> {
+ try {
+ const events: WorkspaceBroadcastEvent[] = await Promise.all(
+ updatedMessageChannels.map(
+ async ({ id, syncStatus, syncStage, userWorkspaceId }) => ({
+ type: 'updated',
+ entityName: 'messageChannel',
+ recordId: id,
+ properties: {
+ after: {
+ id,
+ syncStatus,
+ syncStage,
+ importProgress: await this.getImportProgress({
+ messageChannelId: id,
+ workspaceId,
+ }),
+ },
+ },
+ recipientUserWorkspaceIds: [userWorkspaceId],
+ }),
+ ),
+ );
+
+ await this.workspaceEventBroadcaster.broadcast({ workspaceId, events });
+ } catch (error) {
+ this.logger.warn(
+ `Failed to broadcast updated event for message channels [${updatedMessageChannels.map(({ id }) => id).join(', ')}] in workspace ${workspaceId}`,
+ error,
+ );
+ }
+ }
+
private async addToAccountsToReconnect(
messageChannelIds: string[],
workspaceId: string,
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/jobs/messaging-clean-cache.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/jobs/messaging-clean-cache.ts
index 028c44e6fc4..16e0bf39b9c 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/jobs/messaging-clean-cache.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/jobs/messaging-clean-cache.ts
@@ -19,8 +19,10 @@ export class MessagingCleanCacheJob {
@Process(MessagingCleanCacheJob.name)
async handle(data: MessagingCleanCacheJobData): Promise<void> {
- await this.cacheStorage.del(
+ await this.cacheStorage.mdel([
`messages-to-import:${data.workspaceId}:${data.messageChannelId}`,
- );
+ `messages-to-import-total:${data.workspaceId}:${data.messageChannelId}`,
+ `messages-imported:${data.workspaceId}:${data.messageChannelId}`,
+ ]);
}
}
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-message-list-fetch.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-message-list-fetch.service.ts
index 374fae27ec9..2af0206d27c 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-message-list-fetch.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-message-list-fetch.service.ts
@@ -121,9 +121,11 @@ export class MessagingMessageListFetchService {
messageFoldersToSync,
);
- await this.cacheStorage.del(
+ await this.cacheStorage.mdel([
`messages-to-import:${workspaceId}:${freshMessageChannel.id}`,
- );
+ `messages-to-import-total:${workspaceId}:${freshMessageChannel.id}`,
+ `messages-imported:${workspaceId}:${freshMessageChannel.id}`,
+ ]);
const messageExternalIds = [
...messageLists.flatMap(
@@ -261,6 +263,19 @@ export class MessagingMessageListFetchService {
return;
}
+ await this.cacheStorage.set(
+ `messages-to-import-total:${workspaceId}:${freshMessageChannel.id}`,
+ await this.cacheStorage.getSetLength(
+ `messages-to-import:${workspaceId}:${freshMessageChannel.id}`,
+ ),
+ ONE_WEEK_IN_MILLISECONDS,
+ );
+ await this.cacheStorage.set(
+ `messages-imported:${workspaceId}:${freshMessageChannel.id}`,
+ 0,
+ ONE_WEEK_IN_MILLISECONDS,
+ );
+
this.logger.debug(
`messageChannelId: ${freshMessageChannel.id} Scheduling direct messages import`,
);
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 60f369b1bb4..67c38d234c6 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
@@ -210,7 +210,9 @@ export class MessagingMessagesImportService {
);
}
- if (messageIdsToFetch.length < messagesGetBatchSize) {
+ const isLastBatch = messageIdsToFetch.length < messagesGetBatchSize;
+
+ if (isLastBatch) {
await this.messageChannelSyncStatusService.markAsMessageSyncCompleted(
[messageChannel.id],
workspaceId,
@@ -231,6 +233,13 @@ export class MessagingMessagesImportService {
},
);
+ if (!isLastBatch) {
+ await this.cacheStorage.incrBy(
+ `messages-imported:${workspaceId}:${messageChannel.id}`,
+ messageIdsToFetch.length,
+ );
+ }
+
return await this.trackMessageImportCompleted(
messageChannel,
workspaceId,