snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
import { useRole, useEndpoint } from '@rocket.chat/ui-contexts';
|
||||
import { useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import GenericUpsellModal from '../../../components/GenericUpsellModal';
|
||||
import { useUpsellActions } from '../../../components/GenericUpsellModal/hooks';
|
||||
import { useExternalLink } from '../../../hooks/useExternalLink';
|
||||
import { useHasLicenseModule } from '../../../hooks/useHasLicenseModule';
|
||||
import { getURL } from '../../../lib/getURL';
|
||||
import { links } from '../../../lib/links';
|
||||
|
||||
export type AdvancedContactModalProps = {
|
||||
onCancel: () => void;
|
||||
};
|
||||
|
||||
const AdvancedContactModal = ({ onCancel }: AdvancedContactModalProps) => {
|
||||
const { t } = useTranslation();
|
||||
const isAdmin = useRole('admin');
|
||||
const { data: hasLicense = false } = useHasLicenseModule('contact-id-verification');
|
||||
const { shouldShowUpsell, handleManageSubscription } = useUpsellActions(hasLicense);
|
||||
const openExternalLink = useExternalLink();
|
||||
const eventStats = useEndpoint('POST', '/v1/statistics.telemetry');
|
||||
|
||||
const handleUpsellClick = async () => {
|
||||
eventStats({
|
||||
params: [{ eventName: 'updateCounter', settingsId: 'Advanced_Contact_Upsell_Clicks_Count' }],
|
||||
});
|
||||
return handleManageSubscription();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldShowUpsell) {
|
||||
eventStats({
|
||||
params: [{ eventName: 'updateCounter', settingsId: 'Advanced_Contact_Upsell_Views_Count' }],
|
||||
});
|
||||
}
|
||||
}, [eventStats, shouldShowUpsell]);
|
||||
|
||||
return (
|
||||
<GenericUpsellModal
|
||||
title={t('Advanced_contact_profile')}
|
||||
description={t('Advanced_contact_profile_description')}
|
||||
img={getURL('images/single-contact-id-upsell.png')}
|
||||
onClose={onCancel}
|
||||
onCancel={shouldShowUpsell ? onCancel : () => openExternalLink(links.go.omnichannelDocs)}
|
||||
cancelText={!shouldShowUpsell ? t('Learn_more') : undefined}
|
||||
onConfirm={shouldShowUpsell ? handleUpsellClick : undefined}
|
||||
annotation={!shouldShowUpsell && !isAdmin ? t('Ask_enable_advanced_contact_profile') : undefined}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdvancedContactModal;
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { ILivechatContact, Serialized } from '@rocket.chat/core-typings';
|
||||
import { Box, Button, ButtonGroup, Callout, IconButton, Tabs, TabsItem } from '@rocket.chat/fuselage';
|
||||
import { UserAvatar } from '@rocket.chat/ui-avatar';
|
||||
import {
|
||||
ContextualbarHeader,
|
||||
ContextualbarIcon,
|
||||
ContextualbarTitle,
|
||||
ContextualbarClose,
|
||||
ContextualbarDialog,
|
||||
} from '@rocket.chat/ui-client';
|
||||
import { usePermission, useRouteParameter, useSetModal } from '@rocket.chat/ui-contexts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import ReviewContactModal from './ReviewContactModal';
|
||||
import { useFormatDate } from '../../../../hooks/useFormatDate';
|
||||
import { useContactRoute } from '../../hooks/useContactRoute';
|
||||
import { useValidCustomFields } from '../hooks/useValidCustomFields';
|
||||
import ContactInfoChannels from '../tabs/ContactInfoChannels';
|
||||
import ContactInfoDetails from '../tabs/ContactInfoDetails';
|
||||
import ContactInfoHistory from '../tabs/ContactInfoHistory';
|
||||
|
||||
export type ContactInfoProps = {
|
||||
contact: Serialized<ILivechatContact>;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
const ContactInfo = ({ contact, onClose }: ContactInfoProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const setModal = useSetModal();
|
||||
const handleNavigate = useContactRoute();
|
||||
const context = useRouteParameter('context');
|
||||
|
||||
const formatDate = useFormatDate();
|
||||
const canEditContact = usePermission('edit-omnichannel-contact');
|
||||
|
||||
const { name, emails, phones, conflictingFields, createdAt, lastChat, contactManager, customFields: userCustomFields } = contact;
|
||||
|
||||
const hasConflicts = conflictingFields && conflictingFields?.length > 0;
|
||||
const customFieldEntries = useValidCustomFields(userCustomFields, 'visitor');
|
||||
|
||||
return (
|
||||
<ContextualbarDialog onClose={onClose}>
|
||||
<ContextualbarHeader>
|
||||
<ContextualbarIcon name='user' />
|
||||
<ContextualbarTitle>{t('Contact')}</ContextualbarTitle>
|
||||
<ContextualbarClose onClick={onClose} />
|
||||
</ContextualbarHeader>
|
||||
<Box display='flex' flexDirection='column' paddingInline={24}>
|
||||
{name && (
|
||||
<Box width='100%' paddingBlock={16} display='flex' alignItems='center' justifyContent='space-between'>
|
||||
<Box withTruncatedText display='flex'>
|
||||
<UserAvatar size='x40' title={name} username={name} />
|
||||
<Box withTruncatedText marginInlineStart={16} display='flex' flexDirection='column'>
|
||||
<Box withTruncatedText fontScale='h4'>
|
||||
{name}
|
||||
</Box>
|
||||
{lastChat && <Box fontScale='c1'>{`${t('Last_Chat')}: ${formatDate(lastChat.ts)}`}</Box>}
|
||||
</Box>
|
||||
</Box>
|
||||
<IconButton
|
||||
disabled={!canEditContact || hasConflicts}
|
||||
title={canEditContact ? t('Edit') : t('Not_authorized')}
|
||||
small
|
||||
icon='pencil'
|
||||
onClick={() => handleNavigate({ context: 'edit' })}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
{hasConflicts && (
|
||||
<Callout
|
||||
marginBlockEnd={8}
|
||||
alignItems='center'
|
||||
icon='members'
|
||||
actions={
|
||||
<ButtonGroup>
|
||||
<Button onClick={() => setModal(<ReviewContactModal onCancel={() => setModal(null)} contact={contact} />)} small>
|
||||
{t('See_conflicts')}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
}
|
||||
title={t('Conflicts_found', { conflicts: conflictingFields?.length })}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
<Tabs>
|
||||
<TabsItem onClick={() => handleNavigate({ context: 'details' })} selected={context === 'details'}>
|
||||
{t('Details')}
|
||||
</TabsItem>
|
||||
<TabsItem onClick={() => handleNavigate({ context: 'channels' })} selected={context === 'channels'}>
|
||||
{t('Channels')}
|
||||
</TabsItem>
|
||||
<TabsItem onClick={() => handleNavigate({ context: 'history' })} selected={context === 'history'}>
|
||||
{t('History')}
|
||||
</TabsItem>
|
||||
</Tabs>
|
||||
{context === 'details' && (
|
||||
<ContactInfoDetails
|
||||
contact={contact}
|
||||
createdAt={createdAt}
|
||||
contactManager={contactManager}
|
||||
phones={phones?.map(({ phoneNumber }) => phoneNumber)}
|
||||
emails={emails?.map(({ address }) => address)}
|
||||
customFieldEntries={customFieldEntries}
|
||||
/>
|
||||
)}
|
||||
{context === 'channels' && <ContactInfoChannels contact={contact} />}
|
||||
{context === 'history' && <ContactInfoHistory contact={contact} />}
|
||||
</ContextualbarDialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactInfo;
|
||||
@@ -0,0 +1,34 @@
|
||||
import { ContextualbarSkeleton } from '@rocket.chat/ui-client';
|
||||
import { useEndpoint, usePermission } from '@rocket.chat/ui-contexts';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import ContactInfoError from '../ContactInfoError';
|
||||
import ContactInfo from './ContactInfo';
|
||||
|
||||
export type ContactInfoWithDataProps = {
|
||||
id: string;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
const ContactInfoWithData = ({ id: contactId, onClose }: ContactInfoWithDataProps) => {
|
||||
const canViewCustomFields = usePermission('view-livechat-room-customfields');
|
||||
|
||||
const getContact = useEndpoint('GET', '/v1/omnichannel/contacts.get');
|
||||
const { data, isPending, isError } = useQuery({
|
||||
queryKey: ['getContactById', contactId],
|
||||
queryFn: () => getContact({ contactId }),
|
||||
enabled: canViewCustomFields && !!contactId,
|
||||
});
|
||||
|
||||
if (isPending) {
|
||||
return <ContextualbarSkeleton onClose={onClose} />;
|
||||
}
|
||||
|
||||
if (isError || !data?.contact) {
|
||||
return <ContactInfoError onClose={onClose} />;
|
||||
}
|
||||
|
||||
return <ContactInfo contact={data?.contact} onClose={onClose} />;
|
||||
};
|
||||
|
||||
export default ContactInfoWithData;
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { ILivechatContact, Serialized } from '@rocket.chat/core-typings';
|
||||
import { Badge, Box, Field, FieldError, FieldGroup, FieldHint, FieldLabel, FieldRow, Select } from '@rocket.chat/fuselage';
|
||||
import { GenericModal } from '@rocket.chat/ui-client';
|
||||
import type { TranslationKey } from '@rocket.chat/ui-contexts';
|
||||
import { useAtLeastOnePermission } from '@rocket.chat/ui-contexts';
|
||||
import { useMemo } from 'react';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { mapLivechatContactConflicts } from '../../../../../lib/mapLivechatContactConflicts';
|
||||
import { useHasLicenseModule } from '../../../../hooks/useHasLicenseModule';
|
||||
import { ContactManagerInput } from '../../additionalForms';
|
||||
import { useCustomFieldsMetadata } from '../../directory/hooks/useCustomFieldsMetadata';
|
||||
import { useReviewContact } from '../hooks/useReviewContact';
|
||||
|
||||
export type ReviewContactModalProps = {
|
||||
contact: Serialized<ILivechatContact>;
|
||||
onCancel: () => void;
|
||||
};
|
||||
|
||||
type HandleConflictsPayload = {
|
||||
name: string;
|
||||
contactManager: string;
|
||||
[key: string]: string;
|
||||
};
|
||||
|
||||
const ReviewContactModal = ({ contact, onCancel }: ReviewContactModalProps) => {
|
||||
const { t } = useTranslation();
|
||||
const { data: hasLicense = false } = useHasLicenseModule('livechat-enterprise');
|
||||
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<HandleConflictsPayload>();
|
||||
|
||||
const canViewCustomFields = useAtLeastOnePermission(['view-livechat-room-customfields', 'edit-livechat-room-customfields']);
|
||||
|
||||
const { data: customFieldsMetadata = [] } = useCustomFieldsMetadata({
|
||||
scope: 'visitor',
|
||||
enabled: canViewCustomFields,
|
||||
});
|
||||
|
||||
const editContact = useReviewContact(['getContactById']);
|
||||
|
||||
const handleConflicts = async ({ name, contactManager, ...customFields }: HandleConflictsPayload) => {
|
||||
const payload = {
|
||||
name,
|
||||
contactManager,
|
||||
...(customFields && { customFields }),
|
||||
wipeConflicts: true,
|
||||
};
|
||||
|
||||
editContact.mutate(
|
||||
{ contactId: contact?._id, ...payload },
|
||||
{
|
||||
onSettled: () => onCancel(),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const conflictingFields = useMemo(() => {
|
||||
const mappedConflicts = mapLivechatContactConflicts(contact, customFieldsMetadata);
|
||||
return Object.values(mappedConflicts);
|
||||
}, [contact, customFieldsMetadata]);
|
||||
|
||||
return (
|
||||
<GenericModal
|
||||
icon={null}
|
||||
variant='warning'
|
||||
onCancel={onCancel}
|
||||
confirmText={t('Save')}
|
||||
onConfirm={handleSubmit(handleConflicts)}
|
||||
annotation={t('Contact_history_is_preserved')}
|
||||
title={t('Review_contact')}
|
||||
>
|
||||
<FieldGroup>
|
||||
{conflictingFields.map(({ name, label, values }, index) => {
|
||||
const isContactManagerField = name === 'contactManager';
|
||||
const mappedOptions = values.map((option) => [option, option] as const);
|
||||
const Component = isContactManagerField ? ContactManagerInput : Select;
|
||||
|
||||
if (isContactManagerField && !hasLicense) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Field key={index}>
|
||||
<FieldLabel id={name}>{t(label as TranslationKey)}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name={name}
|
||||
control={control}
|
||||
rules={{
|
||||
required: isContactManagerField ? undefined : t('Required_field', { field: t(label as TranslationKey) }),
|
||||
}}
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<Component
|
||||
aria-labelledby={name}
|
||||
aria-describedby={`${name}-hint ${name}-error`}
|
||||
options={mappedOptions}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${name}-hint`}>
|
||||
<Box display='flex' alignItems='center'>
|
||||
<Box marginInlineEnd={4}>{t('different_values_found', { number: values.length })}</Box>
|
||||
<Badge variant='primary' small />
|
||||
</Box>
|
||||
</FieldHint>
|
||||
{errors?.[name] && <FieldError id={`${name}-error`}>{errors?.[name]?.message}</FieldError>}
|
||||
</Field>
|
||||
);
|
||||
})}
|
||||
</FieldGroup>
|
||||
</GenericModal>
|
||||
);
|
||||
};
|
||||
|
||||
export default ReviewContactModal;
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from './ContactInfoWithData';
|
||||
@@ -0,0 +1,26 @@
|
||||
import {
|
||||
ContextualbarHeader,
|
||||
ContextualbarIcon,
|
||||
ContextualbarTitle,
|
||||
ContextualbarClose,
|
||||
ContextualbarEmptyContent,
|
||||
ContextualbarDialog,
|
||||
} from '@rocket.chat/ui-client';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const ContactInfoError = ({ onClose }: { onClose: () => void }) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<ContextualbarDialog onClose={onClose}>
|
||||
<ContextualbarHeader>
|
||||
<ContextualbarIcon name='user' />
|
||||
<ContextualbarTitle>{t('Contact')}</ContextualbarTitle>
|
||||
<ContextualbarClose onClick={onClose} />
|
||||
</ContextualbarHeader>
|
||||
<ContextualbarEmptyContent icon='user' title={t('Contact_not_found')} />
|
||||
</ContextualbarDialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactInfoError;
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useRoute, useRouteParameter, useRoomToolbox } from '@rocket.chat/ui-contexts';
|
||||
|
||||
import ContactInfo from './ContactInfo';
|
||||
import ContactInfoError from './ContactInfoError';
|
||||
import EditContactInfoWithData from './EditContactInfoWithData';
|
||||
import { useOmnichannelRoom } from '../../room/contexts/RoomContext';
|
||||
|
||||
const ContactInfoRouter = () => {
|
||||
const room = useOmnichannelRoom();
|
||||
const { closeTab } = useRoomToolbox();
|
||||
|
||||
const liveRoute = useRoute('live');
|
||||
const context = useRouteParameter('context');
|
||||
|
||||
const handleCloseEdit = (): void => liveRoute.push({ id: room._id, tab: 'contact-profile' });
|
||||
|
||||
if (!room.contactId) {
|
||||
return <ContactInfoError onClose={closeTab} />;
|
||||
}
|
||||
|
||||
if (context === 'edit' && room.contactId) {
|
||||
return <EditContactInfoWithData id={room.contactId} onClose={closeTab} onCancel={handleCloseEdit} />;
|
||||
}
|
||||
|
||||
return <ContactInfo id={room.contactId} onClose={closeTab} />;
|
||||
};
|
||||
|
||||
export default ContactInfoRouter;
|
||||
@@ -0,0 +1,299 @@
|
||||
import type { ILivechatContact, Serialized } from '@rocket.chat/core-typings';
|
||||
import { ButtonGroup, Button, IconButton, Divider } from '@rocket.chat/fuselage';
|
||||
import { Field, FieldLabel, FieldRow, FieldError, TextInput } from '@rocket.chat/fuselage-forms';
|
||||
import { validateEmail } from '@rocket.chat/tools';
|
||||
import {
|
||||
CustomFieldsForm,
|
||||
ContextualbarScrollableContent,
|
||||
ContextualbarFooter,
|
||||
ContextualbarHeader,
|
||||
ContextualbarIcon,
|
||||
ContextualbarTitle,
|
||||
ContextualbarClose,
|
||||
ContextualbarDialog,
|
||||
ContextualbarSkeleton,
|
||||
} from '@rocket.chat/ui-client';
|
||||
import { useEndpoint, useSetModal } from '@rocket.chat/ui-contexts';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Fragment, useId } from 'react';
|
||||
import { Controller, useFieldArray, useForm } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import AdvancedContactModal from './AdvancedContactModal';
|
||||
import { useCreateContact } from './hooks/useCreateContact';
|
||||
import { useEditContact } from './hooks/useEditContact';
|
||||
import { useFormSubmitWithDirtyCheck } from '../../../hooks/useFormSubmitWithDirtyCheck';
|
||||
import { useHasLicenseModule } from '../../../hooks/useHasLicenseModule';
|
||||
import { hasAtLeastOnePermission } from '../../../lib/authorization';
|
||||
import { omnichannelQueryKeys } from '../../../lib/queryKeys';
|
||||
import { ContactManagerInput } from '../additionalForms';
|
||||
import { useCustomFieldsMetadata } from '../directory/hooks/useCustomFieldsMetadata';
|
||||
|
||||
type ContactNewEditProps = {
|
||||
contactData?: Serialized<ILivechatContact> | null;
|
||||
onClose: () => void;
|
||||
onCancel: () => void;
|
||||
};
|
||||
|
||||
type ContactFormData = {
|
||||
name: string;
|
||||
emails: { address: string }[];
|
||||
phones: { phoneNumber: string }[];
|
||||
customFields: Record<any, any>;
|
||||
contactManager: string;
|
||||
};
|
||||
|
||||
const DEFAULT_VALUES = {
|
||||
name: '',
|
||||
emails: [],
|
||||
phones: [],
|
||||
contactManager: '',
|
||||
customFields: {},
|
||||
};
|
||||
|
||||
const getInitialValues = (data: ContactNewEditProps['contactData']): ContactFormData => {
|
||||
if (!data) {
|
||||
return DEFAULT_VALUES;
|
||||
}
|
||||
|
||||
const { name, phones, emails, customFields, contactManager } = data ?? {};
|
||||
|
||||
return {
|
||||
name: name ?? '',
|
||||
emails: emails ?? [],
|
||||
phones: phones ?? [],
|
||||
customFields: customFields ?? {},
|
||||
contactManager: contactManager ?? '',
|
||||
};
|
||||
};
|
||||
|
||||
const validateMultipleFields = (fieldsLength: number, hasLicense: boolean) => fieldsLength >= 1 && !hasLicense;
|
||||
|
||||
const EditContactInfo = ({ contactData, onClose, onCancel }: ContactNewEditProps) => {
|
||||
const { t } = useTranslation();
|
||||
const setModal = useSetModal();
|
||||
|
||||
const { data: hasLicense = false } = useHasLicenseModule('contact-id-verification');
|
||||
const canViewCustomFields = hasAtLeastOnePermission(['view-livechat-room-customfields', 'edit-livechat-room-customfields']);
|
||||
|
||||
const editContact = useEditContact(['current-contacts']);
|
||||
const createContact = useCreateContact(['current-contacts']);
|
||||
const checkExistenceEndpoint = useEndpoint('GET', '/v1/omnichannel/contacts.checkExistence');
|
||||
const queryClient = useQueryClient();
|
||||
const handleOpenUpSellModal = () => setModal(<AdvancedContactModal onCancel={() => setModal(null)} />);
|
||||
|
||||
const { data: customFieldsMetadata = [], isLoading: isLoadingCustomFields } = useCustomFieldsMetadata({
|
||||
scope: 'visitor',
|
||||
enabled: canViewCustomFields,
|
||||
});
|
||||
|
||||
const initialValue = getInitialValues(contactData);
|
||||
|
||||
const {
|
||||
formState: { errors, isSubmitting, isDirty },
|
||||
control,
|
||||
watch,
|
||||
handleSubmit,
|
||||
} = useForm<ContactFormData>({
|
||||
reValidateMode: 'onBlur',
|
||||
defaultValues: initialValue,
|
||||
});
|
||||
|
||||
const {
|
||||
fields: emailFields,
|
||||
append: appendEmail,
|
||||
remove: removeEmail,
|
||||
} = useFieldArray({
|
||||
control,
|
||||
name: 'emails',
|
||||
});
|
||||
|
||||
const {
|
||||
fields: phoneFields,
|
||||
append: appendPhone,
|
||||
remove: removePhone,
|
||||
} = useFieldArray({
|
||||
control,
|
||||
name: 'phones',
|
||||
});
|
||||
|
||||
const { emails, phones } = watch();
|
||||
|
||||
const validateEmailFormat = async (emailValue: string) => {
|
||||
if (!emails) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const currentEmails = emails.map(({ address }) => address);
|
||||
|
||||
if (!validateEmail(emailValue)) {
|
||||
return t('error-invalid-email-address');
|
||||
}
|
||||
|
||||
if (currentEmails.filter((email) => email === emailValue).length > 1) {
|
||||
return t('Email_already_exists');
|
||||
}
|
||||
|
||||
const initialEmails = initialValue.emails.map(({ address }) => address);
|
||||
|
||||
if (!initialEmails.includes(emailValue) && (await checkExistenceEndpoint({ email: emailValue })).exists) {
|
||||
return t('Email_already_exists');
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const validatePhone = async (phoneValue: string) => {
|
||||
if (!phones) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const currentPhones = phones.map(({ phoneNumber }) => phoneNumber);
|
||||
|
||||
if (currentPhones.filter((phone) => phone === phoneValue).length > 1) {
|
||||
return t('Phone_already_exists');
|
||||
}
|
||||
|
||||
const initialPhones = initialValue.phones.map(({ phoneNumber }) => phoneNumber);
|
||||
|
||||
if (!initialPhones.includes(phoneValue) && (await checkExistenceEndpoint({ phone: phoneValue })).exists) {
|
||||
return t('Phone_already_exists');
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const validateName = (v: string): string | boolean => (!v.trim() ? t('Required_field', { field: t('Name') }) : true);
|
||||
|
||||
const handleSave = useFormSubmitWithDirtyCheck(
|
||||
async (data: ContactFormData): Promise<void> => {
|
||||
const { name, phones, emails, customFields, contactManager } = data;
|
||||
|
||||
const payload = {
|
||||
name,
|
||||
phones: phones.map(({ phoneNumber }) => phoneNumber),
|
||||
emails: emails.map(({ address }) => address),
|
||||
customFields,
|
||||
contactManager,
|
||||
};
|
||||
|
||||
if (contactData) {
|
||||
await editContact.mutateAsync({ contactId: contactData?._id, ...payload });
|
||||
await queryClient.invalidateQueries({ queryKey: omnichannelQueryKeys.contacts() });
|
||||
return;
|
||||
}
|
||||
|
||||
await createContact.mutateAsync(payload);
|
||||
await queryClient.invalidateQueries({ queryKey: omnichannelQueryKeys.contacts() });
|
||||
},
|
||||
{
|
||||
isDirty,
|
||||
},
|
||||
);
|
||||
|
||||
const formId = useId();
|
||||
|
||||
if (isLoadingCustomFields) {
|
||||
return <ContextualbarSkeleton onClose={onClose} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<ContextualbarDialog onClose={onClose}>
|
||||
<ContextualbarHeader>
|
||||
<ContextualbarIcon name={contactData ? 'pencil' : 'user'} />
|
||||
<ContextualbarTitle>{contactData ? t('Edit_Contact_Profile') : t('New_contact')}</ContextualbarTitle>
|
||||
<ContextualbarClose onClick={onClose} />
|
||||
</ContextualbarHeader>
|
||||
<ContextualbarScrollableContent id={formId} is='form' onSubmit={handleSubmit(handleSave)}>
|
||||
<Field>
|
||||
<FieldLabel required>{t('Name')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
rules={{ validate: validateName }}
|
||||
render={({ field }) => <TextInput {...field} error={errors.name?.message} />}
|
||||
/>
|
||||
</FieldRow>
|
||||
{errors.name && <FieldError>{errors.name.message}</FieldError>}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t('Email')}</FieldLabel>
|
||||
{emailFields.map((field, index) => (
|
||||
<Fragment key={field.id}>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name={`emails.${index}.address`}
|
||||
control={control}
|
||||
rules={{
|
||||
required: t('Required_field', { field: t('Email') }),
|
||||
validate: validateEmailFormat,
|
||||
}}
|
||||
render={({ field }) => <TextInput {...field} error={errors.emails?.[index]?.address?.message} aria-required='true' />}
|
||||
/>
|
||||
<IconButton title={t('Remove_email')} small onClick={() => removeEmail(index)} marginInlineStart={8} icon='trash' />
|
||||
</FieldRow>
|
||||
{errors.emails?.[index]?.address && <FieldError>{errors.emails?.[index]?.address?.message}</FieldError>}
|
||||
</Fragment>
|
||||
))}
|
||||
<Button
|
||||
marginBlockStart={8}
|
||||
onClick={validateMultipleFields(emailFields.length, hasLicense) ? handleOpenUpSellModal : () => appendEmail({ address: '' })}
|
||||
>
|
||||
{t('Add_email')}
|
||||
</Button>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t('Phone')}</FieldLabel>
|
||||
{phoneFields.map((field, index) => (
|
||||
<Fragment key={field.id}>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name={`phones.${index}.phoneNumber`}
|
||||
control={control}
|
||||
rules={{
|
||||
required: t('Required_field', { field: t('Phone') }),
|
||||
validate: validatePhone,
|
||||
}}
|
||||
render={({ field }) => <TextInput {...field} error={errors.phones?.[index]?.phoneNumber?.message} aria-required='true' />}
|
||||
/>
|
||||
<IconButton title={t('Remove_phone')} small onClick={() => removePhone(index)} marginInlineStart={8} icon='trash' />
|
||||
</FieldRow>
|
||||
{errors.phones?.[index]?.phoneNumber && <FieldError>{errors.phones?.[index]?.phoneNumber?.message}</FieldError>}
|
||||
</Fragment>
|
||||
))}
|
||||
<Button
|
||||
marginBlockStart={8}
|
||||
onClick={
|
||||
validateMultipleFields(phoneFields.length, hasLicense) ? handleOpenUpSellModal : () => appendPhone({ phoneNumber: '' })
|
||||
}
|
||||
>
|
||||
{t('Add_phone')}
|
||||
</Button>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t('Contact_Manager')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='contactManager'
|
||||
control={control}
|
||||
render={({ field: { value, onChange } }) => <ContactManagerInput value={value} onChange={onChange} />}
|
||||
/>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
<Divider />
|
||||
{canViewCustomFields && <CustomFieldsForm formName='customFields' formControl={control} metadata={customFieldsMetadata} />}
|
||||
</ContextualbarScrollableContent>
|
||||
<ContextualbarFooter>
|
||||
<ButtonGroup stretch>
|
||||
<Button onClick={onCancel}>{t('Cancel')}</Button>
|
||||
<Button type='submit' form={formId} loading={isSubmitting} primary>
|
||||
{t('Save')}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</ContextualbarFooter>
|
||||
</ContextualbarDialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditContactInfo;
|
||||
@@ -0,0 +1,32 @@
|
||||
import { ContextualbarSkeleton } from '@rocket.chat/ui-client';
|
||||
import { useEndpoint } from '@rocket.chat/ui-contexts';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import ContactInfoError from './ContactInfoError';
|
||||
import EditContactInfo from './EditContactInfo';
|
||||
|
||||
export type EditContactInfoWithDataProps = {
|
||||
id: string;
|
||||
onClose: () => void;
|
||||
onCancel: () => void;
|
||||
};
|
||||
|
||||
const EditContactInfoWithData = ({ id, onClose, onCancel }: EditContactInfoWithDataProps) => {
|
||||
const getContactEndpoint = useEndpoint('GET', '/v1/omnichannel/contacts.get');
|
||||
const { data, isPending, isError } = useQuery({
|
||||
queryKey: ['getContactById', id],
|
||||
queryFn: async () => getContactEndpoint({ contactId: id }),
|
||||
});
|
||||
|
||||
if (isPending) {
|
||||
return <ContextualbarSkeleton onClose={onClose} />;
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return <ContactInfoError onClose={onClose} />;
|
||||
}
|
||||
|
||||
return <EditContactInfo contactData={data.contact} onClose={onClose} onCancel={onCancel} />;
|
||||
};
|
||||
|
||||
export default EditContactInfoWithData;
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useEndpoint, useToastMessageDispatch } from '@rocket.chat/ui-contexts';
|
||||
import type { QueryKey } from '@tanstack/react-query';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useContactRoute } from '../../hooks/useContactRoute';
|
||||
|
||||
export const useCreateContact = (invalidateQueries: QueryKey) => {
|
||||
const { t } = useTranslation();
|
||||
const createContact = useEndpoint('POST', '/v1/omnichannel/contacts');
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
const queryClient = useQueryClient();
|
||||
const handleNavigate = useContactRoute();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: createContact,
|
||||
onSuccess: async ({ contactId }) => {
|
||||
handleNavigate({ context: 'details', id: contactId });
|
||||
dispatchToastMessage({ type: 'success', message: t('Contact_has_been_created') });
|
||||
await queryClient.invalidateQueries({ queryKey: invalidateQueries });
|
||||
},
|
||||
onError: (error) => {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useEndpoint, useToastMessageDispatch } from '@rocket.chat/ui-contexts';
|
||||
import type { QueryKey } from '@tanstack/react-query';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useContactRoute } from '../../hooks/useContactRoute';
|
||||
|
||||
export const useEditContact = (invalidateQueries?: QueryKey) => {
|
||||
const { t } = useTranslation();
|
||||
const updateContact = useEndpoint('POST', '/v1/omnichannel/contacts.update');
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
const queryClient = useQueryClient();
|
||||
const handleNavigate = useContactRoute();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: updateContact,
|
||||
onSuccess: async ({ contact }) => {
|
||||
handleNavigate({ context: 'details', id: contact?._id });
|
||||
dispatchToastMessage({ type: 'success', message: t('Contact_has_been_updated') });
|
||||
await queryClient.invalidateQueries({ queryKey: invalidateQueries });
|
||||
},
|
||||
onError: (error) => {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useEndpoint, useToastMessageDispatch } from '@rocket.chat/ui-contexts';
|
||||
import type { QueryKey } from '@tanstack/react-query';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useContactRoute } from '../../hooks/useContactRoute';
|
||||
|
||||
export const useReviewContact = (invalidateQueries?: QueryKey) => {
|
||||
const { t } = useTranslation();
|
||||
const updateContact = useEndpoint('POST', '/v1/omnichannel/contacts.conflicts');
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
const queryClient = useQueryClient();
|
||||
const handleNavigate = useContactRoute();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: updateContact,
|
||||
onSuccess: async ({ contact }) => {
|
||||
handleNavigate({ context: 'details', id: contact?._id });
|
||||
dispatchToastMessage({ type: 'success', message: t('Contact_has_been_updated') });
|
||||
await queryClient.invalidateQueries({ queryKey: invalidateQueries });
|
||||
},
|
||||
onError: (error) => {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { ILivechatCustomField } from '@rocket.chat/core-typings';
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
|
||||
import { useValidCustomFields } from './useValidCustomFields';
|
||||
|
||||
const makeField = (partial: Pick<ILivechatCustomField, '_id' | 'scope'> & Partial<ILivechatCustomField>): ILivechatCustomField => ({
|
||||
_updatedAt: new Date(),
|
||||
label: 'Field',
|
||||
visibility: 'visible',
|
||||
...partial,
|
||||
});
|
||||
|
||||
const buildWrapper = ({ withPermission, customFields }: { withPermission: boolean; customFields: ILivechatCustomField[] }) => {
|
||||
const builder = mockAppRoot().withEndpoint(
|
||||
'GET',
|
||||
'/v1/livechat/custom-fields',
|
||||
() =>
|
||||
({
|
||||
customFields,
|
||||
total: customFields.length,
|
||||
offset: 0,
|
||||
count: customFields.length,
|
||||
}) as any,
|
||||
);
|
||||
|
||||
if (withPermission) {
|
||||
builder.withPermission('view-livechat-room-customfields');
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
};
|
||||
|
||||
describe('useValidCustomFields', () => {
|
||||
const visitorField = makeField({ _id: 'cf_visitor', scope: 'visitor' });
|
||||
const roomField = makeField({ _id: 'cf_room', scope: 'room' });
|
||||
|
||||
describe('scope', () => {
|
||||
const userCustomFields = {
|
||||
cf_visitor: 'visitor value',
|
||||
cf_room: 'room value',
|
||||
};
|
||||
|
||||
it('keeps only visitor-scoped custom fields when scope is visitor', async () => {
|
||||
const { result } = renderHook(() => useValidCustomFields(userCustomFields, 'visitor'), {
|
||||
wrapper: buildWrapper({ withPermission: true, customFields: [visitorField, roomField] }),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current).toEqual([['cf_visitor', 'visitor value']]));
|
||||
});
|
||||
|
||||
it('keeps only room-scoped custom fields when scope is room', async () => {
|
||||
const { result } = renderHook(() => useValidCustomFields(userCustomFields, 'room'), {
|
||||
wrapper: buildWrapper({ withPermission: true, customFields: [visitorField, roomField] }),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current).toEqual([['cf_room', 'room value']]));
|
||||
});
|
||||
|
||||
it('omits a key when the field is defined for the other scope', async () => {
|
||||
const { result } = renderHook(() => useValidCustomFields({ cf_room: 'room only' }, 'visitor'), {
|
||||
wrapper: buildWrapper({ withPermission: true, customFields: [roomField] }),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current).toEqual([]));
|
||||
});
|
||||
});
|
||||
|
||||
describe('other filters (baseline)', () => {
|
||||
it('returns an empty list without view permission even when scope matches', async () => {
|
||||
const { result } = renderHook(() => useValidCustomFields({ cf_visitor: 'x' }, 'visitor'), {
|
||||
wrapper: buildWrapper({ withPermission: false, customFields: [visitorField] }),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current).toEqual([]));
|
||||
});
|
||||
|
||||
it('excludes fields that are not set as visible', async () => {
|
||||
const hiddenField = makeField({ _id: 'cf_hidden', scope: 'visitor', visibility: 'hidden' });
|
||||
const { result } = renderHook(() => useValidCustomFields({ cf_hidden: 'secret', cf_visitor: 'ok' }, 'visitor'), {
|
||||
wrapper: buildWrapper({ withPermission: true, customFields: [hiddenField, visitorField] }),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current).toEqual([['cf_visitor', 'ok']]));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { ILivechatCustomField } from '@rocket.chat/core-typings';
|
||||
import { usePermission } from '@rocket.chat/ui-contexts';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { useCustomFieldsQuery } from '../../hooks/useCustomFieldsQuery';
|
||||
|
||||
const checkIsVisibleAndCorrectScope = (key: string, customFields: ILivechatCustomField[], scope: 'visitor' | 'room') => {
|
||||
const field = customFields?.find(({ _id }) => _id === key);
|
||||
return field?.visibility === 'visible' && field?.scope === scope;
|
||||
};
|
||||
|
||||
export const useValidCustomFields = (userCustomFields: Record<string, string | unknown> | undefined, scope: 'visitor' | 'room') => {
|
||||
const { data, isError } = useCustomFieldsQuery();
|
||||
const canViewCustomFields = usePermission('view-livechat-room-customfields');
|
||||
|
||||
const customFieldEntries = useMemo(() => {
|
||||
if (!canViewCustomFields || !userCustomFields || !data?.customFields || isError) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Object.entries(userCustomFields).filter(
|
||||
([key, value]) => checkIsVisibleAndCorrectScope(key, data?.customFields, scope) && value,
|
||||
);
|
||||
}, [canViewCustomFields, userCustomFields, data?.customFields, isError, scope]);
|
||||
|
||||
return customFieldEntries;
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Box } from '@rocket.chat/fuselage';
|
||||
import { GenericModal } from '@rocket.chat/ui-client';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export type BlockChannelModalProps = {
|
||||
onCancel: () => void;
|
||||
onConfirm: () => void;
|
||||
};
|
||||
|
||||
const BlockChannelModal = ({ onCancel, onConfirm }: BlockChannelModalProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<GenericModal variant='danger' icon='ban' title={t('Block_channel')} confirmText={t('Block')} onConfirm={onConfirm} onCancel={onCancel}>
|
||||
<Box>{t('Block_channel_description')}</Box>
|
||||
</GenericModal>
|
||||
);
|
||||
};
|
||||
|
||||
export default BlockChannelModal;
|
||||
@@ -0,0 +1,83 @@
|
||||
import type { ILivechatContact } from '@rocket.chat/core-typings';
|
||||
import { Box, States, StatesIcon, StatesTitle, Throbber } from '@rocket.chat/fuselage';
|
||||
import { VirtualizedScrollbars, ContextualbarContent, ContextualbarEmptyContent } from '@rocket.chat/ui-client';
|
||||
import { useEndpoint } from '@rocket.chat/ui-contexts';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Virtuoso } from 'react-virtuoso';
|
||||
|
||||
import ContactInfoChannelsItem from './ContactInfoChannelsItem';
|
||||
import useOutboundProvidersList from '../../../components/outboundMessage/hooks/useOutboundProvidersList';
|
||||
|
||||
export type ContactInfoChannelsProps = {
|
||||
contact: Pick<ILivechatContact, '_id' | 'unknown'>;
|
||||
};
|
||||
|
||||
const ContactInfoChannels = ({ contact }: ContactInfoChannelsProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const getContactChannels = useEndpoint('GET', '/v1/omnichannel/contacts.channels');
|
||||
const { data, isError, isPending } = useQuery({
|
||||
queryKey: ['getContactChannels', contact._id],
|
||||
queryFn: () => getContactChannels({ contactId: contact._id }),
|
||||
});
|
||||
|
||||
const { data: providers = [] } = useOutboundProvidersList({
|
||||
select: (data) => data.providers.map((provider) => provider.providerId),
|
||||
});
|
||||
|
||||
if (isPending) {
|
||||
return (
|
||||
<ContextualbarContent>
|
||||
<Box paddingBlock={12}>
|
||||
<Throbber size='x12' />
|
||||
</Box>
|
||||
</ContextualbarContent>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<ContextualbarContent paddingInline={0}>
|
||||
<States>
|
||||
<StatesIcon name='warning' variation='danger' />
|
||||
<StatesTitle>{t('Something_went_wrong')}</StatesTitle>
|
||||
</States>
|
||||
</ContextualbarContent>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ContextualbarContent paddingInline={0}>
|
||||
{data.channels?.length === 0 && (
|
||||
<ContextualbarEmptyContent icon='balloon' title={t('No_channels_yet')} subtitle={t('No_channels_yet_description')} />
|
||||
)}
|
||||
{data.channels && data.channels.length > 0 && (
|
||||
<>
|
||||
<Box is='span' fontScale='p2' paddingBlockStart={24} paddingInlineStart={24} marginBlockEnd={8}>
|
||||
{t('Last_contacts')}
|
||||
</Box>
|
||||
<Box role='list' flexGrow={1} flexShrink={1} overflow='hidden' display='flex'>
|
||||
<VirtualizedScrollbars>
|
||||
<Virtuoso
|
||||
totalCount={data.channels.length}
|
||||
overscan={25}
|
||||
data={data?.channels}
|
||||
itemContent={(index, data) => (
|
||||
<ContactInfoChannelsItem
|
||||
key={index}
|
||||
{...data}
|
||||
contact={contact}
|
||||
canSendOutboundMessage={data.details.id ? providers.includes(data.details.id) : false}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</VirtualizedScrollbars>
|
||||
</Box>
|
||||
</>
|
||||
)}
|
||||
</ContextualbarContent>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactInfoChannels;
|
||||
@@ -0,0 +1,118 @@
|
||||
import type { ILivechatContact, ILivechatContactChannel, Serialized } from '@rocket.chat/core-typings';
|
||||
import { css } from '@rocket.chat/css-in-js';
|
||||
import { Box, Palette } from '@rocket.chat/fuselage';
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { GenericMenu } from '@rocket.chat/ui-client';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useBlockChannel } from './useBlockChannel';
|
||||
import { OmnichannelRoomIcon } from '../../../../../components/RoomIcon/OmnichannelRoomIcon';
|
||||
import { useTimeFromNow } from '../../../../../hooks/useTimeFromNow';
|
||||
import { useOutboundMessageModal } from '../../../components/outboundMessage/modals/OutboundMessageModal';
|
||||
import { useVisitorInfo } from '../../../directory/hooks/useVisitorInfo';
|
||||
import { useOmnichannelSource } from '../../../hooks/useOmnichannelSource';
|
||||
|
||||
export type ContactInfoChannelsItemProps = Serialized<ILivechatContactChannel> & {
|
||||
contact?: Pick<ILivechatContact, '_id' | 'unknown'>;
|
||||
canSendOutboundMessage?: boolean;
|
||||
};
|
||||
|
||||
const ContactInfoChannelsItem = ({
|
||||
contact,
|
||||
visitor,
|
||||
details,
|
||||
blocked,
|
||||
lastChat,
|
||||
canSendOutboundMessage,
|
||||
}: ContactInfoChannelsItemProps) => {
|
||||
const { t } = useTranslation();
|
||||
const { getSourceLabel, getSourceName } = useOmnichannelSource();
|
||||
const getTimeFromNow = useTimeFromNow(true);
|
||||
|
||||
const { data: visitorData } = useVisitorInfo(visitor.visitorId);
|
||||
|
||||
const channelLabel = useMemo(() => {
|
||||
const phone = getSourceLabel(details);
|
||||
const externalId = details?.id ? visitorData?.externalIds?.find((e) => e.appId === details.id) : undefined;
|
||||
const username = externalId?.metadata?.username;
|
||||
|
||||
if (typeof username === 'string' && phone) {
|
||||
return `${username} - ${phone}`;
|
||||
}
|
||||
return typeof username === 'string' ? username : phone;
|
||||
}, [visitorData?.externalIds, details, getSourceLabel]);
|
||||
|
||||
const [showButton, setShowButton] = useState(false);
|
||||
const handleBlockContact = useBlockChannel({ association: visitor, blocked });
|
||||
const outboundMessageModal = useOutboundMessageModal();
|
||||
|
||||
const customClass = css`
|
||||
&:hover,
|
||||
&:focus {
|
||||
background: ${Palette.surface['surface-hover']};
|
||||
}
|
||||
`;
|
||||
|
||||
const menuItems = useMemo(() => {
|
||||
const items: GenericMenuItemProps[] = [
|
||||
{
|
||||
id: 'block',
|
||||
icon: 'ban',
|
||||
content: blocked ? t('Unblock') : t('Block'),
|
||||
variant: 'danger',
|
||||
onClick: handleBlockContact,
|
||||
},
|
||||
];
|
||||
|
||||
if (canSendOutboundMessage) {
|
||||
items.unshift({
|
||||
id: 'outbound-message',
|
||||
icon: 'send',
|
||||
disabled: contact?.unknown,
|
||||
tooltip: contact?.unknown ? t('error-unknown-contact') : undefined,
|
||||
content: t('Outbound_message'),
|
||||
onClick: () => outboundMessageModal.open({ contactId: contact?._id, providerId: details.id }),
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}, [blocked, canSendOutboundMessage, contact?._id, contact?.unknown, details.id, handleBlockContact, outboundMessageModal, t]);
|
||||
|
||||
return (
|
||||
<Box
|
||||
tabIndex={0}
|
||||
borderBlockEndWidth={1}
|
||||
borderBlockEndColor='stroke-extra-light'
|
||||
borderBlockEndStyle='solid'
|
||||
className={['rcx-box--animated', customClass]}
|
||||
paddingInline={24}
|
||||
paddingBlock={12}
|
||||
display='flex'
|
||||
flexDirection='column'
|
||||
onFocus={() => setShowButton(true)}
|
||||
onPointerEnter={() => setShowButton(true)}
|
||||
onPointerLeave={() => setShowButton(false)}
|
||||
>
|
||||
<Box display='flex' alignItems='center'>
|
||||
{details && <OmnichannelRoomIcon source={details} size='x18' placement='default' />}
|
||||
{details && (
|
||||
<Box marginInline={4} fontScale='p2b'>
|
||||
{getSourceName(details)} {blocked && `(${t('Blocked')})`}
|
||||
</Box>
|
||||
)}
|
||||
{lastChat && (
|
||||
<Box marginInlineStart={4} fontScale='c1'>
|
||||
{getTimeFromNow(lastChat.ts)}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
<Box minHeight='x24' alignItems='center' marginBlockStart={4} display='flex' justifyContent='space-between'>
|
||||
<Box>{channelLabel}</Box>
|
||||
{showButton && <GenericMenu detached title={t('Options')} sections={[{ items: menuItems }]} tiny />}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactInfoChannelsItem;
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from './ContactInfoChannels';
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { ILivechatContactVisitorAssociation } from '@rocket.chat/core-typings';
|
||||
import { useEndpoint, useSetModal, useToastMessageDispatch } from '@rocket.chat/ui-contexts';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import BlockChannelModal from './BlockChannelModal';
|
||||
import { useHasLicenseModule } from '../../../../../hooks/useHasLicenseModule';
|
||||
import AdvancedContactModal from '../../AdvancedContactModal';
|
||||
|
||||
export const useBlockChannel = ({ blocked, association }: { blocked: boolean; association: ILivechatContactVisitorAssociation }) => {
|
||||
const { t } = useTranslation();
|
||||
const setModal = useSetModal();
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
const { data: hasLicense = false } = useHasLicenseModule('contact-id-verification');
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const blockContact = useEndpoint('POST', '/v1/omnichannel/contacts.block');
|
||||
const unblockContact = useEndpoint('POST', '/v1/omnichannel/contacts.unblock');
|
||||
|
||||
const handleUnblock = useCallback(async () => {
|
||||
try {
|
||||
await unblockContact({ visitor: association });
|
||||
dispatchToastMessage({ type: 'success', message: t('Contact_unblocked') });
|
||||
queryClient.invalidateQueries({ queryKey: ['getContactById'] });
|
||||
} catch (error) {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
}
|
||||
}, [association, dispatchToastMessage, queryClient, t, unblockContact]);
|
||||
|
||||
const handleBlock = useCallback(() => {
|
||||
if (!hasLicense) {
|
||||
return setModal(<AdvancedContactModal onCancel={() => setModal(null)} />);
|
||||
}
|
||||
|
||||
const blockAction = async () => {
|
||||
try {
|
||||
await blockContact({ visitor: association });
|
||||
dispatchToastMessage({ type: 'success', message: t('Contact_blocked') });
|
||||
queryClient.invalidateQueries({ queryKey: ['getContactById'] });
|
||||
} catch (error) {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
} finally {
|
||||
setModal(null);
|
||||
}
|
||||
};
|
||||
|
||||
setModal(<BlockChannelModal onCancel={() => setModal(null)} onConfirm={blockAction} />);
|
||||
}, [association, blockContact, dispatchToastMessage, hasLicense, queryClient, setModal, t]);
|
||||
|
||||
return blocked ? handleUnblock : handleBlock;
|
||||
};
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { ILivechatContact } from '@rocket.chat/core-typings';
|
||||
import { Divider, Margins } from '@rocket.chat/fuselage';
|
||||
import { ContextualbarScrollableContent } from '@rocket.chat/ui-client';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import ContactInfoDetailsEntry from './ContactInfoDetailsEntry';
|
||||
import ContactInfoPhoneEntry from './ContactInfoPhoneEntry';
|
||||
import ContactManagerInfo from './ContactManagerInfo';
|
||||
import { useFormatDate } from '../../../../../hooks/useFormatDate';
|
||||
import CustomField from '../../../components/CustomField';
|
||||
import Field from '../../../components/Field';
|
||||
import Info from '../../../components/Info';
|
||||
import Label from '../../../components/Label';
|
||||
|
||||
export type ContactInfoDetailsProps = {
|
||||
contact: Pick<ILivechatContact, '_id' | 'unknown'>;
|
||||
emails?: string[];
|
||||
phones?: string[];
|
||||
createdAt: string;
|
||||
customFieldEntries: [string, string | unknown][];
|
||||
contactManager?: string;
|
||||
};
|
||||
|
||||
const ContactInfoDetails = ({ contact, emails, phones, createdAt, customFieldEntries, contactManager }: ContactInfoDetailsProps) => {
|
||||
const { t } = useTranslation();
|
||||
const formatDate = useFormatDate();
|
||||
|
||||
return (
|
||||
<ContextualbarScrollableContent>
|
||||
{emails?.length ? (
|
||||
<Field>
|
||||
<Label id={`${contact._id}-emails`}>{t('Email')}</Label>
|
||||
<ul aria-labelledby={`${contact._id}-emails`}>
|
||||
{emails.map((email) => (
|
||||
<ContactInfoDetailsEntry key={email} is='li' icon='mail' value={email} />
|
||||
))}
|
||||
</ul>
|
||||
</Field>
|
||||
) : null}
|
||||
|
||||
{phones?.length ? (
|
||||
<Field>
|
||||
<Label id={`${contact._id}-phones`}>{t('Phone')}</Label>
|
||||
<ul aria-labelledby={`${contact._id}-phones`}>
|
||||
{phones.map((phone) => (
|
||||
<ContactInfoPhoneEntry key={phone} is='li' contact={contact} value={phone} />
|
||||
))}
|
||||
</ul>
|
||||
</Field>
|
||||
) : null}
|
||||
|
||||
{contactManager ? <ContactManagerInfo userId={contactManager} /> : null}
|
||||
|
||||
<Margins block={4}>
|
||||
{createdAt && (
|
||||
<Field>
|
||||
<Label id={`${contact._id}-created-at`}>{t('Created_at')}</Label>
|
||||
<Info aria-labelledby={`${contact._id}-created-at`}>{formatDate(createdAt)}</Info>
|
||||
</Field>
|
||||
)}
|
||||
|
||||
{customFieldEntries.length > 0 && (
|
||||
<>
|
||||
<Divider marginInline={-24} />
|
||||
{customFieldEntries?.map(([key, value]) => (
|
||||
<CustomField key={key} id={key} value={value as string} />
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</Margins>
|
||||
</ContextualbarScrollableContent>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactInfoDetails;
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { IconProps } from '@rocket.chat/fuselage';
|
||||
import { Box, ButtonGroup, Icon } from '@rocket.chat/fuselage';
|
||||
import type { ComponentProps, ReactNode } from 'react';
|
||||
|
||||
export type ContactInfoDetailsEntryProps = Pick<ComponentProps<typeof Box>, 'is' | 'aria-labelledby'> & {
|
||||
icon: IconProps['name'];
|
||||
value: string;
|
||||
actions?: ReactNode;
|
||||
};
|
||||
|
||||
const ContactInfoDetailsEntry = ({ icon, value, actions, ...props }: ContactInfoDetailsEntryProps) => (
|
||||
<Box display='flex' alignItems='center' {...props}>
|
||||
<Icon size='x18' marginInlineEnd={4} name={icon} />
|
||||
<Box withTruncatedText display='flex' flexGrow={1} alignItems='center' justifyContent='space-between'>
|
||||
<Box is='p' fontScale='p2' withTruncatedText marginInline={4}>
|
||||
{value}
|
||||
</Box>
|
||||
<Box display='flex' alignItems='center'>
|
||||
<ButtonGroup>{actions}</ButtonGroup>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
|
||||
export default ContactInfoDetailsEntry;
|
||||
@@ -0,0 +1,34 @@
|
||||
import { IconButton } from '@rocket.chat/fuselage';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useOutboundMessageAccess } from '../../../components/outboundMessage/hooks';
|
||||
import type { OutboundMessageModalProps } from '../../../components/outboundMessage/modals/OutboundMessageModal';
|
||||
import { useOutboundMessageModal } from '../../../components/outboundMessage/modals/OutboundMessageModal';
|
||||
|
||||
export type ContactInfoOutboundMessageButtonProps = {
|
||||
title?: string;
|
||||
disabled?: boolean;
|
||||
defaultValues?: OutboundMessageModalProps['defaultValues'];
|
||||
};
|
||||
|
||||
const ContactInfoOutboundMessageButton = ({ defaultValues, disabled, title }: ContactInfoOutboundMessageButtonProps) => {
|
||||
const { t } = useTranslation();
|
||||
const outboundMessageModal = useOutboundMessageModal();
|
||||
const canSendOutboundMessage = useOutboundMessageAccess();
|
||||
|
||||
if (!canSendOutboundMessage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<IconButton
|
||||
disabled={disabled}
|
||||
onClick={() => outboundMessageModal.open(defaultValues)}
|
||||
tiny
|
||||
icon='send'
|
||||
title={`${t('Outbound_message')} ${title ? `(${title})` : ''}`}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactInfoOutboundMessageButton;
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { ILivechatContact } from '@rocket.chat/core-typings';
|
||||
import { IconButton } from '@rocket.chat/fuselage';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import ContactInfoDetailsEntry from './ContactInfoDetailsEntry';
|
||||
import ContactInfoOutboundMessageButton from './ContactInfoOutboundMessageButton';
|
||||
import useClipboardWithToast from '../../../../../hooks/useClipboardWithToast';
|
||||
import { parseOutboundPhoneNumber } from '../../../../../lib/voip/parseOutboundPhoneNumber';
|
||||
|
||||
export type ContactInfoPhoneEntryProps = Omit<ComponentProps<typeof ContactInfoDetailsEntry>, 'icon' | 'actions'> & {
|
||||
contact?: Pick<ILivechatContact, '_id' | 'unknown'>;
|
||||
};
|
||||
|
||||
const ContactInfoPhoneEntry = ({ contact, value, ...props }: ContactInfoPhoneEntryProps) => {
|
||||
const { t } = useTranslation();
|
||||
const { copy } = useClipboardWithToast(value);
|
||||
|
||||
return (
|
||||
<ContactInfoDetailsEntry
|
||||
{...props}
|
||||
icon='phone'
|
||||
value={parseOutboundPhoneNumber(value)}
|
||||
actions={[
|
||||
<IconButton key={`${value}-copy`} onClick={() => copy()} tiny icon='copy' title={t('Copy')} />,
|
||||
null,
|
||||
<ContactInfoOutboundMessageButton
|
||||
key={`${value}-outbound-message`}
|
||||
title={contact?.unknown ? t('error-unknown-contact') : undefined}
|
||||
disabled={contact?.unknown}
|
||||
defaultValues={{ contactId: contact?._id, recipient: value }}
|
||||
/>,
|
||||
]}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactInfoPhoneEntry;
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Box, Skeleton } from '@rocket.chat/fuselage';
|
||||
import { UserAvatar } from '@rocket.chat/ui-avatar';
|
||||
import { useEndpoint } from '@rocket.chat/ui-contexts';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { UserStatus } from '../../../../../components/UserStatus';
|
||||
|
||||
export type ContactManagerInfoProps = { userId: string };
|
||||
|
||||
const ContactManagerInfo = ({ userId }: ContactManagerInfoProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const getContactManagerByUsername = useEndpoint('GET', '/v1/users.info');
|
||||
const { data, isLoading, isSuccess, isError } = useQuery({
|
||||
queryKey: ['getContactManagerByUserId', userId],
|
||||
queryFn: async () => getContactManagerByUsername({ userId }),
|
||||
});
|
||||
|
||||
if (isError) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Box marginBlockEnd={4}>{t('Contact_Manager')}</Box>
|
||||
{isLoading && <Skeleton />}
|
||||
{isSuccess && (
|
||||
<Box display='flex' alignItems='center'>
|
||||
{data.user.username && <UserAvatar size='x18' username={data.user.username} />}
|
||||
<Box marginInline={8}>
|
||||
<UserStatus status={data.user.status} />
|
||||
</Box>
|
||||
<Box fontScale='p2'>{data.user.name}</Box>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactManagerInfo;
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from './ContactInfoDetails';
|
||||
@@ -0,0 +1,130 @@
|
||||
import type { ILivechatContact, Serialized } from '@rocket.chat/core-typings';
|
||||
import { OmnichannelSourceType } from '@rocket.chat/core-typings';
|
||||
import { Box, Margins, Throbber, States, StatesIcon, StatesTitle, Select } from '@rocket.chat/fuselage';
|
||||
import { useLocalStorage } from '@rocket.chat/fuselage-hooks';
|
||||
import { VirtualizedScrollbars, ContextualbarContent, ContextualbarEmptyContent } from '@rocket.chat/ui-client';
|
||||
import { useEndpoint, useSetModal } from '@rocket.chat/ui-contexts';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import type { Key } from 'react';
|
||||
import { useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Virtuoso } from 'react-virtuoso';
|
||||
|
||||
import ContactInfoHistoryItem from './ContactInfoHistoryItem';
|
||||
import { useHasLicenseModule } from '../../../../../hooks/useHasLicenseModule';
|
||||
import { useOmnichannelSource } from '../../../hooks/useOmnichannelSource';
|
||||
import AdvancedContactModal from '../../AdvancedContactModal';
|
||||
|
||||
export type ContactInfoHistoryProps = {
|
||||
contact: Serialized<ILivechatContact>;
|
||||
setChatId: (chatId: string) => void;
|
||||
};
|
||||
|
||||
const isFilterBlocked = (hasLicense: boolean, fieldValue: Key) => !hasLicense && fieldValue !== 'all';
|
||||
|
||||
const ContactInfoHistory = ({ contact, setChatId }: ContactInfoHistoryProps) => {
|
||||
const { t } = useTranslation();
|
||||
const setModal = useSetModal();
|
||||
const [storedType, setStoredType] = useLocalStorage<string>('contact-history-type', 'all');
|
||||
|
||||
const { data: hasLicense = false } = useHasLicenseModule('contact-id-verification');
|
||||
const type = isFilterBlocked(hasLicense, storedType) ? 'all' : storedType;
|
||||
|
||||
const { getSourceName } = useOmnichannelSource();
|
||||
|
||||
const getContactHistory = useEndpoint('GET', '/v1/omnichannel/contacts.history');
|
||||
const { data, isLoading, isError } = useQuery({
|
||||
queryKey: ['getContactHistory', contact._id, type],
|
||||
queryFn: () => getContactHistory({ contactId: contact._id, source: type === 'all' ? undefined : type }),
|
||||
});
|
||||
|
||||
const handleChangeFilter = (value: Key) => {
|
||||
if (isFilterBlocked(hasLicense, value)) {
|
||||
return setModal(<AdvancedContactModal onCancel={() => setModal(null)} />);
|
||||
}
|
||||
|
||||
setStoredType(value as string);
|
||||
};
|
||||
|
||||
const historyFilterOptions: [string, string][] = useMemo(
|
||||
() =>
|
||||
Object.values(OmnichannelSourceType).reduce(
|
||||
(acc, cv) => {
|
||||
let sourceName;
|
||||
const hasSourceType = contact.channels?.find((item) => {
|
||||
sourceName = getSourceName(item.details, false);
|
||||
return item.details.type === cv;
|
||||
});
|
||||
|
||||
if (hasSourceType && sourceName) {
|
||||
acc.push([cv, sourceName]);
|
||||
}
|
||||
|
||||
return acc;
|
||||
},
|
||||
[['all', t('All')]],
|
||||
),
|
||||
[contact.channels, getSourceName, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<ContextualbarContent paddingInline={0}>
|
||||
<Box
|
||||
display='flex'
|
||||
flexDirection='row'
|
||||
padding={24}
|
||||
borderBlockEndWidth='default'
|
||||
borderBlockEndStyle='solid'
|
||||
borderBlockEndColor='extra-light'
|
||||
flexShrink={0}
|
||||
>
|
||||
<Box display='flex' flexDirection='row' flexGrow={1} marginInline='neg-x4'>
|
||||
<Margins inline={4}>
|
||||
<Select
|
||||
value={type}
|
||||
onChange={handleChangeFilter}
|
||||
placeholder={t('Filter')}
|
||||
options={historyFilterOptions}
|
||||
disabled={type === 'all' && data?.history.length === 0}
|
||||
/>
|
||||
</Margins>
|
||||
</Box>
|
||||
</Box>
|
||||
{isLoading && (
|
||||
<Box paddingInline={24} paddingBlock={12}>
|
||||
<Throbber size='x12' />
|
||||
</Box>
|
||||
)}
|
||||
{isError && (
|
||||
<States>
|
||||
<StatesIcon name='warning' variation='danger' />
|
||||
<StatesTitle>{t('Something_went_wrong')}</StatesTitle>
|
||||
</States>
|
||||
)}
|
||||
{data?.history.length === 0 && (
|
||||
<ContextualbarEmptyContent icon='history' title={t('No_history_yet')} subtitle={t('No_history_yet_description')} />
|
||||
)}
|
||||
{!isError && data?.history && data.history.length > 0 && (
|
||||
<>
|
||||
<Box paddingInline={24} paddingBlock={12}>
|
||||
<Box is='span' color='hint' fontScale='p2'>
|
||||
{t('Showing_current_of_total', { current: data?.history.length, total: data?.total })}
|
||||
</Box>
|
||||
</Box>
|
||||
<Box role='list' height='100%' overflow='hidden' flexShrink={1}>
|
||||
<VirtualizedScrollbars>
|
||||
<Virtuoso
|
||||
totalCount={data.history.length}
|
||||
overscan={25}
|
||||
data={data?.history}
|
||||
itemContent={(index, data) => <ContactInfoHistoryItem key={index} onClick={() => setChatId(data._id)} {...data} />}
|
||||
/>
|
||||
</VirtualizedScrollbars>
|
||||
</Box>
|
||||
</>
|
||||
)}
|
||||
</ContextualbarContent>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactInfoHistory;
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { Serialized } from '@rocket.chat/core-typings';
|
||||
import { css } from '@rocket.chat/css-in-js';
|
||||
import {
|
||||
Box,
|
||||
Palette,
|
||||
IconButton,
|
||||
Icon,
|
||||
MessageGenericPreview,
|
||||
MessageGenericPreviewContent,
|
||||
MessageGenericPreviewDescription,
|
||||
MessageGenericPreviewTitle,
|
||||
} from '@rocket.chat/fuselage';
|
||||
import type { ContactSearchChatsResult } from '@rocket.chat/rest-typings';
|
||||
import { useSetModal } from '@rocket.chat/ui-contexts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { OmnichannelRoomIcon } from '../../../../../components/RoomIcon/OmnichannelRoomIcon';
|
||||
import { useHasLicenseModule } from '../../../../../hooks/useHasLicenseModule';
|
||||
import { usePreventPropagation } from '../../../../../hooks/usePreventPropagation';
|
||||
import { useTimeFromNow } from '../../../../../hooks/useTimeFromNow';
|
||||
import { useOmnichannelSource } from '../../../hooks/useOmnichannelSource';
|
||||
import AdvancedContactModal from '../../AdvancedContactModal';
|
||||
|
||||
export type ContactInfoHistoryItemProps = Serialized<ContactSearchChatsResult> & {
|
||||
onClick: () => void;
|
||||
};
|
||||
|
||||
const ContactInfoHistoryItem = ({ source, lastMessage, verified, onClick }: ContactInfoHistoryItemProps) => {
|
||||
const { t } = useTranslation();
|
||||
const getTimeFromNow = useTimeFromNow(true);
|
||||
const setModal = useSetModal();
|
||||
const preventPropagation = usePreventPropagation();
|
||||
const { data: hasLicense = false } = useHasLicenseModule('contact-id-verification');
|
||||
const { getSourceName } = useOmnichannelSource();
|
||||
|
||||
const customClass = css`
|
||||
&:hover {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&:focus {
|
||||
background: ${Palette.surface['surface-hover']};
|
||||
}
|
||||
`;
|
||||
|
||||
return (
|
||||
<Box
|
||||
tabIndex={0}
|
||||
role='listitem'
|
||||
aria-label={getSourceName(source)}
|
||||
borderBlockEndWidth={1}
|
||||
borderBlockEndColor='stroke-extra-light'
|
||||
borderBlockEndStyle='solid'
|
||||
className={['rcx-box--animated', customClass]}
|
||||
paddingInline={24}
|
||||
paddingBlock={12}
|
||||
display='flex'
|
||||
flexDirection='column'
|
||||
onClick={onClick}
|
||||
>
|
||||
<Box display='flex' justifyContent='space-between'>
|
||||
<Box display='flex' alignItems='center'>
|
||||
{source && <OmnichannelRoomIcon source={source} size='x18' placement='default' />}
|
||||
{source && (
|
||||
<Box marginInline={4} fontScale='p2b'>
|
||||
{getSourceName(source)}
|
||||
</Box>
|
||||
)}
|
||||
{lastMessage && (
|
||||
<Box marginInlineStart={4} fontScale='c1'>
|
||||
{getTimeFromNow(lastMessage.ts)}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
<Box marginInlineStart={4} is='span' onClick={preventPropagation}>
|
||||
{hasLicense && verified ? (
|
||||
<Icon title={t('Verified')} marginInlineStart={4} size='x16' name='success-circle' color='stroke-highlight' />
|
||||
) : (
|
||||
<IconButton
|
||||
title={t('Unverified')}
|
||||
onClick={() => setModal(<AdvancedContactModal onCancel={() => setModal(null)} />)}
|
||||
icon='question-mark'
|
||||
tiny
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
{lastMessage?.msg.trim() && (
|
||||
<Box width='full' marginBlockStart={8}>
|
||||
<MessageGenericPreview>
|
||||
<MessageGenericPreviewContent>
|
||||
<MessageGenericPreviewTitle>{t('Closing_chat_message')}:</MessageGenericPreviewTitle>
|
||||
<MessageGenericPreviewDescription clamp>{lastMessage?.msg}</MessageGenericPreviewDescription>
|
||||
</MessageGenericPreviewContent>
|
||||
</MessageGenericPreview>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactInfoHistoryItem;
|
||||
@@ -0,0 +1,134 @@
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
ButtonGroup,
|
||||
Icon,
|
||||
IconButton,
|
||||
Margins,
|
||||
States,
|
||||
StatesIcon,
|
||||
StatesSubtitle,
|
||||
StatesTitle,
|
||||
TextInput,
|
||||
Throbber,
|
||||
} from '@rocket.chat/fuselage';
|
||||
import { useDebouncedValue, useResizeObserver } from '@rocket.chat/fuselage-hooks';
|
||||
import { VirtualizedScrollbars, ContextualbarContent, ContextualbarEmptyContent, ContextualbarFooter } from '@rocket.chat/ui-client';
|
||||
import { useSetting, useUserPreference } from '@rocket.chat/ui-contexts';
|
||||
import type { ChangeEvent } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Virtuoso } from 'react-virtuoso';
|
||||
|
||||
import { isMessageNewDay } from '../../../../room/MessageList/lib/isMessageNewDay';
|
||||
import { isMessageSequential } from '../../../../room/MessageList/lib/isMessageSequential';
|
||||
import ContactHistoryMessage from '../../../contactHistory/MessageList/ContactHistoryMessage';
|
||||
import { useHistoryMessageList } from '../../../contactHistory/MessageList/useHistoryMessageList';
|
||||
|
||||
type ContactHistoryMessagesListProps = {
|
||||
chatId: string;
|
||||
onBack: () => void;
|
||||
onOpenRoom?: () => void;
|
||||
};
|
||||
|
||||
const ContactInfoHistoryMessages = ({ chatId, onBack, onOpenRoom }: ContactHistoryMessagesListProps) => {
|
||||
const { t } = useTranslation();
|
||||
const [text, setText] = useState('');
|
||||
const showUserAvatar = !!useUserPreference<boolean>('displayAvatars');
|
||||
|
||||
const { ref, contentBoxSize: { inlineSize = 378, blockSize = 1 } = {} } = useResizeObserver<HTMLElement>({
|
||||
debounceDelay: 200,
|
||||
});
|
||||
|
||||
const query = useDebouncedValue(
|
||||
useMemo(() => ({ roomId: chatId, filter: text }), [chatId, text]),
|
||||
500,
|
||||
);
|
||||
|
||||
const { isPending, error, isSuccess, data, fetchNextPage } = useHistoryMessageList(query);
|
||||
|
||||
const messages = data?.items || [];
|
||||
const totalItemCount = data?.itemCount ?? 0;
|
||||
|
||||
const handleSearchChange = (event: ChangeEvent<HTMLInputElement>): void => {
|
||||
setText(event.currentTarget.value);
|
||||
};
|
||||
|
||||
const messageGroupingPeriod = Number(useSetting('Message_GroupingPeriod'));
|
||||
|
||||
return (
|
||||
<>
|
||||
<ContextualbarContent paddingInline={0}>
|
||||
<Box
|
||||
display='flex'
|
||||
flexDirection='row'
|
||||
padding={24}
|
||||
borderBlockEndWidth='default'
|
||||
borderBlockEndStyle='solid'
|
||||
borderBlockEndColor='extra-light'
|
||||
flexShrink={0}
|
||||
>
|
||||
<Box display='flex' alignItems='center' flexDirection='row' flexGrow={1} marginInline='neg-x4'>
|
||||
<Margins inline={4}>
|
||||
<TextInput
|
||||
placeholder={t('Search')}
|
||||
value={text}
|
||||
onChange={handleSearchChange}
|
||||
endAddon={<Icon name='magnifier' size='x20' />}
|
||||
/>
|
||||
<IconButton title={t('Back')} small icon='back' onClick={onBack} />
|
||||
</Margins>
|
||||
</Box>
|
||||
</Box>
|
||||
{isPending && (
|
||||
<Box paddingInline={24} paddingBlock={12}>
|
||||
<Throbber size='x12' />
|
||||
</Box>
|
||||
)}
|
||||
{error && (
|
||||
<States>
|
||||
<StatesIcon name='warning' variation='danger' />
|
||||
<StatesTitle>{t('Something_went_wrong')}</StatesTitle>
|
||||
<StatesSubtitle>{error.toString()}</StatesSubtitle>
|
||||
</States>
|
||||
)}
|
||||
{isSuccess && totalItemCount === 0 && <ContextualbarEmptyContent title={t('No_results_found')} />}
|
||||
<Box flexGrow={1} flexShrink={1} overflow='hidden' display='flex' ref={ref}>
|
||||
{!error && totalItemCount > 0 && messages.length > 0 && (
|
||||
<VirtualizedScrollbars>
|
||||
<Virtuoso
|
||||
totalCount={totalItemCount}
|
||||
initialTopMostItemIndex={{ index: 'LAST' }}
|
||||
followOutput
|
||||
style={{
|
||||
height: blockSize,
|
||||
width: inlineSize,
|
||||
}}
|
||||
endReached={() => fetchNextPage()}
|
||||
overscan={25}
|
||||
data={messages}
|
||||
itemContent={(index, data) => {
|
||||
const lastMessage = messages[index - 1];
|
||||
const isSequential = isMessageSequential(data, lastMessage, messageGroupingPeriod);
|
||||
const isNewDay = isMessageNewDay(data, lastMessage);
|
||||
return (
|
||||
<ContactHistoryMessage message={data} sequential={isSequential} isNewDay={isNewDay} showUserAvatar={showUserAvatar} />
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</VirtualizedScrollbars>
|
||||
)}
|
||||
</Box>
|
||||
</ContextualbarContent>
|
||||
{onOpenRoom && (
|
||||
<ContextualbarFooter>
|
||||
<ButtonGroup stretch>
|
||||
<Button onClick={onOpenRoom}>{t('Open_chat')}</Button>
|
||||
</ButtonGroup>
|
||||
</ContextualbarFooter>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactInfoHistoryMessages;
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { ILivechatContact, Serialized } from '@rocket.chat/core-typings';
|
||||
import { useRouter } from '@rocket.chat/ui-contexts';
|
||||
import { useState } from 'react';
|
||||
|
||||
import ContactInfoHistory from './ContactInfoHistory';
|
||||
import ContactInfoHistoryMessages from './ContactInfoHistoryMessages';
|
||||
|
||||
export type ContactInfoHistoryRouterProps = { contact: Serialized<ILivechatContact> };
|
||||
|
||||
const ContactInfoHistoryRouter = ({ contact }: ContactInfoHistoryRouterProps) => {
|
||||
const [chatId, setChatId] = useState<string | undefined>();
|
||||
const { navigate } = useRouter();
|
||||
|
||||
if (chatId) {
|
||||
return (
|
||||
<ContactInfoHistoryMessages chatId={chatId} onBack={() => setChatId(undefined)} onOpenRoom={() => navigate(`/live/${chatId}`)} />
|
||||
);
|
||||
}
|
||||
|
||||
return <ContactInfoHistory contact={contact} setChatId={setChatId} />;
|
||||
};
|
||||
|
||||
export default ContactInfoHistoryRouter;
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from './ContactInfoHistoryRouter';
|
||||
Reference in New Issue
Block a user