The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Make Disconnect and Delete act on the whole account group (#29015)
nitinfe20aef8ea51
diff --git a/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAccountGroupActionTargetList.tsx b/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAccountGroupActionTargetList.tsxnew file mode 100644index 00000000000..437303c9dcc--- /dev/null+++ b/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAccountGroupActionTargetList.tsx@@ -0,0 +1,26 @@+import { type AccountGroupActionTarget } from '@/settings/app-preferences/types/AccountGroupActionTarget';+import { styled } from '@linaria/react';+import { themeCssVariables } from 'twenty-ui/theme';++const StyledList = styled.ul`+ margin: ${themeCssVariables.spacing[2]} 0 0;+ padding-left: ${themeCssVariables.spacing[4]};+`;++type SettingsAccountGroupActionTargetListProps = {+ targets: AccountGroupActionTarget[];+};++export const SettingsAccountGroupActionTargetList = ({+ targets,+}: SettingsAccountGroupActionTargetListProps) => {+ const labels = [...new Set(targets.map(({ label }) => label))];++ return (+ <StyledList>+ {labels.map((label) => (+ <li key={label}>{label}</li>+ ))}+ </StyledList>+ );+};diff --git a/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAccountGroupTableRow.tsx b/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAccountGroupTableRow.tsxindex 889b76dd352..5e974363b2b 100644--- a/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAccountGroupTableRow.tsx+++ b/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAccountGroupTableRow.tsx@@ -110,9 +110,11 @@ export const SettingsAccountGroupTableRow = ({{isDefined(builtInAccountApp) && shouldShowSyncStatus && (<SettingsConnectedAccountSyncStatus account={builtInAccount} />)}- {isDefined(builtInAccount) && (- <SettingsAppPreferencesRowDropdownMenu account={builtInAccount} />- )}+ <SettingsAppPreferencesRowDropdownMenu+ group={group}+ hasAccountSettings={hasSettings}+ builtInAccountApp={builtInAccountApp}+ /></TableCell></TableRow>);diff --git a/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAccountGroupUsedBy.tsx b/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAccountGroupUsedBy.tsxindex fb24bb5f727..b9422bf1c09 100644--- a/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAccountGroupUsedBy.tsx+++ b/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAccountGroupUsedBy.tsx@@ -1,8 +1,8 @@import { AppChip } from '@/applications/components/AppChip';-import { getApplicationDisplayName } from '@/applications/utils/getApplicationDisplayName';import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import { type ConnectedAccountGroup } from '@/settings/app-preferences/types/ConnectedAccountGroup';import { getBuiltInAccountAppsUsingAccount } from '@/settings/app-preferences/utils/getBuiltInAccountAppsUsingAccount';+import { getInstalledApplicationDisplayName } from '@/settings/app-preferences/utils/getInstalledApplicationDisplayName';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { styled } from '@linaria/react';import { useLingui } from '@lingui/react/macro';@@ -50,19 +50,14 @@ export const SettingsAccountGroupUsedBy = ({group.appAccounts.map((account) => account.applicationId).filter(isDefined),);- const appUsages = [...applicationIds].map((applicationId): Usage => {- const application = currentWorkspace?.installedApplications.find(- (installedApplication) => installedApplication.id === applicationId,- );-- return {- key: applicationId,- title: isDefined(application)- ? getApplicationDisplayName({ application, currentWorkspace })- : t`Application`,- icon: <AppChip applicationId={applicationId} chipOnly />,- };- });+ const appUsages = [...applicationIds].map((applicationId): Usage => ({+ key: applicationId,+ title: getInstalledApplicationDisplayName({+ applicationId,+ currentWorkspace,+ }),+ icon: <AppChip applicationId={applicationId} chipOnly />,+ }));return (<StyledUsedBy>diff --git a/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAppPreferencesRowDropdownMenu.tsx b/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAppPreferencesRowDropdownMenu.tsxindex e38a28202ad..6420ccad093 100644--- a/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAppPreferencesRowDropdownMenu.tsx+++ b/packages/twenty-front/src/modules/settings/app-preferences/components/SettingsAppPreferencesRowDropdownMenu.tsx@@ -1,18 +1,27 @@import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';-import { type ConnectedAccount } from '@/accounts/types/ConnectedAccount';-import { useApolloClient, useMutation } from '@apollo/client/react';+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import {CalendarChannelSyncStage,ConnectedAccountProvider,MessageChannelSyncStage,SettingsPath,} from 'twenty-shared/types';-import { getSettingsPath, isDefined } from 'twenty-shared/utils';+import {+ getSettingsPath,+ isDefined,+ isNonEmptyArray,+} from 'twenty-shared/utils';import { useTriggerProviderReconnect } from '@/settings/accounts/hooks/useTriggerProviderReconnect';+import { SettingsAccountGroupActionTargetList } from '@/settings/app-preferences/components/SettingsAccountGroupActionTargetList';+import { useRunAccountGroupAction } from '@/settings/app-preferences/hooks/useRunAccountGroupAction';+import { type BuiltInAccountApp } from '@/settings/app-preferences/types/BuiltInAccountApp';+import { type ConnectedAccountGroup } from '@/settings/app-preferences/types/ConnectedAccountGroup';+import { getAccountGroupActionTargets } from '@/settings/app-preferences/utils/getAccountGroupActionTargets';import { ConfirmationDialog } from '@/ui/layout/dialog/components/ConfirmationDialog';import { useDialog } from '@/ui/layout/dialog/hooks/useDialog';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { Trans, useLingui } from '@lingui/react/macro';import {IconAt,@@ -25,61 +34,52 @@ import {import { LightIconButton } from 'twenty-ui/components/input';import { Dropdown } from 'twenty-ui/components/navigation';import { Link, useLocation } from 'react-router-dom';-import { DELETE_CONNECTED_ACCOUNT } from '@/settings/accounts/graphql/mutations/deleteConnectedAccount';-import { DISCONNECT_CONNECTED_ACCOUNT } from '@/settings/accounts/graphql/mutations/disconnectConnectedAccount';import { isConnectedAccountEligibleForProviderReconnect } from '@/settings/accounts/utils/isConnectedAccountEligibleForProviderReconnect';type SettingsAppPreferencesRowDropdownMenuProps = {- account: ConnectedAccount;+ group: ConnectedAccountGroup;+ hasAccountSettings: boolean;+ builtInAccountApp?: BuiltInAccountApp;};export const SettingsAppPreferencesRowDropdownMenu = ({- account,+ group,+ hasAccountSettings,+ builtInAccountApp,}: SettingsAppPreferencesRowDropdownMenuProps) => {- const dropdownId = `settings-account-row-${account.id}`;- const deleteAccountModalId = `delete-account-modal-${account.id}`;- const disconnectAccountModalId = `disconnect-account-modal-${account.id}`;- const accountHandle = account.handle;+ const { builtInAccount } = group;+ const dropdownId = `settings-account-row-${group.id}`;+ const deleteAccountModalId = `delete-account-modal-${group.id}`;+ const disconnectAccountModalId = `disconnect-account-modal-${group.id}`;const { t } = useLingui();const { openDialog } = useDialog();-- const apolloClient = useApolloClient();- const [deleteConnectedAccountMutation] = useMutation(- DELETE_CONNECTED_ACCOUNT,- );- const [disconnectConnectedAccountMutation] = useMutation(- DISCONNECT_CONNECTED_ACCOUNT,- );+ const currentWorkspace = useAtomStateValue(currentWorkspaceState);+ const { runAccountGroupAction } = useRunAccountGroupAction();const { triggerProviderReconnect } = useTriggerProviderReconnect();const { pathname, hash } = useLocation();+ const disconnectTargets = getAccountGroupActionTargets({+ group,+ action: 'disconnect',+ currentWorkspace,+ });+ const deleteTargets = getAccountGroupActionTargets({+ group,+ action: 'delete',+ currentWorkspace,+ });+const hasPendingConfiguration =- account.messageChannels.some(+ isDefined(builtInAccount) &&+ (builtInAccount.messageChannels.some((channel) =>channel.syncStage === MessageChannelSyncStage.PENDING_CONFIGURATION,) ||- account.calendarChannels.some(- (channel) =>- channel.syncStage === CalendarChannelSyncStage.PENDING_CONFIGURATION,- );-- const isEligibleForProviderReconnect =- isConnectedAccountEligibleForProviderReconnect(account);-- const deleteAccount = async () => {- await deleteConnectedAccountMutation({- variables: { id: account.id },- });- await apolloClient.refetchQueries({ include: 'active' });- };-- const disconnectAccount = async () => {- await disconnectConnectedAccountMutation({- variables: { id: account.id },- });- await apolloClient.refetchQueries({ include: 'active' });- };+ builtInAccount.calendarChannels.some(+ (channel) =>+ channel.syncStage === CalendarChannelSyncStage.PENDING_CONFIGURATION,+ ));return (<>@@ -93,45 +93,67 @@ export const SettingsAppPreferencesRowDropdownMenu = ({/><DropdownContent side="right" align="start"><Dropdown.Section>- {hasPendingConfiguration && (+ {hasAccountSettings && (<Dropdown.ActionItem- startIcon={<IconPlayerPlay />}+ startIcon={<IconAt />}render={<Link- to={getSettingsPath(SettingsPath.AccountsConfiguration, {- connectedAccountId: account.id,+ to={getSettingsPath(SettingsPath.AccountDetail, {+ connectedAccountId: group.id,})}/>}- >{t`Complete setup`}</Dropdown.ActionItem>+ >{t`Account settings`}</Dropdown.ActionItem>)}- {account.provider === ConnectedAccountProvider.IMAP_SMTP_CALDAV && (+ {hasPendingConfiguration && (<Dropdown.ActionItem- startIcon={<IconAt />}+ startIcon={<IconPlayerPlay />}render={<Link- to={getSettingsPath(- SettingsPath.EditImapSmtpCaldavConnection,- {- connectedAccountId: account.id,- },- )}+ to={getSettingsPath(SettingsPath.AccountsConfiguration, {+ connectedAccountId: builtInAccount.id,+ })}/>}- >{t`Connection settings`}</Dropdown.ActionItem>- )}- {isEligibleForProviderReconnect && (- <Dropdown.ActionItem- startIcon={<IconRefresh />}- onClick={() => {- triggerProviderReconnect(account.provider, account.id, {- loginHint: account.handle,- redirectLocation: `${pathname}${hash}`,- });- }}- >{t`Reconnect`}</Dropdown.ActionItem>+ >{t`Complete setup`}</Dropdown.ActionItem>)}- {!isDefined(account.archivedAt) && (+ {isDefined(builtInAccount) &&+ builtInAccount.provider ===+ ConnectedAccountProvider.IMAP_SMTP_CALDAV && (+ <Dropdown.ActionItem+ startIcon={<IconAt />}+ render={+ <Link+ to={getSettingsPath(+ SettingsPath.EditImapSmtpCaldavConnection,+ {+ connectedAccountId: builtInAccount.id,+ },+ )}+ />+ }+ >{t`Connection settings`}</Dropdown.ActionItem>+ )}+ {isDefined(builtInAccountApp) &&+ isDefined(builtInAccount) &&+ isConnectedAccountEligibleForProviderReconnect(+ builtInAccount,+ ) && (+ <Dropdown.ActionItem+ startIcon={<IconRefresh />}+ onClick={() => {+ triggerProviderReconnect(+ builtInAccount.provider,+ builtInAccount.id,+ {+ loginHint: builtInAccount.handle,+ redirectLocation: `${pathname}${hash}`,+ },+ );+ }}+ >{t`Reconnect`}</Dropdown.ActionItem>+ )}+ {isNonEmptyArray(disconnectTargets) && (<Dropdown.ActionItemstartIcon={<IconUnlink />}onClick={() => {@@ -153,26 +175,41 @@ export const SettingsAppPreferencesRowDropdownMenu = ({dialogId={disconnectAccountModalId}title={t`Disconnect account`}subtitle={- <Trans>- Syncing will stop and this account's credentials will be removed.- Your emails and events will be retained and available after you- reconnect.- </Trans>+ <>+ <Trans>+ Syncing will stop and credentials will be removed for the+ following. Your emails and events will be retained and available+ after you reconnect.+ </Trans>+ <SettingsAccountGroupActionTargetList targets={disconnectTargets} />+ </>+ }+ onConfirmClick={() =>+ runAccountGroupAction({+ action: 'disconnect',+ targets: disconnectTargets,+ })}- onConfirmClick={disconnectAccount}confirmButtonText={t`Disconnect account`}+ shouldWaitForConfirmBeforeClosing/><ConfirmationDialogdialogId={deleteAccountModalId}title={t`Delete account and synced data?`}subtitle={- <Trans>- This permanently deletes {accountHandle} and all of its synced- emails and events. This action cannot be undone.- </Trans>+ <>+ <Trans>+ This permanently deletes the following and all of their synced+ emails and events. This action cannot be undone.+ </Trans>+ <SettingsAccountGroupActionTargetList targets={deleteTargets} />+ </>+ }+ onConfirmClick={() =>+ runAccountGroupAction({ action: 'delete', targets: deleteTargets })}- onConfirmClick={deleteAccount}confirmButtonText={t`Delete account and data`}+ shouldWaitForConfirmBeforeClosing/></>);diff --git a/packages/twenty-front/src/modules/settings/app-preferences/hooks/useRunAccountGroupAction.ts b/packages/twenty-front/src/modules/settings/app-preferences/hooks/useRunAccountGroupAction.tsnew file mode 100644index 00000000000..4c2bcfe2e4d--- /dev/null+++ b/packages/twenty-front/src/modules/settings/app-preferences/hooks/useRunAccountGroupAction.ts@@ -0,0 +1,53 @@+import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';+import { DELETE_CONNECTED_ACCOUNT } from '@/settings/accounts/graphql/mutations/deleteConnectedAccount';+import { DISCONNECT_CONNECTED_ACCOUNT } from '@/settings/accounts/graphql/mutations/disconnectConnectedAccount';+import { type AccountGroupAction } from '@/settings/app-preferences/types/AccountGroupAction';+import { type AccountGroupActionTarget } from '@/settings/app-preferences/types/AccountGroupActionTarget';+import { getAccountGroupActionFailureMessage } from '@/settings/app-preferences/utils/getAccountGroupActionFailureMessage';+import { useApolloClient, useMutation } from '@apollo/client/react';+import { isDefined } from 'twenty-shared/utils';+import { useToast } from 'twenty-ui/components/feedback';++export const useRunAccountGroupAction = () => {+ const { enqueueToast } = useToast();+ const apolloClient = useApolloClient();+ const [deleteConnectedAccount] = useMutation(DELETE_CONNECTED_ACCOUNT);+ const [disconnectConnectedAccount] = useMutation(+ DISCONNECT_CONNECTED_ACCOUNT,+ );++ const runAccountGroupAction = async ({+ action,+ targets,+ }: {+ action: AccountGroupAction;+ targets: AccountGroupActionTarget[];+ }) => {+ const mutation =+ action === 'disconnect'+ ? disconnectConnectedAccount+ : deleteConnectedAccount;++ const results = await Promise.allSettled(+ targets.map(({ id }) => mutation({ variables: { id } })),+ );++ const failureMessage = getAccountGroupActionFailureMessage({+ action,+ targets,+ results,+ });++ if (isDefined(failureMessage)) {+ enqueueToast({ status: 'error', children: failureMessage });+ }++ try {+ await apolloClient.refetchQueries({ include: 'active' });+ } catch (error) {+ enqueueToast(getToastOptionsFromError({ error }));+ }+ };++ return { runAccountGroupAction };+};diff --git a/packages/twenty-front/src/modules/settings/app-preferences/types/AccountGroupAction.ts b/packages/twenty-front/src/modules/settings/app-preferences/types/AccountGroupAction.tsnew file mode 100644index 00000000000..6d43c2ed3b4--- /dev/null+++ b/packages/twenty-front/src/modules/settings/app-preferences/types/AccountGroupAction.ts@@ -0,0 +1 @@+export type AccountGroupAction = 'disconnect' | 'delete';diff --git a/packages/twenty-front/src/modules/settings/app-preferences/types/AccountGroupActionTarget.ts b/packages/twenty-front/src/modules/settings/app-preferences/types/AccountGroupActionTarget.tsnew file mode 100644index 00000000000..477ae76b937--- /dev/null+++ b/packages/twenty-front/src/modules/settings/app-preferences/types/AccountGroupActionTarget.ts@@ -0,0 +1 @@+export type AccountGroupActionTarget = { id: string; label: string };diff --git a/packages/twenty-front/src/modules/settings/app-preferences/utils/__tests__/getAccountGroupActionFailureMessage.test.ts b/packages/twenty-front/src/modules/settings/app-preferences/utils/__tests__/getAccountGroupActionFailureMessage.test.tsnew file mode 100644index 00000000000..14e2c1e93a5--- /dev/null+++ b/packages/twenty-front/src/modules/settings/app-preferences/utils/__tests__/getAccountGroupActionFailureMessage.test.ts@@ -0,0 +1,58 @@+import { getAccountGroupActionFailureMessage } from '@/settings/app-preferences/utils/getAccountGroupActionFailureMessage';++const TARGETS = [+ { id: 'google', label: '[email protected]' },+ { id: 'fathom-connection', label: 'Fathom' },+];++const FULFILLED: PromiseSettledResult<unknown> = {+ status: 'fulfilled',+ value: undefined,+};+const REJECTED: PromiseSettledResult<unknown> = {+ status: 'rejected',+ reason: new Error('Mutation failed'),+};++describe('getAccountGroupActionFailureMessage', () => {+ it('returns no message when every connection succeeds', () => {+ expect(+ getAccountGroupActionFailureMessage({+ action: 'delete',+ targets: TARGETS,+ results: [FULFILLED, FULFILLED],+ }),+ ).toBeUndefined();+ });++ it.each([+ [+ 'disconnect',+ 'Disconnected 1 of 2 connections. Could not disconnect: Fathom.',+ ],+ ['delete', 'Deleted 1 of 2 connections. Could not delete: Fathom.'],+ ] as const)('names the one failed connection on %s', (action, message) => {+ expect(+ getAccountGroupActionFailureMessage({+ action,+ targets: TARGETS,+ results: [FULFILLED, REJECTED],+ }),+ ).toBe(message);+ });++ it('names each failed label once', () => {+ expect(+ getAccountGroupActionFailureMessage({+ action: 'delete',+ targets: [+ ...TARGETS,+ { id: 'second-fathom-connection', label: 'Fathom' },+ ],+ results: [REJECTED, REJECTED, REJECTED],+ }),+ ).toBe(+ 'Deleted 0 of 3 connections. Could not delete: [email protected], Fathom.',+ );+ });+});diff --git a/packages/twenty-front/src/modules/settings/app-preferences/utils/__tests__/getAccountGroupActionTargets.test.ts b/packages/twenty-front/src/modules/settings/app-preferences/utils/__tests__/getAccountGroupActionTargets.test.tsnew file mode 100644index 00000000000..af162bf956c--- /dev/null+++ b/packages/twenty-front/src/modules/settings/app-preferences/utils/__tests__/getAccountGroupActionTargets.test.ts@@ -0,0 +1,120 @@+import { getAccountGroupActionTargets } from '@/settings/app-preferences/utils/getAccountGroupActionTargets';++const ARCHIVED_AT = '2026-10-01T00:00:00.000Z';++const CURRENT_WORKSPACE = {+ installedApplications: [+ {+ id: 'fathom',+ name: 'Fathom',+ universalIdentifier: 'fathom-universal-identifier',+ logoUrl: null,+ createdAt: '2024-01-01T00:00:00.000Z',+ },+ ],+ workspaceCustomApplication: null,+};++const buildAccount = ({+ id,+ handle = '[email protected]',+ applicationId = null,+ archivedAt = null,+}: {+ id: string;+ handle?: string;+ applicationId?: string | null;+ archivedAt?: string | null;+}) => ({ id, handle, applicationId, archivedAt });++describe('getAccountGroupActionTargets', () => {+ it('lists the mailbox by handle first, then each app connection by app name, on disconnect', () => {+ expect(+ getAccountGroupActionTargets({+ group: {+ id: 'google',+ handle: '[email protected]',+ builtInAccount: buildAccount({ id: 'google' }),+ appAccounts: [+ buildAccount({+ id: 'fathom-connection',+ handle: '[email protected]',+ applicationId: 'fathom',+ }),+ ],+ },+ action: 'disconnect',+ currentWorkspace: CURRENT_WORKSPACE,+ }),+ ).toEqual([+ { id: 'google', label: '[email protected]' },+ { id: 'fathom-connection', label: 'Fathom' },+ ]);+ });++ const groupWithArchivedConnections = {+ id: 'google',+ handle: '[email protected]',+ builtInAccount: buildAccount({ id: 'google', archivedAt: ARCHIVED_AT }),+ appAccounts: [+ buildAccount({+ id: 'archived-fathom-connection',+ applicationId: 'fathom',+ archivedAt: ARCHIVED_AT,+ }),+ buildAccount({ id: 'active-fathom-connection', applicationId: 'fathom' }),+ ],+ };++ it('skips archived connections on disconnect', () => {+ expect(+ getAccountGroupActionTargets({+ group: groupWithArchivedConnections,+ action: 'disconnect',+ currentWorkspace: CURRENT_WORKSPACE,+ }),+ ).toEqual([{ id: 'active-fathom-connection', label: 'Fathom' }]);+ });++ it('keeps archived connections on delete', () => {+ expect(+ getAccountGroupActionTargets({+ group: groupWithArchivedConnections,+ action: 'delete',+ currentWorkspace: CURRENT_WORKSPACE,+ }).map(({ id }) => id),+ ).toEqual([+ 'google',+ 'archived-fathom-connection',+ 'active-fathom-connection',+ ]);+ });++ it('labels an app missing from the installed applications as Application in an app-only group', () => {+ expect(+ getAccountGroupActionTargets({+ group: {+ id: 'fathom-connection',+ handle: '[email protected]',+ appAccounts: [+ buildAccount({+ id: 'fathom-connection',+ handle: '[email protected]',+ applicationId: 'fathom',+ }),+ buildAccount({+ id: 'uninstalled-connection',+ handle: '[email protected]',+ applicationId: 'uninstalled',+ }),+ ],+ },+ action: 'delete',+ currentWorkspace: CURRENT_WORKSPACE,+ }),+ ).toEqual([+ { id: 'fathom-connection', label: 'Fathom' },+ { id: 'uninstalled-connection', label: 'Application' },+ ]);+ });+});diff --git a/packages/twenty-front/src/modules/settings/app-preferences/utils/getAccountGroupActionFailureMessage.ts b/packages/twenty-front/src/modules/settings/app-preferences/utils/getAccountGroupActionFailureMessage.tsnew file mode 100644index 00000000000..c3495fce372--- /dev/null+++ b/packages/twenty-front/src/modules/settings/app-preferences/utils/getAccountGroupActionFailureMessage.ts@@ -0,0 +1,34 @@+import { type AccountGroupAction } from '@/settings/app-preferences/types/AccountGroupAction';+import { type AccountGroupActionTarget } from '@/settings/app-preferences/types/AccountGroupActionTarget';+import { t } from '@lingui/core/macro';+import { isNonEmptyArray } from 'twenty-shared/utils';++export const getAccountGroupActionFailureMessage = ({+ action,+ targets,+ results,+}: {+ action: AccountGroupAction;+ targets: AccountGroupActionTarget[];+ results: PromiseSettledResult<unknown>[];+}): string | undefined => {+ const failedTargets = targets.filter(+ (_, index) => results[index].status === 'rejected',+ );++ if (!isNonEmptyArray(failedTargets)) {+ return undefined;+ }++ const failedLabels = [+ ...new Set(failedTargets.map(({ label }) => label)),+ ].join(', ');+ const successfulCount = targets.length - failedTargets.length;+ const totalCount = targets.length;++ if (action === 'disconnect') {+ return t`Disconnected ${successfulCount} of ${totalCount} connections. Could not disconnect: ${failedLabels}.`;+ }++ return t`Deleted ${successfulCount} of ${totalCount} connections. Could not delete: ${failedLabels}.`;+};diff --git a/packages/twenty-front/src/modules/settings/app-preferences/utils/getAccountGroupActionTargets.ts b/packages/twenty-front/src/modules/settings/app-preferences/utils/getAccountGroupActionTargets.tsnew file mode 100644index 00000000000..a9d957c7be6--- /dev/null+++ b/packages/twenty-front/src/modules/settings/app-preferences/utils/getAccountGroupActionTargets.ts@@ -0,0 +1,48 @@+import { type ConnectedAccount } from '@/accounts/types/ConnectedAccount';+import { type CurrentWorkspace } from '@/auth/states/currentWorkspaceState';+import { type AccountGroupAction } from '@/settings/app-preferences/types/AccountGroupAction';+import { type AccountGroupActionTarget } from '@/settings/app-preferences/types/AccountGroupActionTarget';+import { type ConnectedAccountGroup } from '@/settings/app-preferences/types/ConnectedAccountGroup';+import { getInstalledApplicationDisplayName } from '@/settings/app-preferences/utils/getInstalledApplicationDisplayName';+import { isDefined } from 'twenty-shared/utils';++export const getAccountGroupActionTargets = <+ TConnectedAccount extends Pick<+ ConnectedAccount,+ 'id' | 'handle' | 'applicationId' | 'archivedAt'+ >,+>({+ group,+ action,+ currentWorkspace,+}: {+ group: ConnectedAccountGroup<TConnectedAccount>;+ action: AccountGroupAction;+ currentWorkspace:+ | Pick<+ CurrentWorkspace,+ 'installedApplications' | 'workspaceCustomApplication'+ >+ | null+ | undefined;+}): AccountGroupActionTarget[] => {+ const isTargeted = (connection: TConnectedAccount) =>+ action === 'delete' || !isDefined(connection.archivedAt);++ const builtInAccountTargets = [group.builtInAccount]+ .filter(isDefined)+ .filter(isTargeted)+ .map(({ id, handle }) => ({ id, label: handle }));++ const appAccountTargets = group.appAccounts+ .filter(isTargeted)+ .map(({ id, applicationId }) => ({+ id,+ label: getInstalledApplicationDisplayName({+ applicationId,+ currentWorkspace,+ }),+ }));++ return [...builtInAccountTargets, ...appAccountTargets];+};diff --git a/packages/twenty-front/src/modules/settings/app-preferences/utils/getInstalledApplicationDisplayName.ts b/packages/twenty-front/src/modules/settings/app-preferences/utils/getInstalledApplicationDisplayName.tsnew file mode 100644index 00000000000..8799b4f3e0c--- /dev/null+++ b/packages/twenty-front/src/modules/settings/app-preferences/utils/getInstalledApplicationDisplayName.ts@@ -0,0 +1,26 @@+import { getApplicationDisplayName } from '@/applications/utils/getApplicationDisplayName';+import { type CurrentWorkspace } from '@/auth/states/currentWorkspaceState';+import { t } from '@lingui/core/macro';+import { isDefined } from 'twenty-shared/utils';++export const getInstalledApplicationDisplayName = ({+ applicationId,+ currentWorkspace,+}: {+ applicationId: string | null | undefined;+ currentWorkspace:+ | Pick<+ CurrentWorkspace,+ 'installedApplications' | 'workspaceCustomApplication'+ >+ | null+ | undefined;+}): string => {+ const application = currentWorkspace?.installedApplications.find(+ (installedApplication) => installedApplication.id === applicationId,+ );++ return isDefined(application)+ ? getApplicationDisplayName({ application, currentWorkspace })+ : t`Application`;+};diff --git a/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccounts.stories.tsx b/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccounts.stories.tsxindex 73838551b21..9d88df86045 100644--- a/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccounts.stories.tsx+++ b/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccounts.stories.tsx@@ -20,13 +20,16 @@ import { SettingsAccounts } from '~/pages/settings/accounts/SettingsAccounts';import {ACCOUNT_GROUPS_GRAPHQL_HANDLERS,CONNECTED_ACCOUNTS,+ FATHOM_ACCOUNT_ID,FATHOM_APPLICATION_ID,GOOGLE_ACCOUNT_ID,GOOGLE_MESSAGE_CHANNEL_ID,MESSAGE_CHANNELS,MICROSOFT_ACCOUNT_ID,deleteConnectedAccount,+ disconnectConnectedAccount,seedAccountGroupsStory,+ withoutDeletedAccounts,} from '~/pages/settings/accounts/__stories__/mockedAccountGroups';import {APPLICATION_PREFERENCES_DETAIL_GRAPHQL_HANDLERS,@@ -34,6 +37,7 @@ import {failNextApplicationPreferencesRequest,seedApplicationPreferencesStory,} from '~/pages/settings/accounts/__stories__/mockedApplicationPreferences';+import { withinTableRowOrThrow } from '~/testing/utils/withinTableRowOrThrow';const meta: Meta<PageDecoratorArgs> = {title: 'Pages/Settings/Accounts/SettingsAccounts',@@ -82,6 +86,21 @@ const getTab = ({tabId: string;}) => within(canvasElement).getByTestId(`tab-${tabId}`);+const openRowMenu = async ({+ canvasElement,+ text,+}: {+ canvasElement: HTMLElement;+ text: string;+}) => {+ await within(canvasElement).findByText(text, undefined, { timeout: 3000 });+ await userEvent.click(+ withinTableRowOrThrow({ canvasElement, text }).getByRole('button', {+ name: 'More options',+ }),+ );+};+const accountGroupsStory: Story = {args: {additionalRoutes: ['/settings/accounts/detail/:connectedAccountId'],@@ -170,9 +189,6 @@ export const AccountsGroupedByEmail: Story = {expect(notesRow.queryByRole('img', { name: 'Gmail and Calendar' }),).not.toBeInTheDocument();- expect(- notesRow.queryByRole('button', { name: 'More options' }),- ).not.toBeInTheDocument();expect(canvas.queryByRole('link', { name: '[email protected]' }),).not.toBeInTheDocument();@@ -320,47 +336,176 @@ export const RowOpensAccountPage: Story = {},};-export const DeleteKeepsAppConnections: Story = {+export const DisconnectCoversEveryActiveConnection: Story = {...accountsTabStory,play: async ({ canvasElement }) => {- const canvas = within(canvasElement);const body = within(canvasElement.ownerDocument.body);- await canvas.findByText('[email protected]', undefined, { timeout: 3000 });+ await openRowMenu({ canvasElement, text: '[email protected]' });+ await userEvent.click(+ await body.findByRole('menuitem', { name: 'Disconnect account' }),+ );- const openDeleteDialog = async () => {- await userEvent.click(- getTableRow(canvasElement, '[email protected]').getByRole('button', {- name: 'More options',- }),- );- expect(body.queryByText('Emails settings')).not.toBeInTheDocument();- await userEvent.click(- await body.findByText('Delete account and synced data'),- );- };+ const dialog = within(+ await body.findByRole('dialog', { name: 'Disconnect account' }),+ );- await openDeleteDialog();- await userEvent.click(await body.findByRole('button', { name: /Cancel/ }));+ expect(dialog.getByText('[email protected]')).toBeVisible();+ expect(dialog.getByText('Fathom')).toBeVisible();- expect(canvas.queryByText(/Navigated to/)).not.toBeInTheDocument();+ await userEvent.click(+ dialog.getByRole('button', { name: 'Disconnect account' }),+ );- await openDeleteDialog();+ await waitFor(() =>+ expect(disconnectConnectedAccount).toHaveBeenCalledTimes(2),+ );+ expect(disconnectConnectedAccount).toHaveBeenCalledWith(GOOGLE_ACCOUNT_ID);+ expect(disconnectConnectedAccount).toHaveBeenCalledWith(FATHOM_ACCOUNT_ID);+ },+};++export const DeleteAlsoRemovesArchivedConnections: Story = {+ ...accountsTabStory,+ parameters: {+ msw: {+ handlers: [+ graphql.query('MyConnectedAccounts', () =>+ HttpResponse.json({+ data: {+ myConnectedAccounts: withoutDeletedAccounts(+ CONNECTED_ACCOUNTS.map((account) =>+ account.id === FATHOM_ACCOUNT_ID+ ? { ...account, archivedAt: '2026-10-01T00:00:00.000Z' }+ : account,+ ),+ ),+ },+ }),+ ),+ ...ACCOUNT_GROUPS_GRAPHQL_HANDLERS,+ ],+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await openRowMenu({ canvasElement, text: '[email protected]' });await userEvent.click(- await body.findByRole('button', { name: /Delete account and data/ }),+ await body.findByRole('menuitem', {+ name: 'Delete account and synced data',+ }),);- const remainingRow = await waitFor(() =>- getTableRow(canvasElement, '[email protected]'),+ const dialog = within(+ await body.findByRole('dialog', {+ name: 'Delete account and synced data?',+ }),+ );++ expect(dialog.getByText('[email protected]')).toBeVisible();+ expect(dialog.getByText('Fathom')).toBeVisible();++ await userEvent.click(+ dialog.getByRole('button', { name: 'Delete account and data' }),+ );++ await waitFor(() =>+ expect(deleteConnectedAccount).toHaveBeenCalledTimes(2),+ );+ expect(deleteConnectedAccount).toHaveBeenCalledWith(GOOGLE_ACCOUNT_ID);+ expect(deleteConnectedAccount).toHaveBeenCalledWith(FATHOM_ACCOUNT_ID);+ await waitFor(() =>+ expect(canvas.queryByText('[email protected]')).not.toBeInTheDocument(),+ );+ expect(canvas.queryByText('[email protected]')).not.toBeInTheDocument();+ },+};++export const CancelRunsNothing: Story = {+ ...accountsTabStory,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await openRowMenu({ canvasElement, text: '[email protected]' });+ await userEvent.click(+ await body.findByRole('menuitem', {+ name: 'Delete account and synced data',+ }),+ );+ await userEvent.click(+ within(+ await body.findByRole('dialog', {+ name: 'Delete account and synced data?',+ }),+ ).getByRole('button', { name: 'Cancel' }),+ );+ await waitFor(() =>+ expect(+ body.queryByRole('dialog', { name: 'Delete account and synced data?' }),+ ).not.toBeInTheDocument(),);- expect(remainingRow.getByRole('img', { name: 'Fathom' })).toBeVisible();+ expect(disconnectConnectedAccount).not.toHaveBeenCalled();+ expect(deleteConnectedAccount).not.toHaveBeenCalled();+ expect(canvas.queryByText(/Navigated to/)).not.toBeInTheDocument();+ },+};++export const AccountsTabMenuOpensAccountSettingsWithoutReconnect: Story = {+ ...accountsTabStory,+ parameters: {+ msw: {+ handlers: [+ graphql.query('MyConnectedAccounts', () =>+ HttpResponse.json({+ data: {+ myConnectedAccounts: withoutDeletedAccounts(+ CONNECTED_ACCOUNTS.map((account) =>+ account.id === GOOGLE_ACCOUNT_ID+ ? { ...account, authFailedAt: '2026-10-01T00:00:00.000Z' }+ : account,+ ),+ ),+ },+ }),+ ),+ ...ACCOUNT_GROUPS_GRAPHQL_HANDLERS,+ ],+ },+ },+ play: async ({ canvasElement }) => {+ const body = within(canvasElement.ownerDocument.body);++ await openRowMenu({ canvasElement, text: '[email protected]' });++ expect(+ await body.findByRole('menuitem', { name: 'Account settings' }),+ ).toHaveAttribute('href', `/settings/accounts/detail/${GOOGLE_ACCOUNT_ID}`);expect(- remainingRow.queryByRole('button', { name: 'More options' }),+ body.queryByRole('menuitem', { name: 'Reconnect' }),+ ).not.toBeInTheDocument();+ },+};++export const AppOnlyAccountOffersDisconnectAndDelete: Story = {+ ...accountsTabStory,+ play: async ({ canvasElement }) => {+ const body = within(canvasElement.ownerDocument.body);++ await openRowMenu({ canvasElement, text: '[email protected]' });++ expect(+ await body.findByRole('menuitem', { name: 'Disconnect account' }),+ ).toBeVisible();+ expect(+ body.getByRole('menuitem', { name: 'Delete account and synced data' }),+ ).toBeVisible();+ expect(+ body.queryByRole('menuitem', { name: 'Account settings' }),).not.toBeInTheDocument();- expect(canvas.queryByText('[email protected]')).not.toBeInTheDocument();- expect(deleteConnectedAccount.mock.calls).toEqual([[GOOGLE_ACCOUNT_ID]]);- expect(canvas.queryByText(/Navigated to/)).not.toBeInTheDocument();},};diff --git a/packages/twenty-front/src/pages/settings/accounts/__stories__/mockedAccountGroups.ts b/packages/twenty-front/src/pages/settings/accounts/__stories__/mockedAccountGroups.tsindex 487276cac3c..eb99a546601 100644--- a/packages/twenty-front/src/pages/settings/accounts/__stories__/mockedAccountGroups.ts+++ b/packages/twenty-front/src/pages/settings/accounts/__stories__/mockedAccountGroups.ts@@ -29,7 +29,7 @@ export const GOOGLE_ACCOUNT_ID = '20202020-1a2b-4c3d-8e4f-000000000011';export const MICROSOFT_ACCOUNT_ID = '20202020-1a2b-4c3d-8e4f-000000000014';export const GOOGLE_MESSAGE_CHANNEL_ID = '20202020-1a2b-4c3d-8e4f-000000000031';export const FATHOM_ONLY_ACCOUNT_ID = '20202020-1a2b-4c3d-8e4f-000000000013';-const FATHOM_ACCOUNT_ID = '20202020-1a2b-4c3d-8e4f-000000000012';+export const FATHOM_ACCOUNT_ID = '20202020-1a2b-4c3d-8e4f-000000000012';const MY_SHARED_ACCOUNT_ID = '20202020-1a2b-4c3d-8e4f-000000000015';const TEAMMATE_ACCOUNT_ID = '20202020-1a2b-4c3d-8e4f-000000000016';const EMAIL_GROUP_ACCOUNT_ID = '20202020-1a2b-4c3d-8e4f-000000000017';@@ -224,6 +224,7 @@ export const withoutDeletedAccounts = <TAccount extends { id: string }>() => accounts.filter((account) => !deletedAccountIds.has(account.id));export const deleteConnectedAccount = fn();+export const disconnectConnectedAccount = fn();export const myApplicationPreferencesRequested = fn();export const ACCOUNT_GROUPS_GRAPHQL_HANDLERS = [@@ -267,6 +268,18 @@ export const ACCOUNT_GROUPS_GRAPHQL_HANDLERS = [},});}),+ graphql.mutation('DisconnectConnectedAccount', ({ variables }) => {+ disconnectConnectedAccount(variables.id);++ return HttpResponse.json({+ data: {+ disconnectConnectedAccount: {+ __typename: 'ConnectedAccountPublicDTO',+ id: variables.id,+ },+ },+ });+ }),graphql.query('MyApplicationPreferences', () => {myApplicationPreferencesRequested();@@ -290,6 +303,7 @@ export const ACCOUNT_GROUPS_GRAPHQL_HANDLERS = [export const seedAccountGroupsStory = async () => {deletedAccountIds.clear();deleteConnectedAccount.mockClear();+ disconnectConnectedAccount.mockClear();myApplicationPreferencesRequested.mockClear();await mockedApolloClient.clearStore();