The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Show linked Teams accounts in Teams chat settings (#27987)
Abdul Rahmana611ec3d6f61
diff --git a/packages/twenty-apps/public/teams/src/features/chat/front-components/ChatSettings.tsx b/packages/twenty-apps/public/teams/src/features/chat/front-components/ChatSettings.tsxindex 468bb79d355..a34044738f8 100644--- a/packages/twenty-apps/public/teams/src/features/chat/front-components/ChatSettings.tsx+++ b/packages/twenty-apps/public/teams/src/features/chat/front-components/ChatSettings.tsx@@ -2,6 +2,7 @@ import { useTranslate } from 'twenty-sdk/front-component';import { FEATURE_FLAGS } from 'src/constants/feature-flags';import { CHAT_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/chat/constants/chat-enabled-application-variable-key';+import { TeamsUserLinksList } from 'src/features/chat/front-components/TeamsUserLinksList';import { FeatureSettingsSection } from 'src/front-components/components/FeatureSettingsSection';import { useFeatureSetting } from 'src/front-components/hooks/use-feature-setting';import { isFeatureEnabled } from 'src/utils/is-feature-enabled';@@ -14,25 +15,30 @@ export const ChatSettings = () => {isAvailable: FEATURE_FLAGS.IS_CHAT_ASSISTANT_ENABLED,});+ const isChatEnabled = isFeatureEnabled({+ isAvailable: FEATURE_FLAGS.IS_CHAT_ASSISTANT_ENABLED,+ settingValue,+ });+const handleChange = (isEnabled: boolean) => {void updateSetting(isEnabled);};return (- <FeatureSettingsSection- title={t('Chat')}- label={t('Enable chat')}- description={t(- 'Use the Teams assistant and messaging workflows in this workspace.',- )}- isAvailable={FEATURE_FLAGS.IS_CHAT_ASSISTANT_ENABLED}- isEnabled={isFeatureEnabled({- isAvailable: FEATURE_FLAGS.IS_CHAT_ASSISTANT_ENABLED,- settingValue,- })}- isSaving={isSaving}- hasSaveError={hasSaveError}- onChange={handleChange}- />+ <>+ <FeatureSettingsSection+ title={t('Chat')}+ label={t('Enable chat')}+ description={t(+ 'Use the Teams assistant and messaging workflows in this workspace.',+ )}+ isAvailable={FEATURE_FLAGS.IS_CHAT_ASSISTANT_ENABLED}+ isEnabled={isChatEnabled}+ isSaving={isSaving}+ hasSaveError={hasSaveError}+ onChange={handleChange}+ />+ {isChatEnabled && <TeamsUserLinksList />}+ </>);};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.tsxnew file mode 100644index 00000000000..46f01165dc7--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/chat/front-components/TeamsUserLinksList.tsx@@ -0,0 +1,123 @@+import styled from '@emotion/styled';+import { isNonEmptyString } from '@sniptt/guards';+import { useTranslate } from 'twenty-sdk/front-component';+import { isDefined } from 'twenty-sdk/utils';+import { Tag, type TagColor } from 'twenty-ui/primitives/data-display';+import { OverflowingTextWithTooltip } from 'twenty-ui/primitives/typography';+import { themeCssVariables } from 'twenty-ui/theme';++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';++const SOURCE_TAG_COLORS: Record<TeamsUserLinkSource, TagColor> = {+ [TEAMS_USER_LINK_SOURCE.AUTO]: 'green',+ [TEAMS_USER_LINK_SOURCE.MANUAL]: 'blue',+};++const StyledSection = styled.section`+ color: ${() => themeCssVariables.font.color.primary};+ font-family: ${() => themeCssVariables.font.family};+ margin-top: ${() => themeCssVariables.spacing[4]};+`;++const StyledTitle = styled.h3`+ font-size: ${() => themeCssVariables.font.size.md};+ font-weight: ${() => themeCssVariables.font.weight.medium};+ margin: 0 0 ${() => themeCssVariables.spacing[2]};+`;++const StyledList = styled.ul`+ border: 1px solid ${() => themeCssVariables.border.color.medium};+ border-radius: ${() => themeCssVariables.border.radius.md};+ list-style: none;+ margin: 0;+ padding: 0;+`;++const StyledRow = styled.li`+ display: grid;+ font-size: ${() => themeCssVariables.font.size.md};+ gap: ${() => themeCssVariables.spacing[4]};+ align-items: center;+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto;+ padding: ${() => themeCssVariables.spacing[3]}+ ${() => themeCssVariables.spacing[4]};++ & + & {+ border-top: 1px solid ${() => themeCssVariables.border.color.medium};+ }+`;++const StyledSecondaryText = styled.span`+ color: ${() => themeCssVariables.font.color.secondary};+`;++const TeamsUserLinksContent = () => {+ const { t } = useTranslate();+ const { teamsUserLinks, isLoading, hasLoadError } = useTeamsUserLinks();++ const sourceLabels: Record<TeamsUserLinkSource, string> = {+ [TEAMS_USER_LINK_SOURCE.AUTO]: t('Matched on email'),+ [TEAMS_USER_LINK_SOURCE.MANUAL]: t('Set manually'),+ };++ if (isLoading) {+ return <StyledSecondaryText>{t('Loading…')}</StyledSecondaryText>;+ }++ if (hasLoadError) {+ return (+ <p role="alert">+ {t('Could not load linked Teams accounts. Please try again.')}+ </p>+ );+ }++ if (teamsUserLinks.length === 0) {+ return (+ <StyledSecondaryText>+ {t('No Teams account is linked yet.')}+ </StyledSecondaryText>+ );+ }++ 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>+ ))}+ </StyledList>+ );+};++export const TeamsUserLinksList = () => {+ const { t } = useTranslate();++ return (+ <StyledSection aria-label={t('Linked Teams accounts')}>+ <StyledTitle>{t('Linked Teams accounts')}</StyledTitle>+ <TeamsUserLinksContent />+ </StyledSection>+ );+};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.tsxnew file mode 100644index 00000000000..d27f8818768--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/chat/front-components/__tests__/TeamsUserLinksList.test.tsx@@ -0,0 +1,93 @@+// @vitest-environment jsdom++import { cleanup, render, screen } from '@testing-library/react';+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() }));++vi.mock('twenty-sdk/front-component', () => ({+ useTranslate: () => ({ t: (message: string) => message }),+}));++vi.mock('twenty-client-sdk/rest', () => ({+ RestApiClient: class {+ get = restGetMock;+ },+}));++describe('TeamsUserLinksList', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ });++ afterEach(cleanup);++ it('lists linked Teams accounts across pages sorted by name with their member and known source', async () => {+ restGetMock+ .mockResolvedValueOnce({+ data: {+ teamsUserLinks: [+ {+ id: 'link-2',+ name: 'Zoe Teams',+ source: 'MANUAL',+ workspaceMember: { name: { firstName: 'Zoe', lastName: 'Doe' } },+ },+ { id: null, name: 'Ignored' },+ ],+ },+ pageInfo: { hasNextPage: true, endCursor: 'cursor-1' },+ })+ .mockResolvedValueOnce({+ data: {+ teamsUserLinks: [+ {+ id: 'link-1',+ name: 'Adam Teams',+ source: 'AUTO',+ workspaceMember: { name: { firstName: 'Adam', lastName: '' } },+ },+ {+ id: 'link-3',+ name: 'Mia Teams',+ source: 'LEGACY',+ workspaceMember: null,+ },+ ],+ },+ pageInfo: { hasNextPage: false, endCursor: 'cursor-2' },+ });++ render(<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',+ ]);+ expect(restGetMock.mock.calls).toEqual([+ ['/rest/teamsUserLinks', { query: { depth: '1', limit: '200' } }],+ [+ '/rest/teamsUserLinks',+ {+ query: { depth: '1', limit: '200', starting_after: 'cursor-1' },+ },+ ],+ ]);+ });++ it('shows an error when links cannot be loaded', async () => {+ restGetMock.mockRejectedValue(new Error('Forbidden'));++ render(<TeamsUserLinksList />);++ expect(await screen.findByRole('alert')).toHaveProperty(+ 'textContent',+ 'Could not load linked Teams accounts. Please try again.',+ );+ });+});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.tsnew file mode 100644index 00000000000..2971cd4a2b1--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/chat/front-components/hooks/use-teams-user-links.ts@@ -0,0 +1,103 @@+import { isNonEmptyString } from '@sniptt/guards';+import { useEffect, useState } from 'react';+import { RestApiClient } from 'twenty-client-sdk/rest';++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';++const TEAMS_USER_LINKS_PAGE_SIZE = 200;++const TEAMS_USER_LINK_SOURCES = Object.values(TEAMS_USER_LINK_SOURCE);++type TeamsUserLinksResponse = {+ data?: {+ teamsUserLinks?: {+ id?: string | null;+ name?: string | null;+ source?: string | null;+ workspaceMember?: {+ name?: { firstName?: string | null; lastName?: string | null } | null;+ } | null;+ }[];+ };+ pageInfo?: { hasNextPage?: boolean; endCursor?: string | null };+};++const fetchTeamsUserLinksPage = (startingAfter: string | undefined) =>+ new RestApiClient().get<TeamsUserLinksResponse>('/rest/teamsUserLinks', {+ query: {+ depth: '1',+ limit: String(TEAMS_USER_LINKS_PAGE_SIZE),+ ...(isNonEmptyString(startingAfter) && { starting_after: startingAfter }),+ },+ });++const fetchTeamsUserLinks = async (): Promise<TeamsUserLinkRecord[]> => {+ const records: TeamsUserLinkRecord[] = [];+ let startingAfter: string | undefined;++ do {+ const response = await fetchTeamsUserLinksPage(startingAfter);++ for (const record of response.data?.teamsUserLinks ?? []) {+ if (!isNonEmptyString(record.id)) {+ continue;+ }++ records.push({+ id: record.id,+ name: record.name ?? '',+ workspaceMemberName: [+ record.workspaceMember?.name?.firstName,+ record.workspaceMember?.name?.lastName,+ ]+ .filter(isNonEmptyString)+ .join(' '),+ source: TEAMS_USER_LINK_SOURCES.find(+ (source) => source === record.source,+ ),+ });+ }++ startingAfter = response.pageInfo?.hasNextPage+ ? (response.pageInfo.endCursor ?? undefined)+ : undefined;+ } while (isNonEmptyString(startingAfter));++ return records.sort((left, right) => left.name.localeCompare(right.name));+};++export const useTeamsUserLinks = () => {+ const [teamsUserLinks, setTeamsUserLinks] = useState<TeamsUserLinkRecord[]>(+ [],+ );+ const [isLoading, setIsLoading] = useState(true);+ const [hasLoadError, setHasLoadError] = useState(false);++ useEffect(() => {+ let isCancelled = false;++ fetchTeamsUserLinks()+ .then((records) => {+ if (!isCancelled) {+ setTeamsUserLinks(records);+ }+ })+ .catch(() => {+ if (!isCancelled) {+ setHasLoadError(true);+ }+ })+ .finally(() => {+ if (!isCancelled) {+ setIsLoading(false);+ }+ });++ return () => {+ isCancelled = true;+ };+ }, []);++ return { teamsUserLinks, isLoading, hasLoadError };+};diff --git a/packages/twenty-apps/public/teams/src/features/chat/front-components/types/teams-user-link-record.type.ts b/packages/twenty-apps/public/teams/src/features/chat/front-components/types/teams-user-link-record.type.tsnew file mode 100644index 00000000000..b97250fba4b--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/chat/front-components/types/teams-user-link-record.type.ts@@ -0,0 +1,8 @@+import { type TeamsUserLinkSource } from 'src/features/chat/logic-functions/types/teams-user-link-source.type';++export type TeamsUserLinkRecord = {+ id: string;+ name: string;+ workspaceMemberName: string;+ source: TeamsUserLinkSource | undefined;+};diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/current-user-has-roles-permission.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/current-user-has-roles-permission.tsindex 0deb6419085..8ab36be0046 100644--- a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/current-user-has-roles-permission.ts+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/utils/current-user-has-roles-permission.ts@@ -1,6 +1,4 @@-import { MetadataApiClient } from 'twenty-client-sdk/metadata';--const ROLES_PERMISSION_FLAG = 'ROLES';+import { MetadataApiClient, MetadataSchema } from 'twenty-client-sdk/metadata';export const currentUserHasRolesPermission = async (): Promise<boolean> => {try {@@ -13,7 +11,7 @@ export const currentUserHasRolesPermission = async (): Promise<boolean> => {});return (currentUser.currentUserWorkspace?.permissionFlags ?? []).includes(- ROLES_PERMISSION_FLAG,+ MetadataSchema.enumPermissionFlagType.ROLES,);} catch {return false;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.tsxindex 84c6a0a7e98..fd34517b2a1 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@@ -9,19 +9,21 @@ import { CHAT_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/chat/constanimport { TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/transcripts/constants/transcripts-enabled-application-variable-key';import { TeamsSettings } from 'src/front-components/components/TeamsSettings';-const { featureFlags, variables, queryMock, mutationMock } = vi.hoisted(() => {- const variables: Record<string, string | undefined> = {};-- return {- featureFlags: {- IS_CHAT_ASSISTANT_ENABLED: false,- IS_TRANSCRIPT_IMPORT_ENABLED: false,- },- variables,- queryMock: vi.fn(),- mutationMock: vi.fn(),- };-});+const { featureFlags, variables, queryMock, mutationMock, restGetMock } =+ vi.hoisted(() => {+ const variables: Record<string, string | undefined> = {};++ return {+ featureFlags: {+ IS_CHAT_ASSISTANT_ENABLED: false,+ IS_TRANSCRIPT_IMPORT_ENABLED: false,+ },+ variables,+ queryMock: vi.fn(),+ mutationMock: vi.fn(),+ restGetMock: vi.fn(),+ };+ });const APPLICATION_QUERY = {findOneApplication: {@@ -46,6 +48,12 @@ vi.mock('twenty-client-sdk/metadata', () => ({},}));+vi.mock('twenty-client-sdk/rest', () => ({+ RestApiClient: class {+ get = restGetMock;+ },+}));+describe('TeamsSettings', () => {beforeEach(() => {vi.resetAllMocks();@@ -57,6 +65,7 @@ describe('TeamsSettings', () => {findOneApplication: { id: 'teams-application' },});mutationMock.mockResolvedValue({ updateOneApplicationVariable: true });+ restGetMock.mockResolvedValue({ data: { teamsUserLinks: [] } });});afterEach(cleanup);@@ -135,6 +144,22 @@ describe('TeamsSettings', () => {},);+ it('shows linked Teams accounts only while chat is enabled', async () => {+ featureFlags.IS_CHAT_ASSISTANT_ENABLED = true;+ const user = userEvent.setup();++ render(<TeamsSettings />);++ expect(screen.queryByText('Linked Teams accounts')).toBeNull();++ await user.click(screen.getByRole('switch', { name: 'Enable chat' }));++ expect(+ await screen.findByText('No Teams account is linked yet.'),+ ).toBeTruthy();+ expect(restGetMock).toHaveBeenCalledTimes(1);+ });+it('saves the selected feature without changing the other preference', async () => {featureFlags.IS_CHAT_ASSISTANT_ENABLED = true;featureFlags.IS_TRANSCRIPT_IMPORT_ENABLED = true;