Skip to content

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

feat: salesforce integration overhaul (#17276)

Avram Tudor9f5cb87b91f2
diff --git a/lang/main.json b/lang/main.json
index 7c38786c80..e0bde2de7f 100644
--- a/lang/main.json
+++ b/lang/main.json
@@ -344,9 +344,11 @@
"contactSupport": "Contact support",
"copied": "Copied",
"copy": "Copy",
+ "currentLinks": "Current Links",
"demoteParticipantDialog": "Are you sure you want to move this participant to viewer?",
"demoteParticipantTitle": "Move to viewer",
"dismiss": "Dismiss",
+ "dismissAll": "Dismiss All",
"displayNameRequired": "Hi! What's your name?",
"done": "Done",
"e2eeDescription": "End-to-End Encryption is currently EXPERIMENTAL. Please keep in mind that turning on end-to-end encryption will effectively disable server-side provided services such as: phone participation. Also keep in mind that the meeting will only work for people joining from browsers with support for insertable streams.",
@@ -374,6 +376,7 @@
"kickSystemTitle": "Ouch! You were kicked out of the meeting",
"kickTitle": "Ouch! {{participantDisplayName}} kicked you out of the meeting",
"learnMore": "Learn more",
+ "link": "Link",
"linkMeeting": "Link meeting",
"linkMeetingTitle": "Link meeting to Salesforce",
"liveStreaming": "Live Streaming",
@@ -439,6 +442,8 @@
"passwordNotSupported": "Setting a meeting $t(lockRoomPassword) is not supported.",
"passwordNotSupportedTitle": "$t(lockRoomPasswordUppercase) not supported",
"passwordRequired": "$t(lockRoomPasswordUppercase) required",
+ "pendingDealsDescription": "These opportunities may be related to this meeting",
+ "pendingDescription": "We found these potential matches based on participant emails",
"permissionCameraRequiredError": "Camera permission is required to participate in conferences with video. Please grant it in Settings",
"permissionErrorTitle": "Permission required",
"permissionMicRequiredError": "Microphone permission is required to participate in conferences with audio. Please grant it in Settings",
@@ -465,6 +470,7 @@
"reservationError": "Reservation system error",
"reservationErrorMsg": "Error code: {{code}}, message: {{msg}}",
"retry": "Retry",
+ "salesforceDataError": "Failed to load Salesforce data",
"screenSharingAudio": "Share audio",
"screenSharingFailed": "Oops! Something went wrong, we weren't able to start screen sharing!",
"screenSharingFailedTitle": "Screen sharing failed!",
@@ -516,6 +522,8 @@
"stopRecordingWarning": "Are you sure you would like to stop the recording?",
"stopStreamingWarning": "Are you sure you would like to stop the live streaming?",
"streamKey": "Live stream key",
+ "suggestedAccounts": "Suggested Accounts",
+ "suggestedDeals": "Suggested Deals",
"thankYou": "Thank you for using {{appName}}!",
"token": "token",
"tokenAuthFailed": "Sorry, you're not allowed to join this call.",
@@ -540,6 +548,7 @@
"tokenAuthUnsupported": "Token URL is not supported.",
"transcribing": "Transcribing",
"unauthenticatedAccessDisabled": "This call requires authentication. Please login in order to proceed.",
+ "unlink": "Unlink",
"unlockRoom": "Remove meeting $t(lockRoomPassword)",
"user": "User",
"userIdentifier": "User identifier",
@@ -820,6 +829,10 @@
"audioUnmuteBlockedDescription": "Mic unmute operation has been temporarily blocked because of system limits.",
"audioUnmuteBlockedTitle": "Mic unmute blocked!",
"chatMessages": "Chat messages",
+ "confirmAccountError": "Failed to confirm account",
+ "confirmAccountSuccess": "Account confirmed",
+ "confirmDealError": "Failed to confirm deal",
+ "confirmDealSuccess": "Deal confirmed",
"connectedOneMember": "{{name}} joined the meeting",
"connectedThreePlusMembers": "{{name}} and many others joined the meeting",
"connectedTwoMembers": "{{first}} and {{second}} joined the meeting",
@@ -833,6 +846,8 @@
"disabledIframeSecondaryNative": "Embedding {{domain}} is only meant for demo purposes, so this call will disconnect in {{timeout}} minutes.",
"disabledIframeSecondaryWeb": "Embedding {{domain}} is only meant for demo purposes, so this call will disconnect in {{timeout}} minutes. Please use <a href='{{jaasDomain}}' rel='noopener noreferrer' target='_blank'>Jitsi as a Service</a> for production embedding!",
"disconnected": "disconnected",
+ "dismissError": "Failed to dismiss suggestions",
+ "dismissSuccess": "Suggestions dismissed",
"displayNotifications": "Display notifications for",
"dontRemindMe": "Do not remind me",
"focus": "Conference focus",
@@ -909,6 +924,8 @@
"suggestRecordingAction": "Start",
"suggestRecordingDescription": "Would you like to start a recording?",
"suggestRecordingTitle": "Record this meeting",
+ "unlinkFromSalesforceError": "Failed to unlink from Salesforce",
+ "unlinkFromSalesforceSuccess": "Unlinked from Salesforce",
"unmute": "Unmute Audio",
"unmuteScreen": "Start screen sharing",
"unmuteVideo": "Unmute Video",
diff --git a/react/features/salesforce/components/native/CurrentLinksSection.tsx b/react/features/salesforce/components/native/CurrentLinksSection.tsx
new file mode 100644
index 0000000000..a9981a5acd
--- /dev/null
+++ b/react/features/salesforce/components/native/CurrentLinksSection.tsx
@@ -0,0 +1,112 @@
+import React from 'react';
+import { useTranslation } from 'react-i18next';
+import { Text, View, ViewStyle } from 'react-native';
+
+import {
+ IconRecordAccount,
+ IconRecordContact,
+ IconRecordLead,
+ IconRecordOpportunity
+} from '../../../base/icons/svg';
+import { BUTTON_TYPES } from '../../../base/ui/constants.native';
+import { formatAmount } from '../../functions';
+import { ISalesforceData, SalesforceObjectType } from '../../types';
+
+import { RecordListItem } from './RecordListItem';
+import styles from './styles';
+
+interface IProps {
+ onUnlink: (type: SalesforceObjectType, id: string) => void;
+ salesforceData: ISalesforceData | null;
+ unlinkingId: string | null;
+}
+
+/**
+ * Component for displaying currently linked Salesforce objects with unlink buttons.
+ *
+ * @param {IProps} props - Component props.
+ * @returns {React.ReactElement}
+ */
+export const CurrentLinksSection = ({ salesforceData, unlinkingId, onUnlink }: IProps) => {
+ const { t } = useTranslation();
+
+ const hasAccount = Boolean(salesforceData?.account);
+ const hasLeads = salesforceData?.leads?.length;
+ const hasContacts = salesforceData?.contacts?.length;
+ const hasDeal = Boolean(salesforceData?.deal);
+ const hasAnyLinks = hasAccount || hasLeads || hasContacts || hasDeal;
+
+ if (!hasAnyLinks) {
+ return null;
+ }
+
+ return (
+ <View style = { styles.currentLinksSection as ViewStyle }>
+ <Text style = { styles.sectionTitle }>{t('dialog.currentLinks')}</Text>
+
+ {salesforceData?.account && (
+ <RecordListItem
+ actionLabelKey = 'dialog.unlink'
+ actionType = { BUTTON_TYPES.TERTIARY }
+ compact = { true }
+ disabled = { unlinkingId !== null }
+ icon = { IconRecordAccount }
+ isLoading = { unlinkingId === salesforceData.account.accountId }
+ metadata = { t('record.type.account') }
+ name = { salesforceData.account.accountName }
+ /* eslint-disable-next-line react/jsx-no-bind */
+ onAction = { () => onUnlink('Account', salesforceData.account!.accountId) } />
+ )}
+
+ {salesforceData?.leads?.map(lead => (
+ <RecordListItem
+ actionLabelKey = 'dialog.unlink'
+ actionType = { BUTTON_TYPES.TERTIARY }
+ compact = { true }
+ disabled = { unlinkingId !== null }
+ icon = { IconRecordLead }
+ isLoading = { unlinkingId === lead.leadId }
+ key = { lead.leadId }
+ metadata = { `${t('record.type.lead')}${lead.leadCompany ? ` \u2022 ${lead.leadCompany}` : ''}` }
+ name = { lead.leadName }
+ /* eslint-disable-next-line react/jsx-no-bind */
+ onAction = { () => onUnlink('Lead', lead.leadId) } />
+ ))}
+
+ {salesforceData?.contacts?.map(contact => (
+ <RecordListItem
+ actionLabelKey = 'dialog.unlink'
+ actionType = { BUTTON_TYPES.TERTIARY }
+ compact = { true }
+ disabled = { unlinkingId !== null }
+ icon = { IconRecordContact }
+ isLoading = { unlinkingId === contact.contactId }
+ key = { contact.contactId }
+ metadata = { t('record.type.contact') }
+ name = { contact.contactName }
+ /* eslint-disable-next-line react/jsx-no-bind */
+ onAction = { () => onUnlink('Contact', contact.contactId) } />
+ ))}
+
+ {salesforceData?.deal && (
+ <RecordListItem
+ actionLabelKey = 'dialog.unlink'
+ actionType = { BUTTON_TYPES.TERTIARY }
+ compact = { true }
+ disabled = { unlinkingId !== null }
+ icon = { IconRecordOpportunity }
+ isLoading = { unlinkingId === salesforceData.deal.opportunityId }
+ metadata = { `${salesforceData.deal.opportunityStage}${
+ salesforceData.deal.amount !== undefined
+ ? ` \u2022 $${formatAmount(salesforceData.deal.amount)}`
+ : ''
+ }` }
+ name = { salesforceData.deal.opportunityName }
+ /* eslint-disable-next-line react/jsx-no-bind */
+ onAction = { () => onUnlink('Opportunity', salesforceData.deal!.opportunityId) } />
+ )}
+ </View>
+ );
+};
+
+export default CurrentLinksSection;
diff --git a/react/features/salesforce/components/native/PendingSection.tsx b/react/features/salesforce/components/native/PendingSection.tsx
new file mode 100644
index 0000000000..c86c3d8c08
--- /dev/null
+++ b/react/features/salesforce/components/native/PendingSection.tsx
@@ -0,0 +1,137 @@
+import React from 'react';
+import { useTranslation } from 'react-i18next';
+import { Text, View, ViewStyle } from 'react-native';
+
+import LoadingIndicator from '../../../base/react/components/native/LoadingIndicator';
+import Button from '../../../base/ui/components/native/Button';
+import { BUTTON_TYPES } from '../../../base/ui/constants.native';
+import { formatAmount } from '../../functions';
+import { IPendingAccount, IPendingDeal } from '../../types';
+
+import styles from './styles';
+
+interface IPendingAccountsSectionProps {
+ confirmingId: string | null;
+ items: IPendingAccount[];
+ onConfirm: (accountId: string) => void;
+ onRejectAll: () => void;
+ rejecting: boolean;
+ type: 'accounts';
+}
+
+interface IPendingDealsSectionProps {
+ confirmingId: string | null;
+ items: IPendingDeal[];
+ onConfirm: (opportunityId: string) => void;
+ onRejectAll: () => void;
+ rejecting: boolean;
+ type: 'deals';
+}
+
+type IProps = IPendingAccountsSectionProps | IPendingDealsSectionProps;
+
+/**
+ * Component for displaying pending Salesforce suggestions (accounts or deals).
+ *
+ * @param {IProps} props - Component props.
+ * @returns {React.ReactElement}
+ */
+export const PendingSection = (props: IProps) => {
+ const { t } = useTranslation();
+ const { items, confirmingId, rejecting, onConfirm, onRejectAll, type } = props;
+
+ if (items.length === 0) {
+ return null;
+ }
+
+ const isAccounts = type === 'accounts';
+ const title = isAccounts
+ ? t('dialog.suggestedAccounts')
+ : t('dialog.suggestedDeals');
+ const description = isAccounts
+ ? t('dialog.pendingDescription')
+ : t('dialog.pendingDealsDescription');
+
+ return (
+ <View style = { styles.section as ViewStyle }>
+ <View style = { styles.pendingHeader as ViewStyle }>
+ <Text style = { styles.sectionTitle }>{title}</Text>
+ <Button
+ disabled = { rejecting }
+ labelKey = 'dialog.dismissAll'
+ onClick = { onRejectAll }
+ type = { BUTTON_TYPES.TERTIARY } />
+ </View>
+ <Text style = { styles.sectionDescription }>{description}</Text>
+
+ {isAccounts ? (
+ (items as IPendingAccount[]).map(account => (
+ <View
+ key = { account.accountId }
+ style = { styles.listItem as ViewStyle }>
+ <View style = { styles.listItemInfo as ViewStyle }>
+ <Text
+ numberOfLines = { 1 }
+ style = { styles.listItemName }>
+ {account.accountName}
+ </Text>
+ {account.matchedEmailDomain && (
+ <Text style = { styles.listItemMeta }>
+ {account.matchedEmailDomain}
+ </Text>
+ )}
+ </View>
+ <View style = { styles.listItemButtonContainer as ViewStyle }>
+ {confirmingId === account.accountId ? (
+ <View style = { styles.listItemSpinnerContainer as ViewStyle }>
+ <LoadingIndicator size = 'small' />
+ </View>
+ ) : (
+ <Button
+ disabled = { confirmingId !== null }
+ labelKey = 'dialog.confirm'
+ /* eslint-disable-next-line react/jsx-no-bind */
+ onClick = { () => onConfirm(account.accountId) }
+ type = { BUTTON_TYPES.PRIMARY } />
+ )}
+ </View>
+ </View>
+ ))
+ ) : (
+ (items as IPendingDeal[]).map(deal => (
+ <View
+ key = { deal.opportunityId }
+ style = { styles.listItem as ViewStyle }>
+ <View style = { styles.listItemInfo as ViewStyle }>
+ <Text
+ numberOfLines = { 1 }
+ style = { styles.listItemName }>
+ {deal.opportunityName}
+ </Text>
+ <Text style = { styles.listItemMeta }>
+ {deal.opportunityStage}
+ {deal.amount !== undefined && ` \u2022 $${formatAmount(deal.amount)}`}
+ </Text>
+ </View>
+ <View style = { styles.listItemButtonContainer as ViewStyle }>
+ {confirmingId === deal.opportunityId ? (
+ <View style = { styles.listItemSpinnerContainer as ViewStyle }>
+ <LoadingIndicator size = 'small' />
+ </View>
+ ) : (
+ <Button
+ disabled = { confirmingId !== null }
+ labelKey = 'dialog.confirm'
+ /* eslint-disable-next-line react/jsx-no-bind */
+ onClick = { () => onConfirm(deal.opportunityId) }
+ type = { BUTTON_TYPES.PRIMARY } />
+ )}
+ </View>
+ </View>
+ ))
+ )}
+ </View>
+ );
+};
+
+export default PendingSection;
diff --git a/react/features/salesforce/components/native/RecordItem.tsx b/react/features/salesforce/components/native/RecordItem.tsx
deleted file mode 100644
index 57bbcb54de..0000000000
--- a/react/features/salesforce/components/native/RecordItem.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-import React from 'react';
-import { useTranslation } from 'react-i18next';
-import { GestureResponderEvent, Text, TextStyle, TouchableHighlight, View, ViewStyle } from 'react-native';
-
-import Icon from '../../../base/icons/components/Icon';
-import { RECORD_TYPE } from '../../constants';
-
-import styles from './styles';
-
-/**
- * The type of the React {@code Component} props of {@link RecordItem}.
- */
-interface IProps {
-
- /**
- * The id of the record.
- */
- id?: string;
-
- /**
- * The name of the record.
- */
- name?: string;
-
- /**
- * The handler for the click event.
- */
- onClick?: (e?: GestureResponderEvent | React.MouseEvent) => void;
-
- /**
- * The type of the record.
- */
- type?: string;
-}
-
-/**
- * Component to render Record data.
- *
- * @param {IProps} props - The props of the component.
- * @returns {React$Element<any>}
- */
-export const RecordItem = ({
- id,
- name,
- type,
- /* eslint-disable-next-line @typescript-eslint/no-empty-function */
- onClick = () => {}
-}: IProps) => {
- const { t } = useTranslation();
- const IconRecord = RECORD_TYPE[type ?? ''].icon;
-
- return (
- <TouchableHighlight onPress = { onClick }>
- <View
- key = { `record-${id}` }
- style = { styles.recordItem as ViewStyle }
-
- // @ts-ignore
- title = { name }>
- <View style = { styles.recordTypeIcon as ViewStyle }>
- {IconRecord && (
- <Icon
- src = { IconRecord }
- style = { styles.recordIcon } />
- )}
- </View>
- <View style = { styles.recordDetails as ViewStyle }>
- <Text
- key = { name }
- numberOfLines = { 1 }
- style = { styles.recordName as TextStyle }>
- {name}
- </Text>
- <Text
- key = { type }
- style = { styles.recordType }>
- {t(RECORD_TYPE[type ?? ''].label)}
- </Text>
- </View>
- </View>
- </TouchableHighlight>
- );
-};
diff --git a/react/features/salesforce/components/native/RecordListItem.tsx b/react/features/salesforce/components/native/RecordListItem.tsx
new file mode 100644
index 0000000000..d358932a7c
--- /dev/null
+++ b/react/features/salesforce/components/native/RecordListItem.tsx
@@ -0,0 +1,114 @@
+import React from 'react';
+import { Text, View, ViewStyle } from 'react-native';
+
+import Icon from '../../../base/icons/components/Icon';
+import LoadingIndicator from '../../../base/react/components/native/LoadingIndicator';
+import Button from '../../../base/ui/components/native/Button';
+import { BUTTON_TYPES } from '../../../base/ui/constants.native';
+
+import styles from './styles';
+
+interface IProps {
+
+ /**
+ * Translation key for the action button.
+ */
+ actionLabelKey: string;
+
+ /**
+ * Button type for the action button.
+ */
+ actionType?: BUTTON_TYPES;
+
+ /**
+ * Whether to use compact styling (no background, less padding).
+ */
+ compact?: boolean;
+
+ /**
+ * Whether the action button should be disabled.
+ */
+ disabled?: boolean;
+
+ /**
+ * The icon component to display.
+ */
+ icon: Function;
+
+ /**
+ * Whether this item's action is in progress.
+ */
+ isLoading?: boolean;
+
+ /**
+ * Secondary text (type label, company, stage, etc.).
+ */
+ metadata?: string;
+
+ /**
+ * The primary display name.
+ */
+ name: string;
+
+ /**
+ * Click handler for the action button.
+ */
+ onAction: () => void;
+}
+
+/**
+ * Reusable list item component for Salesforce records with an action button.
+ *
+ * @param {IProps} props - Component props.
+ * @returns {React.ReactElement}
+ */
+export const RecordListItem = ({
+ actionLabelKey,
+ actionType = BUTTON_TYPES.PRIMARY,
+ compact = false,
+ disabled = false,
+ icon,
+ isLoading = false,
+ metadata,
+ name,
+ onAction
+}: IProps) => {
+ const itemStyle = compact ? styles.listItemCompact : styles.listItem;
+
+ return (
+ <View style = { itemStyle as ViewStyle }>
+ <View style = { styles.listItemIcon as ViewStyle }>
+ <Icon
+ size = { 24 }
+ src = { icon } />
+ </View>
+ <View style = { styles.listItemInfo as ViewStyle }>
+ <Text
+ numberOfLines = { 1 }
+ style = { styles.listItemName }>
+ {name}
+ </Text>
+ {metadata && (
+ <Text style = { styles.listItemMeta }>
+ {metadata}
+ </Text>
+ )}
+ </View>
+ <View style = { styles.listItemButtonContainer as ViewStyle }>
+ {isLoading ? (
+ <View style = { styles.listItemSpinnerContainer as ViewStyle }>
+ <LoadingIndicator size = 'small' />
+ </View>
+ ) : (
+ <Button
+ disabled = { disabled }
+ labelKey = { actionLabelKey }
+ onClick = { onAction }
+ type = { actionType } />
+ )}
+ </View>
+ </View>
+ );
+};
+
+export default RecordListItem;
diff --git a/react/features/salesforce/components/native/SalesforceLinkDialog.tsx b/react/features/salesforce/components/native/SalesforceLinkDialog.tsx
index 41868317ff..2ad1889db6 100644
--- a/react/features/salesforce/components/native/SalesforceLinkDialog.tsx
+++ b/react/features/salesforce/components/native/SalesforceLinkDialog.tsx
@@ -1,22 +1,17 @@
import React, { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { Platform, ScrollView, Text, View, ViewStyle } from 'react-native';
-import { SafeAreaView } from 'react-native-safe-area-context';
-import { useSelector } from 'react-redux';
+import { ScrollView, Text, View, ViewStyle } from 'react-native';
-import { IReduxState } from '../../../app/types';
import { IconSearch } from '../../../base/icons/svg';
import JitsiScreen from '../../../base/modal/components/JitsiScreen';
import LoadingIndicator from '../../../base/react/components/native/LoadingIndicator';
-import Button from '../../../base/ui/components/native/Button';
+import { StyleType } from '../../../base/styles/functions.any';
import Input from '../../../base/ui/components/native/Input';
-import { BUTTON_TYPES } from '../../../base/ui/constants.native';
-import { navigate } from '../../../mobile/navigation/components/conference/ConferenceNavigationContainerRef';
-import { screen } from '../../../mobile/navigation/routes';
-import { CONTENT_HEIGHT_OFFSET, LIST_HEIGHT_OFFSET, NOTES_LINES, NOTES_MAX_LENGTH } from '../../constants';
import { useSalesforceLinkDialog } from '../../useSalesforceLinkDialog';
-import { RecordItem } from './RecordItem';
+import { CurrentLinksSection } from './CurrentLinksSection';
+import { PendingSection } from './PendingSection';
+import { SearchResultsSection } from './SearchResultsSection';
import styles from './styles';
/**
@@ -26,160 +21,116 @@ import styles from './styles';
*/
const SalesforceLinkDialog = () => {
const { t } = useTranslation();
- const { clientHeight } = useSelector((state: IReduxState) => state['features/base/responsive-ui']);
+
const {
- hasDetailsErrors,
- hasRecordsErrors,
- isLoading,
- linkMeeting,
- notes,
- records,
+ salesforceData,
+ searchResults,
+ hasSearchResults,
+ hasPendingAccounts,
+ hasPendingDeals,
searchTerm,
- selectedRecord,
- selectedRecordOwner,
- setNotes,
+ isLoading,
+ isSearching,
+ error,
+ confirmingAccountId,
+ confirmingDealId,
+ rejectingAccounts,
+ rejectingDeals,
+ linkingId,
+ unlinkingId,
setSearchTerm,
- setSelectedRecord,
- showNoResults,
- showSearchResults
+ handleConfirmAccount,
+ handleRejectAllAccounts,
+ handleConfirmDeal,
+ handleRejectAllDeals,
+ handleLinkRecord,
+ handleUnlinkRecord
} = useSalesforceLinkDialog();
- const handlePress = useCallback(() => {
- navigate(screen.conference.main);
- selectedRecord && linkMeeting();
- }, [ navigate, linkMeeting ]);
+ const handleSearchChange = useCallback((value: string) => {
+ setSearchTerm(value);
+ }, [ setSearchTerm ]);
- const renderSpinner = () => (
- <View style = { [ styles.recordsSpinner, { height: clientHeight - CONTENT_HEIGHT_OFFSET } ] as ViewStyle[] }>
- <LoadingIndicator />
- </View>
- );
-
- const renderDetailsErrors = () => (
- <Text style = { styles.detailsError }>
- {t('dialog.searchResultsDetailsError')}
- </Text>
- );
-
- const renderSelection = () => (
- <SafeAreaView>
- <ScrollView
- bounces = { false }
- style = { [ styles.selectedRecord, { height: clientHeight - CONTENT_HEIGHT_OFFSET } ] as ViewStyle[] }>
- <View style = { styles.recordInfo as ViewStyle }>
- <RecordItem { ...selectedRecord } />
- { selectedRecordOwner && <RecordItem { ...selectedRecordOwner } /> }
- { hasDetailsErrors && renderDetailsErrors() }
- </View>
- <Text style = { styles.addNote }>
- {t('dialog.addOptionalNote')}
- </Text>
- <Input
- customStyles = {{ container: styles.notes }}
- maxLength = { NOTES_MAX_LENGTH }
- minHeight = { Platform.OS === 'ios' && NOTES_LINES ? 20 * NOTES_LINES : undefined }
- multiline = { true }
- numberOfLines = { Platform.OS === 'ios' ? undefined : NOTES_LINES }
- /* eslint-disable-next-line react/jsx-no-bind */
- onChange = { value => setNotes(value) }
- placeholder = { t('dialog.addMeetingNote') }
- value = { notes } />
- </ScrollView>
- </SafeAreaView>
- );
-
- const renderRecordsSearch = () => (
- <View style = { styles.recordsSearchContainer as ViewStyle }>
+ const renderSearch = () => (
+ <View style = { styles.searchContainer as ViewStyle }>
<Input
icon = { IconSearch }
- maxLength = { NOTES_MAX_LENGTH }
- /* eslint-disable-next-line react/jsx-no-bind */
- onChange = { value => setSearchTerm(value) }
+ onChange = { handleSearchChange }
placeholder = { t('dialog.searchInSalesforce') }
- value = { searchTerm ?? '' } />
- {(!isLoading && !hasRecordsErrors) && (
- <Text style = { styles.resultLabel }>
- {showSearchResults
- ? t('dialog.searchResults', { count: records.length })
- : t('dialog.recentlyUsedObjects')
- }
- </Text>
- )}
- </View>
- );
-
- const renderNoRecords = () => showNoResults && (
- <View style = { [ styles.noRecords, { height: clientHeight - CONTENT_HEIGHT_OFFSET } ] as ViewStyle[] }>
- <Text style = { styles.noRecordsText }>
- {t('dialog.searchResultsNotFound')}
- </Text>
- <Text style = { styles.noRecordsText }>
- {t('dialog.searchResultsTryAgain')}
- </Text>
- </View>
- );
-
- const renderRecordsError = () => (
- <View style = { [ styles.recordsError, { height: clientHeight - CONTENT_HEIGHT_OFFSET } ] as ViewStyle[] }>
- <Text style = { styles.recordsErrorText }>
- {t('dialog.searchResultsError')}
- </Text>
+ value = { searchTerm } />
</View>
);
const renderContent = () => {
if (isLoading) {
- return renderSpinner();
- }
- if (hasRecordsErrors) {
- return renderRecordsError();
- }
- if (showNoResults) {
- return renderNoRecords();
- }
- if (selectedRecord) {
- return renderSelection();
+ return (
+ <View style = { styles.spinnerContainer as ViewStyle }>
+ <LoadingIndicator />
+ </View>
+ );
}
return (
- <SafeAreaView>
- <ScrollView
- bounces = { false }
- style = { [ styles.recordList, { height: clientHeight - LIST_HEIGHT_OFFSET } ] as ViewStyle[] }>
- {records.map((item: any) => (
- <RecordItem
- key = { `record-${item.id}` }
- /* eslint-disable-next-line react/jsx-no-bind */
- onClick = { () => setSelectedRecord(item) }
- { ...item } />
- ))}
- </ScrollView>
- </SafeAreaView>
+ <ScrollView
+ bounces = { false }
+ contentContainerStyle = { styles.scrollContent }>
+ {/* Search spinner */}
+ {isSearching && (
+ <View style = { styles.spinnerContainer as ViewStyle }>
+ <LoadingIndicator />
+ </View>
+ )}
+
+ {/* Search results */}
+ {!isSearching && hasSearchResults && searchResults && (
+ <SearchResultsSection
+ linkingId = { linkingId }
+ onLink = { handleLinkRecord }
+ results = { searchResults } />
+ )}
+
+ {/* Error (only show when not searching and no results) */}
+ {!isSearching && !hasSearchResults && error && (
+ <Text style = { styles.errorText }>
+ {error}
+ </Text>
+ )}
+
+ {/* Pending accounts (when not searching) */}
+ {!searchTerm && hasPendingAccounts && salesforceData?.pendingAccounts && (
+ <PendingSection
+ confirmingId = { confirmingAccountId }
+ items = { salesforceData.pendingAccounts }
+ onConfirm = { handleConfirmAccount }
+ onRejectAll = { handleRejectAllAccounts }
+ rejecting = { rejectingAccounts }
+ type = 'accounts' />
+ )}
+
+ {/* Pending deals (when not searching) */}
+ {!searchTerm && hasPendingDeals && salesforceData?.pendingDeals && (
+ <PendingSection
+ confirmingId = { confirmingDealId }
+ items = { salesforceData.pendingDeals }
+ onConfirm = { handleConfirmDeal }
+ onRejectAll = { handleRejectAllDeals }
+ rejecting = { rejectingDeals }
+ type = 'deals' />
+ )}
+
+ {/* Current links */}
+ <CurrentLinksSection
+ onUnlink = { handleUnlinkRecord }
+ salesforceData = { salesforceData }
+ unlinkingId = { unlinkingId } />
+ </ScrollView>
);
};
return (
- <JitsiScreen style = { styles.salesforceDialogContainer }>
- <View>
- {!selectedRecord && renderRecordsSearch()}
- {renderContent()}
- </View>
- {
- selectedRecord
- && <View>
- <Button
- labelKey = 'dialog.Cancel'
- /* eslint-disable-next-line react/jsx-no-bind */
- onClick = { () => setSelectedRecord(null) }
- style = { styles.cancelButton }
- type = { BUTTON_TYPES.SECONDARY } />
- <Button
- labelKey = 'dialog.linkMeeting'
- onClick = { handlePress }
- style = { styles.linkButton }
- type = { BUTTON_TYPES.PRIMARY } />
- </View>
- }
+ <JitsiScreen style = { styles.salesforceDialogContainer as StyleType }>
+ {renderSearch()}
+ {renderContent()}
</JitsiScreen>
);
};
diff --git a/react/features/salesforce/components/native/SearchResultsSection.tsx b/react/features/salesforce/components/native/SearchResultsSection.tsx
new file mode 100644
index 0000000000..8816af87e2
--- /dev/null
+++ b/react/features/salesforce/components/native/SearchResultsSection.tsx
@@ -0,0 +1,137 @@
+import React from 'react';
+import { useTranslation } from 'react-i18next';
+import { Text, View, ViewStyle } from 'react-native';
+
+import {
+ IconRecordAccount,
+ IconRecordContact,
+ IconRecordLead,
+ IconRecordOpportunity
+} from '../../../base/icons/svg';
+import { BUTTON_TYPES } from '../../../base/ui/constants.native';
+import { formatAmount } from '../../functions';
+import {
+ IAccountMatch,
+ IContactMatch,
+ ILeadMatch,
+ IOpportunityMatch,
+ ISearchResults,
+ SalesforceObjectType
+} from '../../types';
+
+import { RecordListItem } from './RecordListItem';
+import styles from './styles';
+
+interface IProps {
+ linkingId: string | null;
+ onLink: (type: SalesforceObjectType, data: IAccountMatch | ILeadMatch | IContactMatch | IOpportunityMatch) => void;
+ results: ISearchResults;
+}
+
+/**
+ * Component for displaying Salesforce search results with link buttons.
+ *
+ * @param {IProps} props - Component props.
+ * @returns {React.ReactElement}
+ */
+export const SearchResultsSection = ({ results, linkingId, onLink }: IProps) => {
+ const { t } = useTranslation();
+
+ const hasResults = results.accounts.length
+ || results.leads.length
+ || results.contacts.length
+ || results.opportunities.length;
+
+ if (!hasResults) {
+ return (
+ <View style = { styles.noResultsContainer as ViewStyle }>
+ <Text style = { styles.noResultsText }>
+ {t('dialog.searchResultsNotFound')}
+ </Text>
+ </View>
+ );
+ }
+
+ return (
+ <View>
+ {!!results.accounts.length && (
+ <>
+ <Text style = { styles.groupTitle }>{t('record.type.account')}</Text>
+ {results.accounts.map(account => (
+ <RecordListItem
+ actionLabelKey = 'dialog.link'
+ actionType = { BUTTON_TYPES.PRIMARY }
+ disabled = { linkingId !== null }
+ icon = { IconRecordAccount }
+ isLoading = { linkingId === account.accountId }
+ key = { account.accountId }
+ name = { account.accountName }
+ /* eslint-disable-next-line react/jsx-no-bind */
+ onAction = { () => onLink('Account', account) } />
+ ))}
+ </>
+ )}
+
+ {!!results.leads.length && (
+ <>
+ <Text style = { styles.groupTitle }>{t('record.type.lead')}</Text>
+ {results.leads.map(lead => (
+ <RecordListItem
+ actionLabelKey = 'dialog.link'
+ actionType = { BUTTON_TYPES.PRIMARY }
+ disabled = { linkingId !== null }
+ icon = { IconRecordLead }
+ isLoading = { linkingId === lead.leadId }
+ key = { lead.leadId }
+ metadata = { lead.leadCompany }
+ name = { lead.leadName }
+ /* eslint-disable-next-line react/jsx-no-bind */
+ onAction = { () => onLink('Lead', lead) } />
+ ))}
+ </>
+ )}
+
+ {!!results.contacts.length && (
+ <>
+ <Text style = { styles.groupTitle }>{t('record.type.contact')}</Text>
+ {results.contacts.map(contact => (
+ <RecordListItem
+ actionLabelKey = 'dialog.link'
+ actionType = { BUTTON_TYPES.PRIMARY }
+ disabled = { linkingId !== null }
+ icon = { IconRecordContact }
+ isLoading = { linkingId === contact.contactId }
+ key = { contact.contactId }
+ metadata = { contact.contactEmail }
+ name = { contact.contactName }
+ /* eslint-disable-next-line react/jsx-no-bind */
+ onAction = { () => onLink('Contact', contact) } />
+ ))}
+ </>
+ )}
+
+ {!!results.opportunities.length && (
+ <>
+ <Text style = { styles.groupTitle }>{t('record.type.opportunity')}</Text>
+ {results.opportunities.map(opp => (
+ <RecordListItem
+ actionLabelKey = 'dialog.link'
+ actionType = { BUTTON_TYPES.PRIMARY }
+ disabled = { linkingId !== null }
+ icon = { IconRecordOpportunity }
+ isLoading = { linkingId === opp.opportunityId }
+ key = { opp.opportunityId }
+ metadata = { `${opp.opportunityStage}${
+ opp.amount !== undefined ? ` \u2022 $${formatAmount(opp.amount)}` : ''
+ }` }
+ name = { opp.opportunityName }
+ /* eslint-disable-next-line react/jsx-no-bind */
+ onAction = { () => onLink('Opportunity', opp) } />
+ ))}
+ </>
+ )}
+ </View>
+ );
+};
+
+export default SearchResultsSection;
diff --git a/react/features/salesforce/components/native/styles.ts b/react/features/salesforce/components/native/styles.ts
index bb3908db88..2a256606e4 100644
--- a/react/features/salesforce/components/native/styles.ts
+++ b/react/features/salesforce/components/native/styles.ts
@@ -1,148 +1,164 @@
+import { TextStyle, ViewStyle } from 'react-native';
+
import BaseTheme from '../../../base/ui/components/BaseTheme.native';
-export default {
+interface IStyles {
+ currentLinksSection: ViewStyle;
+ errorText: TextStyle;
+ groupTitle: TextStyle;
+ listItem: ViewStyle;
+ listItemButtonContainer: ViewStyle;
+ listItemCompact: ViewStyle;
+ listItemIcon: ViewStyle;
+ listItemInfo: ViewStyle;
+ listItemMeta: TextStyle;
+ listItemName: TextStyle;
+ listItemSpinnerContainer: ViewStyle;
+ noResultsContainer: ViewStyle;
+ noResultsText: TextStyle;
+ pendingHeader: ViewStyle;
+ salesforceDialogContainer: ViewStyle;
+ scrollContent: ViewStyle;
+ searchContainer: ViewStyle;
+ section: ViewStyle;
+ sectionDescription: TextStyle;
+ sectionTitle: TextStyle;
+ spinnerContainer: ViewStyle;
+}
+
+const styles: IStyles = {
+ // Main container
salesforceDialogContainer: {
position: 'relative',
flexDirection: 'column',
flex: 1,
- display: 'flex',
backgroundColor: BaseTheme.palette.ui01
},
- recordsSearchContainer: {
+
+ // Search
+ searchContainer: {
alignSelf: 'stretch',
backgroundColor: BaseTheme.palette.ui01,
paddingHorizontal: BaseTheme.spacing[3],
paddingTop: BaseTheme.spacing[2],
- position: 'relative'
- },
- searchIcon: {
- color: BaseTheme.palette.text03,
- fontSize: 30,
- left: 22,
- position: 'absolute',
- top: 22,
- zIndex: 2
- },
- resultLabel: {
- backgroundColor: BaseTheme.palette.ui01,
- color: BaseTheme.palette.text03,
- fontSize: 15,
- margin: 0,
- paddingBottom: 8,
- paddingTop: 16
+ paddingBottom: BaseTheme.spacing[3]
},
- recordsSpinner: {
- alignItems: 'center',
- display: 'flex',
- justifyContent: 'center',
- width: '100%'
- },
- noRecords: {
+
+ // Loading/spinner
+ spinnerContainer: {
alignItems: 'center',
- backgroundColor: BaseTheme.palette.ui01,
- display: 'flex',
- flexDirection: 'column',
justifyContent: 'center',
- padding: BaseTheme.spacing[3]
+ paddingVertical: BaseTheme.spacing[6]
},
- noRecordsText: {
- color: BaseTheme.palette.text03
+
+ // Error
+ errorText: {
+ color: BaseTheme.palette.textError,
+ textAlign: 'center',
+ padding: BaseTheme.spacing[4]
},
- recordsError: {
+
+ // No results
+ noResultsContainer: {
alignItems: 'center',
- display: 'flex',
- flexDirection: 'column',
justifyContent: 'center',
- paddingBottom: 30
- },
- recordsErrorText: {
- color: BaseTheme.palette.text03
+ padding: BaseTheme.spacing[4]
},
- recordList: {
- alignSelf: 'stretch',
- display: 'flex',
- listStyle: 'none',
- paddingVertical: BaseTheme.spacing[3],
- position: 'relative'
+ noResultsText: {
+ color: BaseTheme.palette.text03,
+ textAlign: 'center'
},
- selectedRecord: {
- alignSelf: 'stretch',
- display: 'flex',
- paddingTop: BaseTheme.spacing[3],
- position: 'relative'
+
+ // Section styles
+ section: {
+ marginBottom: BaseTheme.spacing[4],
+ paddingHorizontal: BaseTheme.spacing[3]
},
- recordInfo: {
- backgroundColor: BaseTheme.palette.ui03,
- borderRadius: BaseTheme.shape.borderRadius,
- display: 'flex',
- margin: BaseTheme.spacing[3],
- position: 'relative'
+ sectionTitle: {
+ fontSize: 15,
+ fontWeight: '600',
+ color: BaseTheme.palette.text01,
+ marginBottom: BaseTheme.spacing[2]
},
- detailsError: {
+ sectionDescription: {
+ fontSize: 13,
color: BaseTheme.palette.text03,
- padding: BaseTheme.spacing[3]
+ marginBottom: BaseTheme.spacing[3]
},
- addNote: {
- color: BaseTheme.palette.text01,
- margin: BaseTheme.spacing[3]
- },
- notes: {
- alignItems: 'flex-start',
- backgroundColor: BaseTheme.palette.field01,
- borderColor: BaseTheme.palette.ui05,
- borderRadius: BaseTheme.shape.borderRadius,
- borderWidth: 1,
- color: BaseTheme.palette.text01,
- lineHeight: 18,
- marginHorizontal: BaseTheme.spacing[3],
- marginVertical: BaseTheme.spacing[2],
- overflow: 'hidden',
- padding: BaseTheme.spacing[2],
- textAlignVertical: 'top'
+
+ // Pending section header
+ pendingHeader: {
+ flexDirection: 'row',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: BaseTheme.spacing[2]
},
- cancelButton: {
- margin: BaseTheme.spacing[2]
+
+ // Current links section
+ currentLinksSection: {
+ marginTop: BaseTheme.spacing[4],
+ paddingTop: BaseTheme.spacing[3],
+ paddingHorizontal: BaseTheme.spacing[3],
+ borderTopWidth: 1,
+ borderTopColor: BaseTheme.palette.ui05
},
- linkButton: {
+
+ // Group title (for search results)
+ groupTitle: {
+ fontSize: 12,
+ fontWeight: '600',
+ color: BaseTheme.palette.text03,
+ textTransform: 'uppercase',
+ marginTop: BaseTheme.spacing[3],
marginBottom: BaseTheme.spacing[2],
- marginHorizontal: BaseTheme.spacing[2]
- },
- recordItem: {
- alignItems: 'center',
- display: 'flex',
- flex: 1,
- flexDirection: 'row',
paddingHorizontal: BaseTheme.spacing[3]
},
- recordTypeIcon: {
+
+ // RecordListItem styles
+ listItem: {
+ flexDirection: 'row',
alignItems: 'center',
+ backgroundColor: BaseTheme.palette.ui03,
borderRadius: BaseTheme.shape.borderRadius,
- display: 'flex',
- height: 40,
- justifyContent: 'center',
- marginRight: BaseTheme.spacing[3],
- width: 40
+ padding: BaseTheme.spacing[3],
+ marginBottom: BaseTheme.spacing[2],
+ marginHorizontal: BaseTheme.spacing[3]
},
- recordIcon: {
+ listItemCompact: {
+ flexDirection: 'row',
alignItems: 'center',
- display: 'flex',
- justifyContent: 'center'
+ paddingVertical: BaseTheme.spacing[2]
},
- recordDetails: {
- display: 'flex',
- flex: 1,
- flexDirection: 'column',
- justifyContent: 'space-around',
- overflow: 'hidden',
- paddingVertical: BaseTheme.spacing[3]
+ listItemIcon: {
+ width: 24,
+ height: 24,
+ marginRight: BaseTheme.spacing[3]
},
- recordName: {
- color: BaseTheme.palette.text01,
+ listItemInfo: {
+ flex: 1
+ },
+ listItemName: {
fontSize: 15,
- overflow: 'hidden'
+ color: BaseTheme.palette.text01
},
- recordType: {
- color: BaseTheme.palette.text01,
- fontSize: 13
+ listItemMeta: {
+ fontSize: 13,
+ color: BaseTheme.palette.text03,
+ marginTop: 2
+ },
+ listItemButtonContainer: {
+ marginLeft: BaseTheme.spacing[3]
+ },
+ listItemSpinnerContainer: {
+ width: 70,
+ alignItems: 'center',
+ justifyContent: 'center'
+ },
+
+ // Scroll container
+ scrollContent: {
+ flexGrow: 1
}
};
+
+export default styles;
diff --git a/react/features/salesforce/components/web/CurrentLinksSection.tsx b/react/features/salesforce/components/web/CurrentLinksSection.tsx
new file mode 100644
index 0000000000..90aaf7b545
--- /dev/null
+++ b/react/features/salesforce/components/web/CurrentLinksSection.tsx
@@ -0,0 +1,146 @@
+import React, { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import { makeStyles } from 'tss-react/mui';
+
+import {
+ IconRecordAccount,
+ IconRecordContact,
+ IconRecordLead,
+ IconRecordOpportunity
+} from '../../../base/icons/svg';
+import { BUTTON_TYPES } from '../../../base/ui/constants.web';
+import { ISalesforceData, SalesforceObjectType } from '../../types';
+
+import { RecordListItem } from './RecordListItem';
+
+interface IProps {
+ onUnlink: (type: SalesforceObjectType, id: string) => void;
+ salesforceData: ISalesforceData | null;
+ unlinkingId: string | null;
+}
+
+const useStyles = makeStyles()(theme => {
+ return {
+ section: {
+ marginTop: '24px',
+ paddingTop: '16px',
+ borderTop: `1px solid ${theme.palette.ui05}`
+ },
+ title: {
+ fontSize: '0.875rem',
+ fontWeight: 600,
+ margin: '0 0 12px 0'
+ },
+ list: {
+ listStyle: 'none',
+ margin: 0,
+ padding: 0
+ }
+ };
+});
+
+/**
+ * Component for displaying currently linked Salesforce objects with unlink buttons.
+ *
+ * @param {IProps} props - Component props.
+ * @returns {React.ReactElement}
+ */
+export const CurrentLinksSection = ({ salesforceData, unlinkingId, onUnlink }: IProps) => {
+ const { t } = useTranslation();
+ const { classes } = useStyles();
+
+ const hasAccount = Boolean(salesforceData?.account);
+ const hasLeads = salesforceData?.leads?.length;
+ const hasContacts = salesforceData?.contacts?.length;
+ const hasDeal = Boolean(salesforceData?.deal);
+ const hasAnyLinks = hasAccount || hasLeads || hasContacts || hasDeal;
+
+ const handleUnlinkAccount = useCallback((id: string) => {
+ onUnlink('Account', id);
+ }, [ onUnlink ]);
+
+ const handleUnlinkLead = useCallback((id: string) => {
+ onUnlink('Lead', id);
+ }, [ onUnlink ]);
+
+ const handleUnlinkContact = useCallback((id: string) => {
+ onUnlink('Contact', id);
+ }, [ onUnlink ]);
+
+ const handleUnlinkOpportunity = useCallback((id: string) => {
+ onUnlink('Opportunity', id);
+ }, [ onUnlink ]);
+
+ if (!hasAnyLinks) {
+ return null;
+ }
+
+ return (
+ <div className = { classes.section }>
+ <h3 className = { classes.title }>{t('dialog.currentLinks')}</h3>
+ <ul className = { classes.list }>
+ {salesforceData?.account && (
+ <RecordListItem
+ actionLabelKey = 'dialog.unlink'
+ actionType = { BUTTON_TYPES.TERTIARY }
+ disabled = { unlinkingId !== null }
+ icon = { IconRecordAccount }
+ isLoading = { unlinkingId === salesforceData.account.accountId }
+ key = { salesforceData.account.accountId }
+ metadata = { t('record.type.account') }
+ name = { salesforceData.account.accountName }
+ onAction = { handleUnlinkAccount }
+ record = { salesforceData.account.accountId } />
+ )}
+
+ {salesforceData?.leads?.map(lead => (
+ <RecordListItem
+ actionLabelKey = 'dialog.unlink'
+ actionType = { BUTTON_TYPES.TERTIARY }
+ disabled = { unlinkingId !== null }
+ icon = { IconRecordLead }
+ isLoading = { unlinkingId === lead.leadId }
+ key = { lead.leadId }
+ metadata = { `${t('record.type.lead')}${lead.leadCompany ? ` \u2022 ${lead.leadCompany}` : ''}` }
+ name = { lead.leadName }
+ onAction = { handleUnlinkLead }
+ record = { lead.leadId } />
+ ))}
+
+ {salesforceData?.contacts?.map(contact => (
+ <RecordListItem
+ actionLabelKey = 'dialog.unlink'
+ actionType = { BUTTON_TYPES.TERTIARY }
+ disabled = { unlinkingId !== null }
+ icon = { IconRecordContact }
+ isLoading = { unlinkingId === contact.contactId }
+ key = { contact.contactId }
+ metadata = { t('record.type.contact') }
+ name = { contact.contactName }
+ onAction = { handleUnlinkContact }
+ record = { contact.contactId } />
+ ))}
+
+ {salesforceData?.deal && (
+ <RecordListItem
+ actionLabelKey = 'dialog.unlink'
+ actionType = { BUTTON_TYPES.TERTIARY }
+ disabled = { unlinkingId !== null }
+ icon = { IconRecordOpportunity }
+ isLoading = { unlinkingId === salesforceData.deal.opportunityId }
+ key = { salesforceData.deal.opportunityId }
+ metadata = { `${salesforceData.deal.opportunityStage}${
+ salesforceData.deal.amount !== undefined
+ ? ` \u2022 $${salesforceData.deal.amount.toLocaleString()}`
+ : ''
+ }` }
+ name = { salesforceData.deal.opportunityName }
+ onAction = { handleUnlinkOpportunity }
+ record = { salesforceData.deal.opportunityId } />
+ )}
+ </ul>
+ </div>
+ );
+};
+
+export default CurrentLinksSection;
diff --git a/react/features/salesforce/components/web/PendingSection.tsx b/react/features/salesforce/components/web/PendingSection.tsx
new file mode 100644
index 0000000000..608ed19a67
--- /dev/null
+++ b/react/features/salesforce/components/web/PendingSection.tsx
@@ -0,0 +1,198 @@
+import React from 'react';
+import { useTranslation } from 'react-i18next';
+import { makeStyles } from 'tss-react/mui';
+
+import Button from '../../../base/ui/components/web/Button';
+import Spinner from '../../../base/ui/components/web/Spinner';
+import { BUTTON_TYPES } from '../../../base/ui/constants.web';
+import { IPendingAccount, IPendingDeal } from '../../types';
+
+interface IPendingAccountsSectionProps {
+ confirmingId: string | null;
+ items: IPendingAccount[];
+ onConfirm: (accountId: string) => void;
+ onRejectAll: () => void;
+ rejecting: boolean;
+ type: 'accounts';
+}
+
+interface IPendingDealsSectionProps {
+ confirmingId: string | null;
+ items: IPendingDeal[];
+ onConfirm: (opportunityId: string) => void;
+ onRejectAll: () => void;
+ rejecting: boolean;
+ type: 'deals';
+}
+
+type IProps = IPendingAccountsSectionProps | IPendingDealsSectionProps;
+
+const useStyles = makeStyles()(theme => {
+ return {
+ section: {
+ marginBottom: '24px'
+ },
+ header: {
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '8px'
+ },
+ title: {
+ fontSize: '0.875rem',
+ fontWeight: 600,
+ margin: 0
+ },
+ description: {
+ fontSize: '0.75rem',
+ color: theme.palette.text03,
+ marginBottom: '12px'
+ },
+ list: {
+ listStyle: 'none',
+ margin: 0,
+ padding: 0
+ },
+ item: {
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ padding: '12px',
+ backgroundColor: theme.palette.inputFieldBackground,
+ borderRadius: theme.shape.borderRadius,
+ marginBottom: '8px',
+
+ '&:last-child': {
+ marginBottom: 0
+ }
+ },
+ itemInfo: {
+ flex: 1,
+ minWidth: 0
+ },
+ itemName: {
+ fontSize: '0.875rem',
+ fontWeight: 500,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap'
+ },
+ itemMeta: {
+ fontSize: '0.75rem',
+ color: theme.palette.text03,
+ marginTop: '2px'
+ },
+ buttonContainer: {
+ marginLeft: '12px',
+ flexShrink: 0
+ },
+ spinnerContainer: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '70px'
+ }
+ };
+});
+
+/**
+ * Component for displaying pending Salesforce suggestions (accounts or deals).
+ *
+ * @param {IProps} props - Component props.
+ * @returns {React.ReactElement}
+ */
+export const PendingSection = (props: IProps) => {
+ const { t } = useTranslation();
+ const { classes } = useStyles();
+
+ const { items, confirmingId, rejecting, onConfirm, onRejectAll, type } = props;
+
+ if (items.length === 0) {
+ return null;
+ }
+
+ const isAccounts = type === 'accounts';
+ const title = isAccounts
+ ? t('dialog.suggestedAccounts')
+ : t('dialog.suggestedDeals');
+ const description = isAccounts
+ ? t('dialog.pendingDescription')
+ : t('dialog.pendingDealsDescription');
+
+ return (
+ <div className = { classes.section }>
+ <div className = { classes.header }>
+ <h3 className = { classes.title }>{title}</h3>
+ <Button
+ disabled = { rejecting }
+ labelKey = 'dialog.dismissAll'
+ onClick = { onRejectAll }
+ size = 'small'
+ type = { BUTTON_TYPES.TERTIARY } />
+ </div>
+ <p className = { classes.description }>{description}</p>
+ <ul className = { classes.list }>
+ {isAccounts ? (
+ (items as IPendingAccount[]).map(account => (
+ <li
+ className = { classes.item }
+ key = { account.accountId }>
+ <div className = { classes.itemInfo }>
+ <div className = { classes.itemName }>{account.accountName}</div>
+ {account.matchedEmailDomain && (
+ <div className = { classes.itemMeta }>{account.matchedEmailDomain}</div>
+ )}
+ </div>
+ <div className = { classes.buttonContainer }>
+ {confirmingId === account.accountId ? (
+ <div className = { classes.spinnerContainer }>
+ <Spinner size = 'small' />
+ </div>
+ ) : (
+ <Button
+ disabled = { confirmingId !== null }
+ labelKey = 'dialog.confirm'
+ /* eslint-disable-next-line react/jsx-no-bind */
+ onClick = { () => onConfirm(account.accountId) }
+ size = 'small'
+ type = { BUTTON_TYPES.PRIMARY } />
+ )}
+ </div>
+ </li>
+ ))
+ ) : (
+ (items as IPendingDeal[]).map(deal => (
+ <li
+ className = { classes.item }
+ key = { deal.opportunityId }>
+ <div className = { classes.itemInfo }>
+ <div className = { classes.itemName }>{deal.opportunityName}</div>
+ <div className = { classes.itemMeta }>
+ {deal.opportunityStage}
+ {deal.amount !== undefined && ` \u2022 $${deal.amount.toLocaleString()}`}
+ </div>
+ </div>
+ <div className = { classes.buttonContainer }>
+ {confirmingId === deal.opportunityId ? (
+ <div className = { classes.spinnerContainer }>
+ <Spinner size = 'small' />
+ </div>
+ ) : (
+ <Button
+ disabled = { confirmingId !== null }
+ labelKey = 'dialog.confirm'
+ /* eslint-disable-next-line react/jsx-no-bind */
+ onClick = { () => onConfirm(deal.opportunityId) }
+ size = 'small'
+ type = { BUTTON_TYPES.PRIMARY } />
+ )}
+ </div>
+ </li>
+ ))
+ )}
+ </ul>
+ </div>
+ );
+};
+
+export default PendingSection;
diff --git a/react/features/salesforce/components/web/RecordItem.tsx b/react/features/salesforce/components/web/RecordItem.tsx
deleted file mode 100644
index f26fd501fd..0000000000
--- a/react/features/salesforce/components/web/RecordItem.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-import React from 'react';
-import { useTranslation } from 'react-i18next';
-import { makeStyles } from 'tss-react/mui';
-
-import { RECORD_TYPE } from '../../constants';
-
-/**
- * The type of the React {@code Component} props of {@link RecordItem}.
- */
-interface IProps {
-
- /**
- * The id of the record.
- */
- id?: string;
-
- /**
- * The name of the record.
- */
- name?: string;
-
- /**
- * The handler for the click event.
- */
- onClick?: (e?: React.MouseEvent) => void;
-
- /**
- * The type of the record.
- */
- type?: string;
-}
-
-const useStyles = makeStyles()(theme => {
- return {
- recordItem: {
- display: 'flex',
- alignItems: 'center'
- },
- recordTypeIcon: {
- borderRadius: theme.shape.borderRadius,
- height: '40px',
- marginRight: '16px',
- width: '40px'
- },
- recordDetails: {
- display: 'flex',
- flex: 1,
- flexDirection: 'column',
- justifyContent: 'space-around',
- overflow: 'hidden',
- padding: '12px 0',
- textOverflow: 'ellipsis'
- },
- recordName: {
- fontSize: '1rem',
- fontWeight: 400,
- lineHeight: '1.25rem',
- overflow: 'hidden',
- textOverflow: 'ellipsis'
- },
- recordType: {
- fontSize: '0.875rem',
- fontWeight: 400,
- lineHeight: '1.125rem'
- }
- };
-});
-
-/**
- * Component to render Record data.
- *
- * @param {IProps} props - The props of the component.
- * @returns {React$Element<any>}
- */
-export const RecordItem = ({
- id,
- name,
- // eslint-disable-next-line @typescript-eslint/no-empty-function
- onClick = () => {},
- type
-}: IProps) => {
- const { t } = useTranslation();
- const Icon = RECORD_TYPE[type as keyof typeof RECORD_TYPE].icon;
- const { classes } = useStyles();
-
- return (
- <li
- className = { classes.recordItem }
- key = { `record-${id}` }
- onClick = { onClick }
- title = { name }>
- <div className = { classes.recordTypeIcon }>{Icon && <Icon />}</div>
- <div className = { classes.recordDetails }>
- <div
- className = { classes.recordName }
- key = { name }>
- {name}
- </div>
- <div
- className = { classes.recordType }
- key = { type }>
- {t(RECORD_TYPE[type ?? ''].label)}
- </div>
- </div>
- </li>
- );
-};
diff --git a/react/features/salesforce/components/web/RecordListItem.tsx b/react/features/salesforce/components/web/RecordListItem.tsx
new file mode 100644
index 0000000000..6fbb896b5c
--- /dev/null
+++ b/react/features/salesforce/components/web/RecordListItem.tsx
@@ -0,0 +1,160 @@
+import React, { useCallback } from 'react';
+import { makeStyles } from 'tss-react/mui';
+
+import Button from '../../../base/ui/components/web/Button';
+import Spinner from '../../../base/ui/components/web/Spinner';
+import { BUTTON_TYPES } from '../../../base/ui/constants.web';
+
+interface IProps<T> {
+
+ /**
+ * Translation key for the action button.
+ */
+ actionLabelKey: string;
+
+ /**
+ * Button type for the action button.
+ */
+ actionType?: BUTTON_TYPES;
+
+ /**
+ * Whether the action button should be disabled.
+ */
+ disabled?: boolean;
+
+ /**
+ * The icon component to display.
+ */
+ icon: React.ComponentType;
+
+ /**
+ * Whether this item's action is in progress.
+ */
+ isLoading?: boolean;
+
+ /**
+ * Secondary text (type label, company, stage, etc.).
+ */
+ metadata?: string;
+
+ /**
+ * The primary display name.
+ */
+ name: string;
+
+ /**
+ * Click handler for the action button.
+ */
+ onAction: (record: T) => void;
+
+ /**
+ * The record data to pass back when action is triggered.
+ */
+ record: T;
+}
+
+const useStyles = makeStyles()(theme => {
+ return {
+ item: {
+ display: 'flex',
+ alignItems: 'center',
+ padding: '10px 12px',
+ backgroundColor: theme.palette.ui03,
+ borderRadius: theme.shape.borderRadius,
+ marginBottom: '6px',
+
+ '&:last-child': {
+ marginBottom: 0
+ }
+ },
+ iconContainer: {
+ width: '24px',
+ height: '24px',
+ marginRight: '12px',
+ flexShrink: 0,
+
+ '& svg': {
+ width: '24px',
+ height: '24px',
+ borderRadius: theme.shape.borderRadius
+ }
+ },
+ itemInfo: {
+ flex: 1,
+ minWidth: 0
+ },
+ itemName: {
+ fontSize: '0.875rem',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap'
+ },
+ itemMeta: {
+ fontSize: '0.75rem',
+ color: theme.palette.text03,
+ marginTop: '2px'
+ },
+ buttonContainer: {
+ marginLeft: '12px',
+ flexShrink: 0
+ },
+ spinnerContainer: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '70px'
+ }
+ };
+});
+
+/**
+ * Reusable list item component for Salesforce records with an action button.
+ *
+ * @param {IProps} props - Component props.
+ * @returns {React.ReactElement}
+ */
+export const RecordListItem = <T, >({
+ actionLabelKey,
+ actionType = BUTTON_TYPES.PRIMARY,
+ disabled = false,
+ icon: Icon,
+ isLoading = false,
+ metadata,
+ name,
+ onAction,
+ record
+}: IProps<T>) => {
+ const { classes } = useStyles();
+
+ const handleAction = useCallback(() => {
+ onAction(record);
+ }, [ onAction, record ]);
+
+ return (
+ <div className = { classes.item }>
+ <div className = { classes.iconContainer }>
+ <Icon />
+ </div>
+ <div className = { classes.itemInfo }>
+ <div className = { classes.itemName }>{name}</div>
+ {metadata && <div className = { classes.itemMeta }>{metadata}</div>}
+ </div>
+ <div className = { classes.buttonContainer }>
+ {isLoading ? (
+ <div className = { classes.spinnerContainer }>
+ <Spinner size = 'small' />
+ </div>
+ ) : (
+ <Button
+ disabled = { disabled }
+ labelKey = { actionLabelKey }
+ onClick = { handleAction }
+ size = 'small'
+ type = { actionType } />
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default RecordListItem;
diff --git a/react/features/salesforce/components/web/SalesforceLinkDialog.tsx b/react/features/salesforce/components/web/SalesforceLinkDialog.tsx
index bbe33c413e..f50888dfb7 100644
--- a/react/features/salesforce/components/web/SalesforceLinkDialog.tsx
+++ b/react/features/salesforce/components/web/SalesforceLinkDialog.tsx
@@ -9,21 +9,24 @@ import { IconSearch } from '../../../base/icons/svg';
import { getFieldValue } from '../../../base/react/functions';
import Dialog from '../../../base/ui/components/web/Dialog';
import Spinner from '../../../base/ui/components/web/Spinner';
-import { NOTES_MAX_LENGTH } from '../../constants';
import { useSalesforceLinkDialog } from '../../useSalesforceLinkDialog';
-import { RecordItem } from './RecordItem';
+import { CurrentLinksSection } from './CurrentLinksSection';
+import { PendingSection } from './PendingSection';
+import { SearchResultsSection } from './SearchResultsSection';
const useStyles = makeStyles()(theme => {
return {
container: {
- height: '450px',
+ minHeight: '400px',
+ maxHeight: '500px',
overflowY: 'auto',
position: 'relative'
},
- recordsSearchContainer: {
+ searchContainer: {
position: 'relative',
- padding: '1px'
+ padding: '1px',
+ marginBottom: '16px'
},
searchIcon: {
display: 'block',
@@ -34,11 +37,7 @@ const useStyles = makeStyles()(theme => {
width: 20,
height: 20
},
- resultLabel: {
- fontSize: '1rem',
- margin: '16px 0 8px'
- },
- recordsSearch: {
+ searchInput: {
backgroundColor: theme.palette.salesforceSearchBackground,
border: '1px solid',
borderRadius: theme.shape.borderRadius,
@@ -53,71 +52,16 @@ const useStyles = makeStyles()(theme => {
}
},
spinner: {
- alignItems: 'center',
- display: 'flex',
- height: 'calc(100% - 70px)',
- justifyContent: 'center',
- width: '100%',
-
- '@media (max-width: 448px)': {
- height: 'auto',
- marginTop: '24px'
- }
- },
- noRecords: {
- height: 'calc(100% - 150px)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
- flexDirection: 'column',
-
- '@media (max-width: 448px)': {
- height: 'auto',
- marginTop: '24px'
- }
+ padding: '48px 0',
+ boxSizing: 'border-box'
},
- recordsError: {
- height: 'calc(100% - 42px)',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- flexDirection: 'column',
-
- '@media (max-width: 448px)': {
- height: 'auto',
- marginTop: '24px'
- }
- },
- recordList: {
- listStyle: 'none',
- margin: '10px 0',
- padding: 0
- },
- recordInfo: {
- backgroundColor: theme.palette.inputFieldBackground,
- padding: '0 16px',
- borderRadius: theme.shape.borderRadius,
- marginBottom: '28px'
- },
- detailsError: {
- padding: '10px 0'
- },
- addNote: {
- padding: '10px 0'
- },
- notes: {
- lineHeight: '1.125rem',
- minHeight: '130px',
- resize: 'vertical',
- width: '100%',
- boxSizing: 'border-box',
- overflow: 'hidden',
- border: '1px solid',
- borderColor: theme.palette.salesforceSearchBorder,
- backgroundColor: theme.palette.inputBackground,
- color: theme.palette.inputText,
- borderRadius: theme.shape.borderRadius,
- padding: '10px 16px'
+ error: {
+ textAlign: 'center',
+ color: theme.palette.textError,
+ padding: '24px'
}
};
});
@@ -132,149 +76,139 @@ function SalesforceLinkDialog() {
const { t } = useTranslation();
const { classes, theme } = useStyles();
const dispatch = useDispatch();
+
const {
- hasDetailsErrors,
- hasRecordsErrors,
- isLoading,
- linkMeeting,
- notes,
- records,
+ salesforceData,
+ searchResults,
+ hasSearchResults,
+ hasPendingAccounts,
+ hasPendingDeals,
searchTerm,
- selectedRecord,
- selectedRecordOwner,
- setNotes,
+ isLoading,
+ isSearching,
+ error,
+ confirmingAccountId,
+ confirmingDealId,
+ rejectingAccounts,
+ rejectingDeals,
+ linkingId,
+ unlinkingId,
setSearchTerm,
- setSelectedRecord,
- showNoResults,
- showSearchResults
+ handleConfirmAccount,
+ handleRejectAllAccounts,
+ handleConfirmDeal,
+ handleRejectAllDeals,
+ handleLinkRecord,
+ handleUnlinkRecord
} = useSalesforceLinkDialog();
- const handleChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
+ const handleSearchChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
const value = getFieldValue(event);
setSearchTerm(value);
- }, [ getFieldValue ]);
-
- const handleSubmit = useCallback(() => {
- dispatch(hideDialog());
- selectedRecord && linkMeeting();
- }, [ hideDialog, linkMeeting ]);
+ }, [ setSearchTerm ]);
- const renderSpinner = () => (
- <div className = { classes.spinner }>
- <Spinner />
- </div>
- );
-
- const renderDetailsErrors = () => (
- <div className = { classes.detailsError }>
- {t('dialog.searchResultsDetailsError')}
- </div>
- );
+ const handleSearchKeyDown = useCallback((event: React.KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ }
+ }, []);
- const renderSelection = () => (
- <div>
- <div className = { classes.recordInfo }>
- <RecordItem { ...selectedRecord } />
- {selectedRecordOwner && <RecordItem { ...selectedRecordOwner } />}
- {hasDetailsErrors && renderDetailsErrors()}
- </div>
- <div className = { classes.addNote }>{t('dialog.addOptionalNote')}</div>
- <textarea
- autoFocus = { true }
- className = { classes.notes }
- maxLength = { NOTES_MAX_LENGTH }
- /* eslint-disable-next-line react/jsx-no-bind */
- onChange = { e => setNotes(e.target.value) }
- placeholder = { t('dialog.addMeetingNote') }
- rows = { 4 }
- value = { notes } />
- </div>
- );
+ const handleClose = useCallback(() => {
+ dispatch(hideDialog());
+ }, [ dispatch ]);
- const renderRecordsSearch = () => !selectedRecord && (
- <div className = { classes.recordsSearchContainer }>
+ const renderSearch = () => (
+ <div className = { classes.searchContainer }>
<Icon
className = { classes.searchIcon }
color = { theme.palette.icon03 }
src = { IconSearch } />
<input
autoComplete = 'off'
- autoFocus = { false }
- className = { classes.recordsSearch }
- name = 'recordsSearch'
- onChange = { handleChange }
+ autoFocus = { true }
+ className = { classes.searchInput }
+ name = 'salesforceSearch'
+ onChange = { handleSearchChange }
+ onKeyDown = { handleSearchKeyDown }
placeholder = { t('dialog.searchInSalesforce') }
tabIndex = { 0 }
- value = { searchTerm ?? '' } />
- {(!isLoading && !hasRecordsErrors) && (
- <div className = { classes.resultLabel }>
- {showSearchResults
- ? t('dialog.searchResults', { count: records.length })
- : t('dialog.recentlyUsedObjects')
- }
- </div>
- )}
- </div>
- );
-
- const renderNoRecords = () => showNoResults && (
- <div className = { classes.noRecords }>
- <div>{t('dialog.searchResultsNotFound')}</div>
- <div>{t('dialog.searchResultsTryAgain')}</div>
- </div>
- );
-
- const renderRecordsError = () => (
- <div className = { classes.recordsError }>
- {t('dialog.searchResultsError')}
+ value = { searchTerm } />
</div>
);
const renderContent = () => {
if (isLoading) {
- return renderSpinner();
- }
- if (hasRecordsErrors) {
- return renderRecordsError();
- }
- if (showNoResults) {
- return renderNoRecords();
- }
- if (selectedRecord) {
- return renderSelection();
+ return (
+ <div className = { classes.spinner }>
+ <Spinner />
+ </div>
+ );
}
return (
- <ul className = { classes.recordList }>
- {records.map((item: any) => (
- <RecordItem
- key = { `record-${item.id}` }
- /* eslint-disable-next-line react/jsx-no-bind */
- onClick = { () => setSelectedRecord(item) }
- { ...item } />
- ))}
- </ul>
+ <>
+ {/* Search spinner */}
+ {isSearching && (
+ <div className = { classes.spinner }>
+ <Spinner />
+ </div>
+ )}
+
+ {/* Search results */}
+ {!isSearching && hasSearchResults && searchResults && (
+ <SearchResultsSection
+ linkingId = { linkingId }
+ onLink = { handleLinkRecord }
+ results = { searchResults } />
+ )}
+
+ {/* Error (only show when not searching and no results) */}
+ {!isSearching && !hasSearchResults && error && (
+ <div className = { classes.error }>
+ {error}
+ </div>
+ )}
+
+ {/* Pending suggestions (when not searching) */}
+ {!searchTerm && hasPendingAccounts && salesforceData?.pendingAccounts && (
+ <PendingSection
+ confirmingId = { confirmingAccountId }
+ items = { salesforceData.pendingAccounts }
+ onConfirm = { handleConfirmAccount }
+ onRejectAll = { handleRejectAllAccounts }
+ rejecting = { rejectingAccounts }
+ type = 'accounts' />
+ )}
+
+ {!searchTerm && hasPendingDeals && salesforceData?.pendingDeals && (
+ <PendingSection
+ confirmingId = { confirmingDealId }
+ items = { salesforceData.pendingDeals }
+ onConfirm = { handleConfirmDeal }
+ onRejectAll = { handleRejectAllDeals }
+ rejecting = { rejectingDeals }
+ type = 'deals' />
+ )}
+
+ {/* Current links */}
+ <CurrentLinksSection
+ onUnlink = { handleUnlinkRecord }
+ salesforceData = { salesforceData }
+ unlinkingId = { unlinkingId } />
+ </>
);
};
return (
<Dialog
- back = {{
- hidden: !selectedRecord,
- onClick: () => setSelectedRecord(null),
- translationKey: 'dialog.Back'
- }}
cancel = {{ hidden: true }}
disableEnter = { true }
- ok = {{
- translationKey: 'dialog.linkMeeting',
- hidden: !selectedRecord
- }}
- onSubmit = { handleSubmit }
+ ok = {{ hidden: true }}
+ onCancel = { handleClose }
titleKey = 'dialog.linkMeetingTitle'>
- <div className = { classes.container } >
- {renderRecordsSearch()}
+ <div className = { classes.container }>
+ {renderSearch()}
{renderContent()}
</div>
</Dialog>
diff --git a/react/features/salesforce/components/web/SearchResultsSection.tsx b/react/features/salesforce/components/web/SearchResultsSection.tsx
new file mode 100644
index 0000000000..fb3b67fcd8
--- /dev/null
+++ b/react/features/salesforce/components/web/SearchResultsSection.tsx
@@ -0,0 +1,183 @@
+import React, { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import { makeStyles } from 'tss-react/mui';
+
+import {
+ IconRecordAccount,
+ IconRecordContact,
+ IconRecordLead,
+ IconRecordOpportunity
+} from '../../../base/icons/svg';
+import { BUTTON_TYPES } from '../../../base/ui/constants.web';
+import {
+ IAccountMatch,
+ IContactMatch,
+ ILeadMatch,
+ IOpportunityMatch,
+ ISearchResults,
+ SalesforceObjectType
+} from '../../types';
+
+import { RecordListItem } from './RecordListItem';
+
+interface IProps {
+ linkingId: string | null;
+ onLink: (type: SalesforceObjectType, data: IAccountMatch | ILeadMatch | IContactMatch | IOpportunityMatch) => void;
+ results: ISearchResults;
+}
+
+const useStyles = makeStyles()(theme => {
+ return {
+ section: {
+ marginBottom: '16px'
+ },
+ groupTitle: {
+ fontSize: '0.75rem',
+ fontWeight: 600,
+ color: theme.palette.text03,
+ textTransform: 'uppercase',
+ margin: '16px 0 8px 0'
+ },
+ list: {
+ listStyle: 'none',
+ margin: 0,
+ padding: 0
+ },
+ noResults: {
+ textAlign: 'center',
+ color: theme.palette.text03,
+ padding: '24px'
+ }
+ };
+});
+
+/**
+ * Component for displaying Salesforce search results with link buttons.
+ *
+ * @param {IProps} props - Component props.
+ * @returns {React.ReactElement}
+ */
+export const SearchResultsSection = ({ results, linkingId, onLink }: IProps) => {
+ const { t } = useTranslation();
+ const { classes } = useStyles();
+
+ const hasResults = results.accounts.length
+ || results.leads.length
+ || results.contacts.length
+ || results.opportunities.length;
+
+ const handleLinkAccount = useCallback((account: IAccountMatch) => {
+ onLink('Account', account);
+ }, [ onLink ]);
+
+ const handleLinkLead = useCallback((lead: ILeadMatch) => {
+ onLink('Lead', lead);
+ }, [ onLink ]);
+
+ const handleLinkContact = useCallback((contact: IContactMatch) => {
+ onLink('Contact', contact);
+ }, [ onLink ]);
+
+ const handleLinkOpportunity = useCallback((opportunity: IOpportunityMatch) => {
+ onLink('Opportunity', opportunity);
+ }, [ onLink ]);
+
+ if (!hasResults) {
+ return (
+ <div className = { classes.noResults }>
+ {t('dialog.searchResultsNotFound')}
+ </div>
+ );
+ }
+
+ return (
+ <div className = { classes.section }>
+ {!!results.accounts.length && (
+ <>
+ <h4 className = { classes.groupTitle }>{t('record.type.account')}</h4>
+ <ul className = { classes.list }>
+ {results.accounts.map(account => (
+ <RecordListItem
+ actionLabelKey = 'dialog.link'
+ actionType = { BUTTON_TYPES.PRIMARY }
+ disabled = { linkingId !== null }
+ icon = { IconRecordAccount }
+ isLoading = { linkingId === account.accountId }
+ key = { account.accountId }
+ name = { account.accountName }
+ onAction = { handleLinkAccount }
+ record = { account } />
+ ))}
+ </ul>
+ </>
+ )}
+
+ {!!results.leads.length && (
+ <>
+ <h4 className = { classes.groupTitle }>{t('record.type.lead')}</h4>
+ <ul className = { classes.list }>
+ {results.leads.map(lead => (
+ <RecordListItem
+ actionLabelKey = 'dialog.link'
+ actionType = { BUTTON_TYPES.PRIMARY }
+ disabled = { linkingId !== null }
+ icon = { IconRecordLead }
+ isLoading = { linkingId === lead.leadId }
+ key = { lead.leadId }
+ metadata = { lead.leadCompany }
+ name = { lead.leadName }
+ onAction = { handleLinkLead }
+ record = { lead } />
+ ))}
+ </ul>
+ </>
+ )}
+
+ {!!results.contacts.length && (
+ <>
+ <h4 className = { classes.groupTitle }>{t('record.type.contact')}</h4>
+ <ul className = { classes.list }>
+ {results.contacts.map(contact => (
+ <RecordListItem
+ actionLabelKey = 'dialog.link'
+ actionType = { BUTTON_TYPES.PRIMARY }
+ disabled = { linkingId !== null }
+ icon = { IconRecordContact }
+ isLoading = { linkingId === contact.contactId }
+ key = { contact.contactId }
+ metadata = { contact.contactEmail }
+ name = { contact.contactName }
+ onAction = { handleLinkContact }
+ record = { contact } />
+ ))}
+ </ul>
+ </>
+ )}
+
+ {!!results.opportunities.length && (
+ <>
+ <h4 className = { classes.groupTitle }>{t('record.type.opportunity')}</h4>
+ <ul className = { classes.list }>
+ {results.opportunities.map(opp => (
+ <RecordListItem
+ actionLabelKey = 'dialog.link'
+ actionType = { BUTTON_TYPES.PRIMARY }
+ disabled = { linkingId !== null }
+ icon = { IconRecordOpportunity }
+ isLoading = { linkingId === opp.opportunityId }
+ key = { opp.opportunityId }
+ metadata = { `${opp.opportunityStage}${
+ opp.amount !== undefined ? ` \u2022 $${opp.amount.toLocaleString()}` : ''
+ }` }
+ name = { opp.opportunityName }
+ onAction = { handleLinkOpportunity }
+ record = { opp } />
+ ))}
+ </ul>
+ </>
+ )}
+ </div>
+ );
+};
+
+export default SearchResultsSection;
diff --git a/react/features/salesforce/functions.ts b/react/features/salesforce/functions.ts
index e117f674bb..dfbbf36b25 100644
--- a/react/features/salesforce/functions.ts
+++ b/react/features/salesforce/functions.ts
@@ -1,7 +1,31 @@
import { IReduxState } from '../app/types';
-import { doGetJSON } from '../base/util/httpUtils';
import { isInBreakoutRoom } from '../breakout-rooms/functions';
+import {
+ IAccountMatch,
+ IConfirmAccountResult,
+ IConfirmDealResult,
+ IContactMatch,
+ ILeadMatch,
+ ILinkResult,
+ IOpportunityMatch,
+ ISalesforceData,
+ ISearchResults,
+ SalesforceObjectType
+} from './types';
+
+/**
+ * Formats a number with thousand separators.
+ * Uses a regex approach that works reliably in React Native
+ * (toLocaleString has known issues on Android and iOS with Hermes).
+ *
+ * @param {number} amount - The number to format.
+ * @returns {string} The formatted number string.
+ */
+export function formatAmount(amount: number): string {
+ return amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
+}
+
/**
* Determines whether Salesforce is enabled for the current conference.
*
@@ -17,98 +41,188 @@ export const isSalesforceEnabled = (state: IReduxState) => {
};
/**
- * Fetches the Salesforce records that were most recently interacted with.
+ * Helper to make authenticated requests to the meet-metrics API.
*
- * @param {string} url - The endpoint for the session records.
- * @param {string} jwt - The JWT needed for authentication.
+ * @param {string} url - The full URL to fetch.
+ * @param {string} jwt - The JWT token for authentication.
+ * @param {RequestInit} options - Additional fetch options.
* @returns {Promise<any>}
*/
-export async function getRecentSessionRecords(
- url: string,
- jwt: string
-) {
- return doGetJSON(`${url}/records/recents`, true, {
+async function fetchWithAuth(url: string, jwt: string, options: RequestInit = {}): Promise<any> {
+ const res = await fetch(url, {
+ ...options,
headers: {
- 'Authorization': `Bearer ${jwt}`
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${jwt}`,
+ ...options.headers
}
});
+
+ const json = await res.json();
+
+ return res.ok ? json : Promise.reject(json);
}
/**
- * Fetches the Salesforce records that match the search criteria.
+ * Fetches the Salesforce data for a session including current links and pending suggestions.
*
- * @param {string} url - The endpoint for the session records.
+ * @param {string} url - The base URL for the meet-metrics API.
* @param {string} jwt - The JWT needed for authentication.
- * @param {string} text - The search term for the session record to find.
- * @returns {Promise<any>}
+ * @param {string} sessionId - The meeting session ID.
+ * @returns {Promise<ISalesforceData>}
*/
-export async function searchSessionRecords(
+export async function getSessionSalesforceData(
url: string,
jwt: string,
- text: string
-) {
- return doGetJSON(`${url}/records?text=${text}`, true, {
- headers: {
- 'Authorization': `Bearer ${jwt}`
- }
+ sessionId: string
+): Promise<ISalesforceData> {
+ const response = await fetchWithAuth(`${url}/api/sessions/crm`, jwt, {
+ method: 'POST',
+ body: JSON.stringify({ sessionIds: [ sessionId ] })
});
+
+ // Extract data for this specific session from the batch response
+ const sessionData = response?.crmDataBySession?.[sessionId]?.salesforce;
+
+ return sessionData || null;
}
/**
-* Fetches the Salesforce record details from the server.
-*
-* @param {string} url - The endpoint for the record details.
-* @param {string} jwt - The JWT needed for authentication.
-* @param {Object} item - The item for which details are being retrieved.
-* @returns {Promise<any>}
-*/
-export async function getSessionRecordDetails(
+ * Searches Salesforce objects (Accounts, Leads, Contacts, Opportunities).
+ *
+ * @param {string} url - The base URL for the meet-metrics API.
+ * @param {string} jwt - The JWT needed for authentication.
+ * @param {string} query - The search query (minimum 2 characters).
+ * @returns {Promise<ISearchResults>}
+ */
+export async function searchSalesforce(
url: string,
jwt: string,
- item: {
- id: string;
- type: string;
- } | null
-) {
- const fullUrl = `${url}/records/${item?.id}?type=${item?.type}`;
-
- return doGetJSON(fullUrl, true, {
- headers: {
- 'Authorization': `Bearer ${jwt}`
- }
+ query: string
+): Promise<ISearchResults> {
+ return fetchWithAuth(`${url}/api/salesforce/search?q=${encodeURIComponent(query)}`, jwt);
+}
+
+/**
+ * Links a session to a Salesforce object.
+ *
+ * @param {string} url - The base URL for the meet-metrics API.
+ * @param {string} jwt - The JWT needed for authentication.
+ * @param {string} sessionId - The meeting session ID.
+ * @param {SalesforceObjectType} type - The type of Salesforce object.
+ * @param {Object} data - The match data for the object.
+ * @returns {Promise<ILinkResult>}
+ */
+export async function linkSession(
+ url: string,
+ jwt: string,
+ sessionId: string,
+ type: SalesforceObjectType,
+ data: IAccountMatch | ILeadMatch | IContactMatch | IOpportunityMatch
+): Promise<ILinkResult> {
+ return fetchWithAuth(`${url}/api/salesforce/sessions/${sessionId}/link`, jwt, {
+ method: 'POST',
+ body: JSON.stringify({ type, data })
});
}
/**
-* Executes the meeting linking.
-*
-* @param {string} url - The endpoint for meeting linking.
-* @param {string} jwt - The JWT needed for authentication.
-* @param {string} sessionId - The ID of the meeting session.
-* @param {Object} body - The body of the request.
-* @returns {Object}
-*/
-export async function executeLinkMeetingRequest(
+ * Confirms a pending account match and auto-links the best opportunity.
+ *
+ * @param {string} url - The base URL for the meet-metrics API.
+ * @param {string} jwt - The JWT needed for authentication.
+ * @param {string} sessionId - The meeting session ID.
+ * @param {string} accountId - The Salesforce Account ID to confirm.
+ * @returns {Promise<IConfirmAccountResult>}
+ */
+export async function confirmPendingAccount(
url: string,
jwt: string,
- sessionId: String,
- body: {
- id?: string;
- notes: string;
- type?: string;
- }
-) {
- const fullUrl = `${url}/sessions/${sessionId}/records/${body.id}`;
- const res = await fetch(fullUrl, {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${jwt}`
- },
- body: JSON.stringify(body)
+ sessionId: string,
+ accountId: string
+): Promise<IConfirmAccountResult> {
+ return fetchWithAuth(`${url}/api/salesforce/sessions/${sessionId}/confirm-account`, jwt, {
+ method: 'POST',
+ body: JSON.stringify({ accountId })
});
+}
- const json = await res.json();
+/**
+ * Rejects all pending account matches for a session.
+ *
+ * @param {string} url - The base URL for the meet-metrics API.
+ * @param {string} jwt - The JWT needed for authentication.
+ * @param {string} sessionId - The meeting session ID.
+ * @returns {Promise<ILinkResult>}
+ */
+export async function rejectPendingAccounts(
+ url: string,
+ jwt: string,
+ sessionId: string
+): Promise<ILinkResult> {
+ return fetchWithAuth(`${url}/api/salesforce/sessions/${sessionId}/pending-accounts`, jwt, {
+ method: 'DELETE'
+ });
+}
- return res.ok ? json : Promise.reject(json);
+/**
+ * Confirms a pending deal match.
+ *
+ * @param {string} url - The base URL for the meet-metrics API.
+ * @param {string} jwt - The JWT needed for authentication.
+ * @param {string} sessionId - The meeting session ID.
+ * @param {string} opportunityId - The Salesforce Opportunity ID to confirm.
+ * @returns {Promise<IConfirmDealResult>}
+ */
+export async function confirmPendingDeal(
+ url: string,
+ jwt: string,
+ sessionId: string,
+ opportunityId: string
+): Promise<IConfirmDealResult> {
+ return fetchWithAuth(`${url}/api/salesforce/sessions/${sessionId}/confirm-deal`, jwt, {
+ method: 'POST',
+ body: JSON.stringify({ opportunityId })
+ });
+}
+
+/**
+ * Rejects all pending deal matches for a session.
+ *
+ * @param {string} url - The base URL for the meet-metrics API.
+ * @param {string} jwt - The JWT needed for authentication.
+ * @param {string} sessionId - The meeting session ID.
+ * @returns {Promise<ILinkResult>}
+ */
+export async function rejectPendingDeals(
+ url: string,
+ jwt: string,
+ sessionId: string
+): Promise<ILinkResult> {
+ return fetchWithAuth(`${url}/api/salesforce/sessions/${sessionId}/pending-deals`, jwt, {
+ method: 'DELETE'
+ });
+}
+
+/**
+ * Unlinks a Salesforce object from a session.
+ *
+ * @param {string} url - The base URL for the meet-metrics API.
+ * @param {string} jwt - The JWT needed for authentication.
+ * @param {string} sessionId - The meeting session ID.
+ * @param {SalesforceObjectType} type - The type of Salesforce object to unlink.
+ * @param {string} id - The Salesforce object ID to unlink.
+ * @returns {Promise<ILinkResult>}
+ */
+export async function unlinkSession(
+ url: string,
+ jwt: string,
+ sessionId: string,
+ type: SalesforceObjectType,
+ id: string
+): Promise<ILinkResult> {
+ return fetchWithAuth(`${url}/api/salesforce/sessions/${sessionId}/link`, jwt, {
+ method: 'DELETE',
+ body: JSON.stringify({ type, id })
+ });
}
diff --git a/react/features/salesforce/types.ts b/react/features/salesforce/types.ts
new file mode 100644
index 0000000000..845319ceb3
--- /dev/null
+++ b/react/features/salesforce/types.ts
@@ -0,0 +1,166 @@
+/**
+ * Pending account suggestion awaiting user confirmation.
+ */
+export interface IPendingAccount {
+ accountId: string;
+ accountName: string;
+ matchConfidence: number;
+ matchedEmailDomain?: string;
+}
+
+/**
+ * Pending deal/opportunity suggestion awaiting user confirmation.
+ */
+export interface IPendingDeal {
+ accountId: string;
+ accountName: string;
+ amount?: number;
+ closeDate?: string;
+ isClosed?: boolean;
+ matchConfidence: number;
+ opportunityId: string;
+ opportunityName: string;
+ opportunityStage: string;
+}
+
+/**
+ * Linked account information.
+ */
+export interface ILinkedAccount {
+ accountId: string;
+ accountName: string;
+}
+
+/**
+ * Linked lead information.
+ */
+export interface ILinkedLead {
+ leadCompany?: string;
+ leadId: string;
+ leadName: string;
+}
+
+/**
+ * Linked contact information.
+ */
+export interface ILinkedContact {
+ contactId: string;
+ contactName: string;
+}
+
+/**
+ * Linked deal/opportunity information.
+ */
+export interface ILinkedDeal {
+ amount?: number;
+ closeDate?: string;
+ isClosed?: boolean;
+ isWon?: boolean;
+ opportunityId: string;
+ opportunityName: string;
+ opportunityStage: string;
+ probability?: number;
+}
+
+/**
+ * Complete Salesforce data for a session including current links and pending suggestions.
+ */
+export interface ISalesforceData {
+ account?: ILinkedAccount;
+ contacts?: ILinkedContact[];
+ deal?: ILinkedDeal;
+ leads?: ILinkedLead[];
+ pendingAccounts?: IPendingAccount[];
+ pendingDeals?: IPendingDeal[];
+}
+
+/**
+ * Account match from search results.
+ */
+export interface IAccountMatch {
+ accountId: string;
+ accountName: string;
+ matchConfidence: number;
+ matchedEmailDomain?: string;
+}
+
+/**
+ * Lead match from search results.
+ */
+export interface ILeadMatch {
+ leadCompany?: string;
+ leadEmail: string;
+ leadId: string;
+ leadName: string;
+ matchConfidence: number;
+}
+
+/**
+ * Contact match from search results.
+ */
+export interface IContactMatch {
+ accountId?: string;
+ accountName?: string;
+ contactEmail: string;
+ contactId: string;
+ contactName: string;
+ matchConfidence: number;
+}
+
+/**
+ * Opportunity match from search results.
+ */
+export interface IOpportunityMatch {
+ accountId?: string;
+ accountName?: string;
+ amount?: number;
+ closeDate?: string;
+ isClosed?: boolean;
+ matchConfidence: number;
+ opportunityId: string;
+ opportunityName: string;
+ opportunityStage: string;
+}
+
+/**
+ * Unified search results from Salesforce.
+ */
+export interface ISearchResults {
+ accounts: IAccountMatch[];
+ contacts: IContactMatch[];
+ leads: ILeadMatch[];
+ opportunities: IOpportunityMatch[];
+}
+
+/**
+ * Salesforce object type for API calls.
+ */
+export type SalesforceObjectType = 'Account' | 'Lead' | 'Contact' | 'Opportunity';
+
+/**
+ * Link result from API.
+ */
+export interface ILinkResult {
+ error?: string;
+ success: boolean;
+}
+
+/**
+ * Confirm pending account result.
+ */
+export interface IConfirmAccountResult {
+ error?: string;
+ linkedOpportunity?: {
+ opportunityId: string;
+ opportunityName: string;
+ };
+ success: boolean;
+}
+
+/**
+ * Confirm pending deal result.
+ */
+export interface IConfirmDealResult {
+ error?: string;
+ success: boolean;
+}
diff --git a/react/features/salesforce/useSalesforceLinkDialog.ts b/react/features/salesforce/useSalesforceLinkDialog.ts
index d5c86d33c9..c55eaaa4c2 100644
--- a/react/features/salesforce/useSalesforceLinkDialog.ts
+++ b/react/features/salesforce/useSalesforceLinkDialog.ts
@@ -1,6 +1,6 @@
-import { useCallback, useEffect, useState } from 'react';
+import { debounce } from 'lodash-es';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { GestureResponderEvent } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import { IReduxState } from '../app/types';
@@ -13,92 +13,284 @@ import {
} from '../notifications/constants';
import {
- executeLinkMeetingRequest,
- getRecentSessionRecords,
- getSessionRecordDetails,
- searchSessionRecords
+ confirmPendingAccount,
+ confirmPendingDeal,
+ getSessionSalesforceData,
+ linkSession,
+ rejectPendingAccounts,
+ rejectPendingDeals,
+ searchSalesforce,
+ unlinkSession
} from './functions';
-
-interface ISelectedRecord {
- id: string;
- name: string;
- onClick: (e?: React.MouseEvent | GestureResponderEvent) => void;
- type: string;
-}
+import {
+ IAccountMatch,
+ IContactMatch,
+ ILeadMatch,
+ IOpportunityMatch,
+ ISalesforceData,
+ ISearchResults,
+ SalesforceObjectType
+} from './types';
export const useSalesforceLinkDialog = () => {
const { t } = useTranslation();
const dispatch = useDispatch();
- const [ selectedRecord, setSelectedRecord ] = useState<ISelectedRecord | null>(null);
- const [ selectedRecordOwner, setSelectedRecordOwner ] = useState<{
- id: string; name: string; type: string; } | null>(null);
- const [ records, setRecords ] = useState([]);
- const [ isLoading, setLoading ] = useState(false);
- const [ searchTerm, setSearchTerm ] = useState<string | null>(null);
- const [ notes, setNotes ] = useState('');
- const [ hasRecordsErrors, setRecordsErrors ] = useState(false);
- const [ hasDetailsErrors, setDetailsErrors ] = useState(false);
+
+ // Redux state
const conference = useSelector(getCurrentConference);
const sessionId = conference?.getMeetingUniqueId();
const { salesforceUrl = '' } = useSelector((state: IReduxState) => state['features/base/config']);
const { jwt = '' } = useSelector((state: IReduxState) => state['features/base/jwt']);
- const showSearchResults = searchTerm && searchTerm.length > 1;
- const showNoResults = showSearchResults && records.length === 0;
+
+ // Component state
+ const [ salesforceData, setSalesforceData ] = useState<ISalesforceData | null>(null);
+ const [ searchResults, setSearchResults ] = useState<ISearchResults | null>(null);
+ const [ searchTerm, setSearchTerm ] = useState('');
+ const [ isLoading, setIsLoading ] = useState(true);
+ const [ isSearching, setIsSearching ] = useState(false);
+ const [ error, setError ] = useState<string | null>(null);
+
+ // Loading states for actions
+ const [ confirmingAccountId, setConfirmingAccountId ] = useState<string | null>(null);
+ const [ confirmingDealId, setConfirmingDealId ] = useState<string | null>(null);
+ const [ rejectingAccounts, setRejectingAccounts ] = useState(false);
+ const [ rejectingDeals, setRejectingDeals ] = useState(false);
+ const [ linkingId, setLinkingId ] = useState<string | null>(null);
+ const [ unlinkingId, setUnlinkingId ] = useState<string | null>(null);
+
+ /**
+ * Refreshes the Salesforce data for the current session.
+ */
+ const refreshSalesforceData = useCallback(async () => {
+ if (!sessionId) {
+ return;
+ }
+
+ try {
+ const data = await getSessionSalesforceData(salesforceUrl, jwt, sessionId);
+
+ setSalesforceData(data);
+ setError(null);
+ } catch (err: any) {
+ console.error('Failed to fetch Salesforce data:', err);
+ setError(err?.error || t('dialog.salesforceDataError'));
+ }
+ }, [ salesforceUrl, jwt, sessionId, t ]);
+
+ /**
+ * Performs a search in Salesforce.
+ */
+ const performSearch = useCallback(async (query: string) => {
+ if (query.length < 2) {
+ setSearchResults(null);
+
+ return;
+ }
+
+ setIsSearching(true);
+
+ try {
+ const results = await searchSalesforce(salesforceUrl, jwt, query);
+
+ setSearchResults(results);
+ setError(null);
+ } catch (err: any) {
+ console.error('Salesforce search failed:', err);
+ setError(err?.error || t('dialog.searchResultsError'));
+ setSearchResults(null);
+ } finally {
+ setIsSearching(false);
+ }
+ }, [ salesforceUrl, jwt, t ]);
+
+ // Debounced search
+ const debouncedSearch = useMemo(
+ () => debounce(performSearch, 500),
+ [ performSearch ]
+ );
+
+ // Track if component is mounted
+ const isMounted = useRef(true);
useEffect(() => {
- const fetchRecords = async () => {
- setRecordsErrors(false);
- setLoading(true);
-
- try {
- const text = showSearchResults ? searchTerm : null;
- const result = text
- ? await searchSessionRecords(salesforceUrl, jwt, text)
- : await getRecentSessionRecords(salesforceUrl, jwt);
-
- setRecords(result);
- } catch (error) {
- setRecordsErrors(true);
- }
+ isMounted.current = true;
- setLoading(false);
+ return () => {
+ isMounted.current = false;
};
+ }, []);
- fetchRecords();
- }, [
- getRecentSessionRecords,
- jwt,
- salesforceUrl,
- searchSessionRecords,
- searchTerm
- ]);
-
+ // Fetch Salesforce data on mount
useEffect(() => {
- const fetchRecordDetails = async () => {
- setDetailsErrors(false);
- setSelectedRecordOwner(null);
- try {
- const result = await getSessionRecordDetails(salesforceUrl, jwt, selectedRecord);
-
- setSelectedRecordOwner({
- id: result.id,
- name: result.ownerName,
- type: 'OWNER'
- });
- } catch (error) {
- setDetailsErrors(true);
+ const fetchData = async () => {
+ setIsLoading(true);
+ await refreshSalesforceData();
+
+ if (isMounted.current) {
+ setIsLoading(false);
}
};
- selectedRecord && fetchRecordDetails();
- }, [
- jwt,
- getSessionRecordDetails,
- salesforceUrl,
- selectedRecord
- ]);
+ fetchData();
+ }, [ refreshSalesforceData ]);
+
+ // Trigger search when search term changes
+ useEffect(() => {
+ if (searchTerm.length >= 2) {
+ debouncedSearch(searchTerm);
+ } else {
+ setSearchResults(null);
+ }
+ }, [ searchTerm, debouncedSearch ]);
+
+ /**
+ * Handles confirming a pending account.
+ */
+ const handleConfirmAccount = useCallback(async (accountId: string) => {
+ if (!sessionId) {
+ return;
+ }
+
+ setConfirmingAccountId(accountId);
+
+ try {
+ const result = await confirmPendingAccount(salesforceUrl, jwt, sessionId, accountId);
+
+ if (result.success) {
+ dispatch(showNotification({
+ titleKey: 'notify.confirmAccountSuccess',
+ uid: SALESFORCE_LINK_NOTIFICATION_ID,
+ appearance: NOTIFICATION_TYPE.SUCCESS
+ }, NOTIFICATION_TIMEOUT_TYPE.SHORT));
+
+ await refreshSalesforceData();
+ }
+ } catch (err: any) {
+ dispatch(showNotification({
+ titleKey: 'notify.confirmAccountError',
+ descriptionKey: err?.error,
+ uid: SALESFORCE_LINK_NOTIFICATION_ID,
+ appearance: NOTIFICATION_TYPE.ERROR
+ }, NOTIFICATION_TIMEOUT_TYPE.LONG));
+ } finally {
+ setConfirmingAccountId(null);
+ }
+ }, [ salesforceUrl, jwt, sessionId, dispatch, refreshSalesforceData ]);
+
+ /**
+ * Handles rejecting all pending accounts.
+ */
+ const handleRejectAllAccounts = useCallback(async () => {
+ if (!sessionId) {
+ return;
+ }
+
+ setRejectingAccounts(true);
+
+ try {
+ await rejectPendingAccounts(salesforceUrl, jwt, sessionId);
+ dispatch(showNotification({
+ titleKey: 'notify.dismissSuccess',
+ uid: SALESFORCE_LINK_NOTIFICATION_ID,
+ appearance: NOTIFICATION_TYPE.SUCCESS
+ }, NOTIFICATION_TIMEOUT_TYPE.SHORT));
+
+ await refreshSalesforceData();
+ } catch (err: any) {
+ dispatch(showNotification({
+ titleKey: 'notify.dismissError',
+ descriptionKey: err?.error,
+ uid: SALESFORCE_LINK_NOTIFICATION_ID,
+ appearance: NOTIFICATION_TYPE.ERROR
+ }, NOTIFICATION_TIMEOUT_TYPE.LONG));
+ } finally {
+ setRejectingAccounts(false);
+ }
+ }, [ salesforceUrl, jwt, sessionId, dispatch, refreshSalesforceData ]);
+
+ /**
+ * Handles confirming a pending deal.
+ */
+ const handleConfirmDeal = useCallback(async (opportunityId: string) => {
+ if (!sessionId) {
+ return;
+ }
+
+ setConfirmingDealId(opportunityId);
+
+ try {
+ const result = await confirmPendingDeal(salesforceUrl, jwt, sessionId, opportunityId);
+
+ if (result.success) {
+ dispatch(showNotification({
+ titleKey: 'notify.confirmDealSuccess',
+ uid: SALESFORCE_LINK_NOTIFICATION_ID,
+ appearance: NOTIFICATION_TYPE.SUCCESS
+ }, NOTIFICATION_TIMEOUT_TYPE.SHORT));
+
+ await refreshSalesforceData();
+ }
+ } catch (err: any) {
+ dispatch(showNotification({
+ titleKey: 'notify.confirmDealError',
+ descriptionKey: err?.error,
+ uid: SALESFORCE_LINK_NOTIFICATION_ID,
+ appearance: NOTIFICATION_TYPE.ERROR
+ }, NOTIFICATION_TIMEOUT_TYPE.LONG));
+ } finally {
+ setConfirmingDealId(null);
+ }
+ }, [ salesforceUrl, jwt, sessionId, dispatch, refreshSalesforceData ]);
+
+ /**
+ * Handles rejecting all pending deals.
+ */
+ const handleRejectAllDeals = useCallback(async () => {
+ if (!sessionId) {
+ return;
+ }
+
+ setRejectingDeals(true);
+
+ try {
+ await rejectPendingDeals(salesforceUrl, jwt, sessionId);
+ dispatch(showNotification({
+ titleKey: 'notify.dismissSuccess',
+ uid: SALESFORCE_LINK_NOTIFICATION_ID,
+ appearance: NOTIFICATION_TYPE.SUCCESS
+ }, NOTIFICATION_TIMEOUT_TYPE.SHORT));
+
+ await refreshSalesforceData();
+ } catch (err: any) {
+ dispatch(showNotification({
+ titleKey: 'notify.dismissError',
+ descriptionKey: err?.error,
+ uid: SALESFORCE_LINK_NOTIFICATION_ID,
+ appearance: NOTIFICATION_TYPE.ERROR
+ }, NOTIFICATION_TIMEOUT_TYPE.LONG));
+ } finally {
+ setRejectingDeals(false);
+ }
+ }, [ salesforceUrl, jwt, sessionId, dispatch, refreshSalesforceData ]);
+
+ /**
+ * Handles linking a record from search results.
+ */
+ const handleLinkRecord = useCallback(async (
+ type: SalesforceObjectType,
+ data: IAccountMatch | ILeadMatch | IContactMatch | IOpportunityMatch
+ ) => {
+ if (!sessionId) {
+ return;
+ }
+
+ const id = type === 'Account' ? (data as IAccountMatch).accountId
+ : type === 'Lead' ? (data as ILeadMatch).leadId
+ : type === 'Contact' ? (data as IContactMatch).contactId
+ : (data as IOpportunityMatch).opportunityId;
+
+ setLinkingId(id);
- const linkMeeting = useCallback(async () => {
dispatch(showNotification({
titleKey: 'notify.linkToSalesforceProgress',
uid: SALESFORCE_LINK_NOTIFICATION_ID,
@@ -106,51 +298,127 @@ export const useSalesforceLinkDialog = () => {
}, NOTIFICATION_TIMEOUT_TYPE.STICKY));
try {
- await executeLinkMeetingRequest(salesforceUrl, jwt, sessionId, {
- id: selectedRecord?.id,
- type: selectedRecord?.type,
- notes
- });
+ await linkSession(salesforceUrl, jwt, sessionId, type, data);
+
dispatch(hideNotification(SALESFORCE_LINK_NOTIFICATION_ID));
dispatch(showNotification({
titleKey: 'notify.linkToSalesforceSuccess',
uid: SALESFORCE_LINK_NOTIFICATION_ID,
appearance: NOTIFICATION_TYPE.SUCCESS
- }, NOTIFICATION_TIMEOUT_TYPE.LONG));
- } catch (error: any) {
+ }, NOTIFICATION_TIMEOUT_TYPE.SHORT));
+
+ // Clear search and refresh data
+ setSearchTerm('');
+ setSearchResults(null);
+ await refreshSalesforceData();
+ } catch (err: any) {
dispatch(hideNotification(SALESFORCE_LINK_NOTIFICATION_ID));
dispatch(showNotification({
titleKey: 'notify.linkToSalesforceError',
- descriptionKey: error?.messageKey && t(error.messageKey),
+ descriptionKey: err?.error,
+ uid: SALESFORCE_LINK_NOTIFICATION_ID,
+ appearance: NOTIFICATION_TYPE.ERROR
+ }, NOTIFICATION_TIMEOUT_TYPE.LONG));
+ } finally {
+ setLinkingId(null);
+ }
+ }, [ salesforceUrl, jwt, sessionId, dispatch, refreshSalesforceData ]);
+
+ /**
+ * Handles unlinking a record from the session.
+ */
+ const handleUnlinkRecord = useCallback(async (type: SalesforceObjectType, id: string) => {
+ if (!sessionId) {
+ return;
+ }
+
+ setUnlinkingId(id);
+
+ try {
+ await unlinkSession(salesforceUrl, jwt, sessionId, type, id);
+
+ dispatch(showNotification({
+ titleKey: 'notify.unlinkFromSalesforceSuccess',
+ uid: SALESFORCE_LINK_NOTIFICATION_ID,
+ appearance: NOTIFICATION_TYPE.SUCCESS
+ }, NOTIFICATION_TIMEOUT_TYPE.SHORT));
+
+ await refreshSalesforceData();
+ } catch (err: any) {
+ dispatch(showNotification({
+ titleKey: 'notify.unlinkFromSalesforceError',
+ descriptionKey: err?.error,
uid: SALESFORCE_LINK_NOTIFICATION_ID,
appearance: NOTIFICATION_TYPE.ERROR
}, NOTIFICATION_TIMEOUT_TYPE.LONG));
+ } finally {
+ setUnlinkingId(null);
}
+ }, [ salesforceUrl, jwt, sessionId, dispatch, refreshSalesforceData ]);
+
+ // Filter out already-linked items from search results
+ const filteredSearchResults = useMemo(() => {
+ if (!searchResults || !salesforceData) {
+ return searchResults;
+ }
+
+ return {
+ accounts: searchResults.accounts.filter(
+ account => salesforceData.account?.accountId !== account.accountId
+ ),
+ leads: searchResults.leads.filter(
+ lead => !salesforceData.leads?.some(l => l.leadId === lead.leadId)
+ ),
+ contacts: searchResults.contacts.filter(
+ contact => !salesforceData.contacts?.some(c => c.contactId === contact.contactId)
+ ),
+ opportunities: searchResults.opportunities.filter(
+ opp => salesforceData.deal?.opportunityId !== opp.opportunityId
+ )
+ };
+ }, [ searchResults, salesforceData ]);
- }, [
- executeLinkMeetingRequest,
- hideNotification,
- jwt,
- notes,
- salesforceUrl,
- selectedRecord,
- showNotification
- ]);
+ const hasSearchResults = filteredSearchResults
+ && (filteredSearchResults.accounts.length > 0
+ || filteredSearchResults.leads.length > 0
+ || filteredSearchResults.contacts.length > 0
+ || filteredSearchResults.opportunities.length > 0);
+
+ const hasPendingAccounts = (salesforceData?.pendingAccounts?.length ?? 0) > 0;
+ const hasPendingDeals = (salesforceData?.pendingDeals?.length ?? 0) > 0;
return {
- hasDetailsErrors,
- hasRecordsErrors,
- isLoading,
- linkMeeting,
- notes,
- records,
+ // Data
+ salesforceData,
+ searchResults: filteredSearchResults,
+ hasSearchResults,
+ hasPendingAccounts,
+ hasPendingDeals,
+
+ // State
searchTerm,
- selectedRecord,
- selectedRecordOwner,
- setNotes,
+ isLoading,
+ isSearching,
+ error,
+
+ // Action loading states
+ confirmingAccountId,
+ confirmingDealId,
+ rejectingAccounts,
+ rejectingDeals,
+ linkingId,
+ unlinkingId,
+
+ // Setters
setSearchTerm,
- setSelectedRecord,
- showNoResults,
- showSearchResults
+
+ // Actions
+ handleConfirmAccount,
+ handleRejectAllAccounts,
+ handleConfirmDeal,
+ handleRejectAllDeals,
+ handleLinkRecord,
+ handleUnlinkRecord,
+ refreshSalesforceData
};
};