Skip to content

The open alternative to Salesforce, designed for AI.

Let admins remove linked Teams accounts from Teams settings (#27996)

Abdul Rahman1cc714c7900d
diff --git a/packages/twenty-apps/public/teams/src/features/chat/front-components/TeamsUserLinksList.tsx b/packages/twenty-apps/public/teams/src/features/chat/front-components/TeamsUserLinksList.tsx
index 46f01165dc7..83fb534b7a7 100644
--- a/packages/twenty-apps/public/teams/src/features/chat/front-components/TeamsUserLinksList.tsx
+++ b/packages/twenty-apps/public/teams/src/features/chat/front-components/TeamsUserLinksList.tsx
@@ -1,14 +1,17 @@
import styled from '@emotion/styled';
import { isNonEmptyString } from '@sniptt/guards';
-import { useTranslate } from 'twenty-sdk/front-component';
+import { enqueueSnackbar, useTranslate } from 'twenty-sdk/front-component';
import { isDefined } from 'twenty-sdk/utils';
import { Tag, type TagColor } from 'twenty-ui/primitives/data-display';
+import { Button } from 'twenty-ui/primitives/input';
import { OverflowingTextWithTooltip } from 'twenty-ui/primitives/typography';
import { themeCssVariables } from 'twenty-ui/theme';
+import { useRemoveTeamsUserLink } from 'src/features/chat/front-components/hooks/use-remove-teams-user-link';
import { useTeamsUserLinks } from 'src/features/chat/front-components/hooks/use-teams-user-links';
import { TEAMS_USER_LINK_SOURCE } from 'src/features/chat/logic-functions/constants/teams-user-link-source';
import { type TeamsUserLinkSource } from 'src/features/chat/logic-functions/types/teams-user-link-source.type';
+import { type TeamsUserLinkRecord } from 'src/features/chat/front-components/types/teams-user-link-record.type';
const SOURCE_TAG_COLORS: Record<TeamsUserLinkSource, TagColor> = {
[TEAMS_USER_LINK_SOURCE.AUTO]: 'green',
@@ -40,7 +43,7 @@ const StyledRow = styled.li`
font-size: ${() => themeCssVariables.font.size.md};
gap: ${() => themeCssVariables.spacing[4]};
align-items: center;
- grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto auto;
padding: ${() => themeCssVariables.spacing[3]}
${() => themeCssVariables.spacing[4]};
@@ -55,7 +58,30 @@ const StyledSecondaryText = styled.span`
const TeamsUserLinksContent = () => {
const { t } = useTranslate();
- const { teamsUserLinks, isLoading, hasLoadError } = useTeamsUserLinks();
+ const {
+ teamsUserLinks,
+ isLoading,
+ hasLoadError,
+ canManageTeamsUserLinks,
+ dropTeamsUserLink,
+ } = useTeamsUserLinks();
+ const { removeTeamsUserLink, removingLinkId } = useRemoveTeamsUserLink();
+
+ const handleRemove = async (teamsUserLink: TeamsUserLinkRecord) => {
+ const isRemoved = await removeTeamsUserLink(teamsUserLink.id);
+
+ if (!isRemoved) {
+ enqueueSnackbar({
+ message: t('Could not remove the link. Please try again.'),
+ variant: 'error',
+ });
+
+ return;
+ }
+
+ dropTeamsUserLink(teamsUserLink.id);
+ enqueueSnackbar({ message: t('Link removed'), variant: 'success' });
+ };
const sourceLabels: Record<TeamsUserLinkSource, string> = {
[TEAMS_USER_LINK_SOURCE.AUTO]: t('Matched on email'),
@@ -84,29 +110,46 @@ const TeamsUserLinksContent = () => {
return (
<StyledList>
- {teamsUserLinks.map((teamsUserLink) => (
- <StyledRow key={teamsUserLink.id}>
- <OverflowingTextWithTooltip
- text={
- isNonEmptyString(teamsUserLink.name)
- ? teamsUserLink.name
- : t('Unnamed Teams account')
- }
- />
- <OverflowingTextWithTooltip
- text={
- isNonEmptyString(teamsUserLink.workspaceMemberName)
- ? teamsUserLink.workspaceMemberName
- : t('No workspace member')
- }
- />
- {isDefined(teamsUserLink.source) && (
- <Tag color={SOURCE_TAG_COLORS[teamsUserLink.source]}>
- {sourceLabels[teamsUserLink.source]}
- </Tag>
- )}
- </StyledRow>
- ))}
+ {teamsUserLinks.map((teamsUserLink) => {
+ const teamsAccountName = isNonEmptyString(teamsUserLink.name)
+ ? teamsUserLink.name
+ : t('Unnamed Teams account');
+
+ return (
+ <StyledRow key={teamsUserLink.id}>
+ <OverflowingTextWithTooltip text={teamsAccountName} />
+ <OverflowingTextWithTooltip
+ text={
+ isNonEmptyString(teamsUserLink.workspaceMemberName)
+ ? teamsUserLink.workspaceMemberName
+ : t('No workspace member')
+ }
+ />
+ <span>
+ {isDefined(teamsUserLink.source) && (
+ <Tag color={SOURCE_TAG_COLORS[teamsUserLink.source]}>
+ {sourceLabels[teamsUserLink.source]}
+ </Tag>
+ )}
+ </span>
+ {canManageTeamsUserLinks && (
+ <Button
+ variant="ghost"
+ color="danger"
+ size="sm"
+ aria-label={t('Remove link for {name}', {
+ name: teamsAccountName,
+ })}
+ loading={removingLinkId === teamsUserLink.id}
+ disabled={isDefined(removingLinkId)}
+ onClick={() => handleRemove(teamsUserLink)}
+ >
+ {t('Remove')}
+ </Button>
+ )}
+ </StyledRow>
+ );
+ })}
</StyledList>
);
};
diff --git a/packages/twenty-apps/public/teams/src/features/chat/front-components/__tests__/TeamsUserLinksList.test.tsx b/packages/twenty-apps/public/teams/src/features/chat/front-components/__tests__/TeamsUserLinksList.test.tsx
index d27f8818768..55f7d9d26f4 100644
--- a/packages/twenty-apps/public/teams/src/features/chat/front-components/__tests__/TeamsUserLinksList.test.tsx
+++ b/packages/twenty-apps/public/teams/src/features/chat/front-components/__tests__/TeamsUserLinksList.test.tsx
@@ -1,25 +1,47 @@
// @vitest-environment jsdom
-import { cleanup, render, screen } from '@testing-library/react';
+import { act, cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { TeamsUserLinksList } from 'src/features/chat/front-components/TeamsUserLinksList';
-const { restGetMock } = vi.hoisted(() => ({ restGetMock: vi.fn() }));
+const {
+ restGetMock,
+ restPostMock,
+ enqueueSnackbarMock,
+ hasRolesPermissionMock,
+} = vi.hoisted(() => ({
+ restGetMock: vi.fn(),
+ restPostMock: vi.fn(),
+ enqueueSnackbarMock: vi.fn(),
+ hasRolesPermissionMock: vi.fn(),
+}));
vi.mock('twenty-sdk/front-component', () => ({
- useTranslate: () => ({ t: (message: string) => message }),
+ enqueueSnackbar: enqueueSnackbarMock,
+ useTranslate: () => ({
+ t: (message: string, values?: Record<string, string>) =>
+ message.replace(/\{(\w+)\}/g, (_, key: string) => values?.[key] ?? ''),
+ }),
}));
vi.mock('twenty-client-sdk/rest', () => ({
RestApiClient: class {
get = restGetMock;
+ post = restPostMock;
},
}));
+vi.mock(
+ 'src/features/chat/logic-functions/utils/current-user-has-roles-permission',
+ () => ({ currentUserHasRolesPermission: hasRolesPermissionMock }),
+);
+
describe('TeamsUserLinksList', () => {
beforeEach(() => {
vi.resetAllMocks();
+ hasRolesPermissionMock.mockResolvedValue(true);
});
afterEach(cleanup);
@@ -65,9 +87,9 @@ describe('TeamsUserLinksList', () => {
const rows = await screen.findAllByRole('listitem');
expect(rows.map((row) => row.textContent)).toEqual([
- 'Adam TeamsAdamMatched on email',
- 'Mia TeamsNo workspace member',
- 'Zoe TeamsZoe DoeSet manually',
+ 'Adam TeamsAdamMatched on emailRemove',
+ 'Mia TeamsNo workspace memberRemove',
+ 'Zoe TeamsZoe DoeSet manuallyRemove',
]);
expect(restGetMock.mock.calls).toEqual([
['/rest/teamsUserLinks', { query: { depth: '1', limit: '200' } }],
@@ -90,4 +112,98 @@ describe('TeamsUserLinksList', () => {
'Could not load linked Teams accounts. Please try again.',
);
});
+
+ it('removes a link through the route and drops it from the list', async () => {
+ restGetMock.mockResolvedValue({
+ data: {
+ teamsUserLinks: [
+ { id: 'link-1', name: 'Adam Teams', source: 'AUTO' },
+ { id: 'link-2', name: 'Zoe Teams', source: 'MANUAL' },
+ ],
+ },
+ });
+ restPostMock.mockResolvedValue({
+ success: true,
+ message: 'Removed the Teams user link.',
+ });
+ const user = userEvent.setup();
+
+ render(<TeamsUserLinksList />);
+ await user.click(
+ await screen.findByRole('button', { name: 'Remove link for Adam Teams' }),
+ );
+
+ expect(restPostMock.mock.calls).toEqual([
+ ['/s/teams-user-links/remove', { id: 'link-1' }],
+ ]);
+ expect(enqueueSnackbarMock.mock.calls).toEqual([
+ [{ message: 'Link removed', variant: 'success' }],
+ ]);
+ expect(screen.queryByText('Adam Teams')).toBeNull();
+ expect(screen.getByText('Zoe Teams')).toBeTruthy();
+ });
+
+ it('hides the Remove button from members without the roles permission', async () => {
+ hasRolesPermissionMock.mockResolvedValue(false);
+ restGetMock.mockResolvedValue({
+ data: {
+ teamsUserLinks: [{ id: 'link-1', name: 'Adam Teams', source: 'AUTO' }],
+ },
+ });
+
+ render(<TeamsUserLinksList />);
+
+ expect(await screen.findByText('Adam Teams')).toBeTruthy();
+ expect(
+ screen.queryByRole('button', { name: /^Remove link for/ }),
+ ).toBeNull();
+ });
+
+ it('locks every Remove button while a removal is pending and recovers when it fails', async () => {
+ restGetMock.mockResolvedValue({
+ data: {
+ teamsUserLinks: [
+ { id: 'link-1', name: 'Adam Teams', source: 'AUTO' },
+ { id: 'link-2', name: 'Zoe Teams', source: 'MANUAL' },
+ ],
+ },
+ });
+ let rejectRemoval: ((error: Error) => void) | undefined;
+ restPostMock.mockReturnValueOnce(
+ new Promise((_, reject) => {
+ rejectRemoval = reject;
+ }),
+ );
+ const user = userEvent.setup();
+
+ render(<TeamsUserLinksList />);
+ await user.click(
+ await screen.findByRole('button', { name: 'Remove link for Adam Teams' }),
+ );
+
+ const removeButtons = screen.getAllByRole('button', {
+ name: /^Remove link for/,
+ });
+
+ for (const button of removeButtons) {
+ expect(button.hasAttribute('disabled')).toBe(true);
+ }
+
+ await act(async () => {
+ rejectRemoval?.(new Error('Network error'));
+ });
+
+ expect(enqueueSnackbarMock.mock.calls).toEqual([
+ [
+ {
+ message: 'Could not remove the link. Please try again.',
+ variant: 'error',
+ },
+ ],
+ ]);
+ expect(screen.getByText('Adam Teams')).toBeTruthy();
+ for (const button of removeButtons) {
+ expect(button.hasAttribute('disabled')).toBe(false);
+ }
+ });
});
diff --git a/packages/twenty-apps/public/teams/src/features/chat/front-components/hooks/use-remove-teams-user-link.ts b/packages/twenty-apps/public/teams/src/features/chat/front-components/hooks/use-remove-teams-user-link.ts
new file mode 100644
index 00000000000..fca9f2fa061
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/chat/front-components/hooks/use-remove-teams-user-link.ts
@@ -0,0 +1,29 @@
+import { useState } from 'react';
+import { RestApiClient } from 'twenty-client-sdk/rest';
+
+import { TEAMS_USER_LINKS_REMOVE_ROUTE_PATH } from 'src/features/chat/constants/teams-user-links-route-path';
+import { type TeamsUserLinkActionResult } from 'src/features/chat/logic-functions/types/teams-user-link-action-result.type';
+
+export const useRemoveTeamsUserLink = () => {
+ const [removingLinkId, setRemovingLinkId] = useState<string | undefined>(
+ undefined,
+ );
+
+ const removeTeamsUserLink = async (id: string): Promise<boolean> => {
+ setRemovingLinkId(id);
+
+ try {
+ const result = await new RestApiClient().post<
+ TeamsUserLinkActionResult | undefined
+ >(`/s${TEAMS_USER_LINKS_REMOVE_ROUTE_PATH}`, { id });
+
+ return result?.success ?? false;
+ } catch {
+ return false;
+ } finally {
+ setRemovingLinkId(undefined);
+ }
+ };
+
+ return { removeTeamsUserLink, removingLinkId };
+};
diff --git a/packages/twenty-apps/public/teams/src/features/chat/front-components/hooks/use-teams-user-links.ts b/packages/twenty-apps/public/teams/src/features/chat/front-components/hooks/use-teams-user-links.ts
index 2971cd4a2b1..5163d27acae 100644
--- a/packages/twenty-apps/public/teams/src/features/chat/front-components/hooks/use-teams-user-links.ts
+++ b/packages/twenty-apps/public/teams/src/features/chat/front-components/hooks/use-teams-user-links.ts
@@ -2,6 +2,7 @@ import { isNonEmptyString } from '@sniptt/guards';
import { useEffect, useState } from 'react';
import { RestApiClient } from 'twenty-client-sdk/rest';
+import { currentUserHasRolesPermission } from 'src/features/chat/logic-functions/utils/current-user-has-roles-permission';
import { TEAMS_USER_LINK_SOURCE } from 'src/features/chat/logic-functions/constants/teams-user-link-source';
import { type TeamsUserLinkRecord } from 'src/features/chat/front-components/types/teams-user-link-record.type';
@@ -73,14 +74,16 @@ export const useTeamsUserLinks = () => {
);
const [isLoading, setIsLoading] = useState(true);
const [hasLoadError, setHasLoadError] = useState(false);
+ const [canManageTeamsUserLinks, setCanManageTeamsUserLinks] = useState(false);
useEffect(() => {
let isCancelled = false;
- fetchTeamsUserLinks()
- .then((records) => {
+ Promise.all([fetchTeamsUserLinks(), currentUserHasRolesPermission()])
+ .then(([records, hasRolesPermission]) => {
if (!isCancelled) {
setTeamsUserLinks(records);
+ setCanManageTeamsUserLinks(hasRolesPermission);
}
})
.catch(() => {
@@ -99,5 +102,15 @@ export const useTeamsUserLinks = () => {
};
}, []);
- return { teamsUserLinks, isLoading, hasLoadError };
+ const dropTeamsUserLink = (id: string) => {
+ setTeamsUserLinks((links) => links.filter((link) => link.id !== id));
+ };
+
+ return {
+ teamsUserLinks,
+ isLoading,
+ hasLoadError,
+ canManageTeamsUserLinks,
+ dropTeamsUserLink,
+ };
};
diff --git a/packages/twenty-apps/public/teams/src/front-components/components/__tests__/TeamsSettings.test.tsx b/packages/twenty-apps/public/teams/src/front-components/components/__tests__/TeamsSettings.test.tsx
index 93930fc1a7b..367be990d44 100644
--- a/packages/twenty-apps/public/teams/src/front-components/components/__tests__/TeamsSettings.test.tsx
+++ b/packages/twenty-apps/public/teams/src/front-components/components/__tests__/TeamsSettings.test.tsx
@@ -59,6 +59,11 @@ vi.mock('twenty-client-sdk/rest', () => ({
},
}));
+vi.mock(
+ 'src/features/chat/logic-functions/utils/current-user-has-roles-permission',
+ () => ({ currentUserHasRolesPermission: async () => false }),
+);
+
describe('TeamsSettings', () => {
beforeEach(() => {
vi.resetAllMocks();