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

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,73 @@
import type { SelectOption } from '@rocket.chat/fuselage';
import { Field, FieldGroup, FieldLabel, FieldRow, NumberInput, Select, TextInput } from '@rocket.chat/fuselage';
import type { ComponentProps } from 'react';
import { useId, useMemo } from 'react';
import type { Control } from 'react-hook-form';
import { Controller, useWatch } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import type { TriggersPayload } from './EditTrigger';
type ConditionFormType = ComponentProps<typeof Field> & {
index: number;
control: Control<TriggersPayload>;
};
export const ConditionForm = ({ control, index, ...props }: ConditionFormType) => {
const conditionFieldId = useId();
const { t } = useTranslation();
const conditionName = useWatch({ control, name: `conditions.${index}.name` });
const placeholders: { [conditionName: string]: string } = useMemo(
() => ({
'page-url': t('Enter_a_regex'),
'time-on-site': t('Time_in_seconds'),
}),
[t],
);
const conditionOptions: SelectOption[] = useMemo(
() => [
['page-url', t('Visitor_page_URL')],
['time-on-site', t('Visitor_time_on_site')],
['chat-opened-by-visitor', t('Chat_opened_by_visitor')],
['after-guest-registration', t('After_guest_registration')],
],
[t],
);
const conditionValuePlaceholder = placeholders[conditionName];
return (
<FieldGroup {...props}>
<Field>
<FieldLabel htmlFor={conditionFieldId}>{t('Condition')}</FieldLabel>
<FieldRow>
<Controller
name={`conditions.${index}.name`}
control={control}
render={({ field }) => (
<Select {...field} id={conditionFieldId} options={conditionOptions} placeholder={t('Select_an_option')} />
)}
/>
</FieldRow>
{conditionValuePlaceholder && (
<FieldRow>
<Controller
name={`conditions.${index}.value`}
control={control}
render={({ field }) => {
if (conditionName === 'time-on-site') {
return <NumberInput {...field} placeholder={conditionValuePlaceholder} />;
}
return <TextInput {...field} placeholder={conditionValuePlaceholder} />;
}}
/>
</FieldRow>
)}
</Field>
</FieldGroup>
);
};

View File

@@ -0,0 +1,223 @@
import type { ILivechatTrigger, ILivechatTriggerAction, Serialized } from '@rocket.chat/core-typings';
import { FieldGroup, Button, ButtonGroup, Field, FieldLabel, FieldRow, FieldError, TextInput, ToggleSwitch } from '@rocket.chat/fuselage';
import {
ContextualbarScrollableContent,
ContextualbarTitle,
ContextualbarFooter,
ContextualbarHeader,
ContextualbarClose,
} from '@rocket.chat/ui-client';
import { useToastMessageDispatch, useEndpoint } from '@rocket.chat/ui-contexts';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useId } from 'react';
import { Controller, useFieldArray, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { ConditionForm } from './ConditionForm';
import { ActionForm } from './actions/ActionForm';
import { useFormSubmitWithDirtyCheck } from '../../../hooks/useFormSubmitWithDirtyCheck';
export type TriggersPayload = {
name: string;
description: string;
enabled: boolean;
runOnce: boolean;
conditions: ILivechatTrigger['conditions'];
actions: ILivechatTrigger['actions'];
};
const DEFAULT_SEND_MESSAGE_ACTION = {
name: 'send-message',
params: {
sender: 'queue',
name: '',
msg: '',
},
} as const;
const DEFAULT_PAGE_URL_CONDITION = { name: 'page-url', value: '' } as const;
export const getDefaultAction = (action: ILivechatTriggerAction): ILivechatTriggerAction => {
switch (action.name) {
case 'send-message':
return {
name: 'send-message',
params: {
name: action.params?.name || '',
msg: action.params?.msg || '',
sender: action.params?.sender || 'queue',
},
};
case 'use-external-service':
return {
name: 'use-external-service',
params: {
name: action.params?.name || '',
sender: action.params?.sender || 'queue',
serviceUrl: action.params?.serviceUrl || '',
serviceTimeout: action.params?.serviceTimeout || 0,
serviceFallbackMessage: action.params?.serviceFallbackMessage || '',
},
};
}
};
const getInitialValues = (triggerData: Serialized<ILivechatTrigger> | undefined): TriggersPayload => ({
name: triggerData?.name ?? '',
description: triggerData?.description || '',
enabled: triggerData?.enabled ?? true,
runOnce: !!triggerData?.runOnce || false,
conditions: triggerData?.conditions.map(({ name, value }) => ({ name: name || 'page-url', value: value || '' })) ?? [
DEFAULT_PAGE_URL_CONDITION,
],
actions: triggerData?.actions.map((action) => getDefaultAction(action)) ?? [DEFAULT_SEND_MESSAGE_ACTION],
});
const EditTrigger = ({ triggerData, onClose }: { triggerData?: Serialized<ILivechatTrigger>; onClose: () => void }) => {
const { t } = useTranslation();
const queryClient = useQueryClient();
const dispatchToastMessage = useToastMessageDispatch();
const saveTrigger = useEndpoint('POST', '/v1/livechat/triggers');
const initValues = getInitialValues(triggerData);
const formId = useId();
const enabledField = useId();
const runOnceField = useId();
const nameField = useId();
const descriptionField = useId();
const {
control,
handleSubmit,
trigger,
formState: { isSubmitting, errors, isDirty },
} = useForm<TriggersPayload>({ values: initValues });
const { fields: conditionsFields } = useFieldArray({
control,
name: 'conditions',
});
const { fields: actionsFields } = useFieldArray({
control,
name: 'actions',
});
const saveTriggerMutation = useMutation({
mutationFn: saveTrigger,
onSuccess: () => {
dispatchToastMessage({ type: 'success', message: t('Saved') });
queryClient.invalidateQueries({
queryKey: ['livechat-getTriggersById'],
});
queryClient.invalidateQueries({
queryKey: ['livechat-triggers'],
});
onClose();
},
onError: (error) => {
dispatchToastMessage({ type: 'error', message: error });
},
});
const handleSave = useFormSubmitWithDirtyCheck(
async (data: TriggersPayload) => {
await saveTriggerMutation.mutateAsync({
...data,
_id: triggerData?._id,
actions: data.actions.map(getDefaultAction),
});
},
{ isDirty },
);
return (
<>
<ContextualbarHeader>
<ContextualbarTitle>{triggerData?._id ? t('Edit_Trigger') : t('New_Trigger')}</ContextualbarTitle>
<ContextualbarClose onClick={onClose} />
</ContextualbarHeader>
<ContextualbarScrollableContent>
<form id={formId} onSubmit={handleSubmit(handleSave)}>
<FieldGroup>
<Field>
<FieldRow>
<FieldLabel htmlFor={enabledField}>{t('Enabled')}</FieldLabel>
<Controller
name='enabled'
control={control}
render={({ field: { value, ...field } }) => <ToggleSwitch id={enabledField} {...field} checked={value} />}
/>
</FieldRow>
</Field>
<Field>
<FieldRow>
<FieldLabel htmlFor={runOnceField}>{t('Run_only_once_for_each_visitor')}</FieldLabel>
<Controller
name='runOnce'
control={control}
render={({ field: { value, ...field } }) => <ToggleSwitch id={runOnceField} {...field} checked={value} />}
/>
</FieldRow>
</Field>
<Field>
<FieldLabel htmlFor={nameField} required>
{t('Name')}
</FieldLabel>
<FieldRow>
<Controller
name='name'
control={control}
rules={{ required: t('Required_field', { field: t('Name') }) }}
render={({ field }) => (
<TextInput
{...field}
id={nameField}
error={errors?.name?.message}
aria-required={true}
aria-invalid={Boolean(errors?.name)}
aria-describedby={`${nameField}-error`}
/>
)}
/>
</FieldRow>
{errors?.name && (
<FieldError aria-live='assertive' id={`${nameField}-error`}>
{errors?.name.message}
</FieldError>
)}
</Field>
<Field>
<FieldLabel htmlFor={descriptionField}>{t('Description')}</FieldLabel>
<FieldRow>
<Controller name='description' control={control} render={({ field }) => <TextInput id={descriptionField} {...field} />} />
</FieldRow>
</Field>
{conditionsFields.map((field, index) => (
<ConditionForm key={field.id} control={control} index={index} />
))}
{actionsFields.map((field, index) => (
<ActionForm key={field.id} control={control} trigger={trigger} index={index} />
))}
</FieldGroup>
</form>
</ContextualbarScrollableContent>
<ContextualbarFooter>
<ButtonGroup stretch>
<Button onClick={onClose}>{t('Cancel')}</Button>
<Button form={formId} type='submit' primary loading={isSubmitting}>
{t('Save')}
</Button>
</ButtonGroup>
</ContextualbarFooter>
</>
);
};
export default EditTrigger;

View File

@@ -0,0 +1,30 @@
import type { ILivechatTrigger } from '@rocket.chat/core-typings';
import { Callout } from '@rocket.chat/fuselage';
import { ContextualbarSkeletonBody } from '@rocket.chat/ui-client';
import { useEndpoint } from '@rocket.chat/ui-contexts';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import EditTrigger from './EditTrigger';
const EditTriggerWithData = ({ triggerId, onClose }: { triggerId: ILivechatTrigger['_id']; onClose: () => void }) => {
const { t } = useTranslation();
const getTriggersById = useEndpoint('GET', '/v1/livechat/triggers/:_id', { _id: triggerId });
const { data, isPending, isError } = useQuery({
queryKey: ['livechat-getTriggersById', triggerId],
queryFn: async () => getTriggersById(),
refetchOnWindowFocus: false,
});
if (isPending) {
return <ContextualbarSkeletonBody />;
}
if (isError) {
return <Callout>{t('Error')}</Callout>;
}
return <EditTrigger triggerData={data.trigger} onClose={onClose} />;
};
export default EditTriggerWithData;

View File

@@ -0,0 +1,17 @@
import { FieldGroup, Box } from '@rocket.chat/fuselage';
import type { StoryObj, Meta } from '@storybook/react';
import EditTrigger from './EditTrigger';
export default {
component: EditTrigger,
decorators: [
(fn) => (
<Box maxWidth='x600'>
<FieldGroup>{fn()}</FieldGroup>
</Box>
),
],
} satisfies Meta<typeof EditTrigger>;
export const Default: StoryObj<typeof EditTrigger> = {};

View File

@@ -0,0 +1,38 @@
import { Button } from '@rocket.chat/fuselage';
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import { ContextualbarDialog, Page, PageHeader, PageContent } from '@rocket.chat/ui-client';
import { useRouteParameter, useRouter } from '@rocket.chat/ui-contexts';
import { useTranslation } from 'react-i18next';
import EditTrigger from './EditTrigger';
import EditTriggerWithData from './EditTriggerWithData';
import TriggersTable from './TriggersTable';
const TriggersPage = () => {
const { t } = useTranslation();
const id = useRouteParameter('id');
const context = useRouteParameter('context');
const router = useRouter();
const handleClose = useStableCallback(() => router.navigate('/omnichannel/triggers'));
return (
<Page flexDirection='row'>
<Page>
<PageHeader title={t('Livechat_Triggers')}>
<Button onClick={() => router.navigate('/omnichannel/triggers/new')}>{t('Create_trigger')}</Button>
</PageHeader>
<PageContent>
<TriggersTable />
</PageContent>
</Page>
{context && (
<ContextualbarDialog onClose={handleClose}>
{context === 'edit' && id && <EditTriggerWithData triggerId={id} onClose={handleClose} />}
{context === 'new' && <EditTrigger onClose={handleClose} />}
</ContextualbarDialog>
)}
</Page>
);
};
export default TriggersPage;

View File

@@ -0,0 +1,16 @@
import { usePermission } from '@rocket.chat/ui-contexts';
import TriggersPage from './TriggersPage';
import NotAuthorizedPage from '../../notAuthorized/NotAuthorizedPage';
const TriggersRoute = () => {
const canViewTriggers = usePermission('view-livechat-triggers');
if (!canViewTriggers) {
return <NotAuthorizedPage />;
}
return <TriggersPage />;
};
export default TriggersRoute;

View File

@@ -0,0 +1,61 @@
import type { ILivechatTrigger } from '@rocket.chat/core-typings';
import { IconButton } from '@rocket.chat/fuselage';
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import { GenericModal, GenericTableCell, GenericTableRow } from '@rocket.chat/ui-client';
import { useSetModal, useToastMessageDispatch, useRoute, useTranslation, useEndpoint } from '@rocket.chat/ui-contexts';
import type { KeyboardEvent, MouseEvent } from 'react';
import { memo } from 'react';
export type TriggersRowProps = Pick<ILivechatTrigger, '_id' | 'name' | 'description' | 'enabled'> & { reload: () => void };
const TriggersRow = ({ _id, name, description, enabled, reload }: TriggersRowProps) => {
const t = useTranslation();
const setModal = useSetModal();
const triggersRoute = useRoute('omnichannel-triggers');
const deleteTrigger = useEndpoint('DELETE', '/v1/livechat/triggers/:_id', { _id });
const dispatchToastMessage = useToastMessageDispatch();
const handleClick = useStableCallback(() => {
triggersRoute.push({
context: 'edit',
id: _id,
});
});
const handleKeyDown = useStableCallback((e: KeyboardEvent) => {
if (!['Enter', 'Space'].includes(e.code)) {
return;
}
handleClick();
});
const handleDelete = useStableCallback((e: MouseEvent) => {
e.stopPropagation();
const onDeleteTrigger = async () => {
try {
await deleteTrigger();
dispatchToastMessage({ type: 'success', message: t('Trigger_removed') });
reload();
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
setModal();
};
setModal(<GenericModal variant='danger' onConfirm={onDeleteTrigger} onCancel={() => setModal()} confirmText={t('Delete')} />);
});
return (
<GenericTableRow key={_id} action tabIndex={0} onClick={handleClick} onKeyDown={handleKeyDown}>
<GenericTableCell withTruncatedText>{name}</GenericTableCell>
<GenericTableCell withTruncatedText>{description}</GenericTableCell>
<GenericTableCell withTruncatedText>{enabled ? t('Yes') : t('No')}</GenericTableCell>
<GenericTableCell withTruncatedText>
<IconButton icon='trash' small title={t('Remove')} onClick={handleDelete} />
</GenericTableCell>
</GenericTableRow>
);
};
export default memo(TriggersRow);

View File

@@ -0,0 +1,98 @@
import { Pagination } from '@rocket.chat/fuselage';
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import {
GenericTable,
GenericTableHeader,
GenericTableBody,
GenericTableHeaderCell,
GenericTableLoadingRow,
usePagination,
} from '@rocket.chat/ui-client';
import { useTranslation, useEndpoint, useRouter } from '@rocket.chat/ui-contexts';
import { useQuery, hashKey } from '@tanstack/react-query';
import { useMemo, useState } from 'react';
import TriggersRow from './TriggersRow';
import GenericError from '../../../components/GenericError';
import GenericNoResults from '../../../components/GenericNoResults';
import { links } from '../../../lib/links';
const TriggersTable = () => {
const t = useTranslation();
const router = useRouter();
const handleAddNew = useStableCallback(() => {
router.navigate('/omnichannel/triggers/new');
});
const { current, itemsPerPage, setItemsPerPage, setCurrent, ...paginationProps } = usePagination();
const query = useMemo(() => ({ offset: current, count: itemsPerPage }), [current, itemsPerPage]);
const getTriggers = useEndpoint('GET', '/v1/livechat/triggers');
const { data, refetch, isSuccess, isLoading, isError } = useQuery({
queryKey: ['livechat-triggers', query],
queryFn: async () => getTriggers(query),
});
const [defaultQuery] = useState(hashKey([query]));
const queryHasChanged = defaultQuery !== hashKey([query]);
const headers = (
<>
<GenericTableHeaderCell>{t('Name')}</GenericTableHeaderCell>
<GenericTableHeaderCell>{t('Description')}</GenericTableHeaderCell>
<GenericTableHeaderCell>{t('Enabled')}</GenericTableHeaderCell>
<GenericTableHeaderCell width='x60' />
</>
);
return (
<>
{isLoading && (
<GenericTable>
<GenericTableHeader>{headers}</GenericTableHeader>
<GenericTableBody>
<GenericTableLoadingRow cols={4} />
</GenericTableBody>
</GenericTable>
)}
{isSuccess && data.triggers.length === 0 && queryHasChanged && <GenericNoResults />}
{isSuccess && data.triggers.length === 0 && !queryHasChanged && (
<GenericNoResults
icon='smart'
title={t('No_triggers_yet')}
description={t('No_triggers_yet_description')}
buttonAction={handleAddNew}
buttonTitle={t('Create_trigger')}
linkHref={links.go.omnichannelDocs}
linkText={t('Learn_more_about_triggers')}
/>
)}
{isSuccess && data.triggers.length > 0 && (
<>
<GenericTable aria-label={t('Livechat_Triggers')}>
<GenericTableHeader>{headers}</GenericTableHeader>
<GenericTableBody>
{data.triggers.map(({ _id, name, description, enabled }) => (
<TriggersRow key={_id} _id={_id} name={name} description={description} enabled={enabled} reload={refetch} />
))}
</GenericTableBody>
</GenericTable>
<Pagination
divider
current={current}
itemsPerPage={itemsPerPage}
count={data?.total || 0}
onSetItemsPerPage={setItemsPerPage}
onSetCurrent={setCurrent}
{...paginationProps}
/>
</>
)}
{isError && <GenericError buttonAction={refetch} />}
</>
);
};
export default TriggersTable;

View File

@@ -0,0 +1,98 @@
import { Box, Button, Field, FieldError, FieldHint, FieldLabel, FieldRow, Icon, TextInput } from '@rocket.chat/fuselage';
import { useSafely } from '@rocket.chat/fuselage-hooks';
import type { TranslationKey } from '@rocket.chat/ui-contexts';
import { useEndpoint } from '@rocket.chat/ui-contexts';
import { useMutation } from '@tanstack/react-query';
import type { ComponentProps } from 'react';
import { useId, useState } from 'react';
import type { Control, UseFormTrigger } from 'react-hook-form';
import { Controller, useWatch } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import type { TriggersPayload } from '../EditTrigger';
import { useFieldError } from '../hooks';
type ActionExternaServicelUrlType = ComponentProps<typeof Field> & {
index: number;
control: Control<TriggersPayload>;
trigger: UseFormTrigger<TriggersPayload>;
disabled?: boolean;
};
export const ActionExternalServiceUrl = ({ control, trigger, index, disabled, ...props }: ActionExternaServicelUrlType) => {
const { t } = useTranslation();
const serviceUrlFieldId = useId();
const serviceUrlFieldName = `actions.${index}.params.serviceUrl` as const;
const serviceTimeoutFieldName = `actions.${index}.params.serviceTimeout` as const;
const serviceTimeoutValue = useWatch({ control, name: serviceTimeoutFieldName });
const [serviceUrlError] = useFieldError({ control, name: serviceUrlFieldName });
const [isSuccessMessageVisible, setSuccessMessageVisible] = useSafely(useState(false));
const webhookTestEndpoint = useEndpoint('POST', '/v1/livechat/triggers/external-service/test');
const showSuccessMesssage = () => {
setSuccessMessageVisible(true);
setTimeout(() => setSuccessMessageVisible(false), 3000);
};
const webhookTest = useMutation({
mutationFn: webhookTestEndpoint,
onSuccess: showSuccessMesssage,
});
const testExternalService = async (serviceUrl: string) => {
if (!serviceUrl) {
return true;
}
try {
await webhookTest.mutateAsync({
webhookUrl: serviceUrl,
timeout: serviceTimeoutValue || 10000,
fallbackMessage: '',
extraData: [],
});
return true;
} catch (e) {
return t((e as { error: TranslationKey }).error);
}
};
return (
<Field {...props}>
<FieldLabel required htmlFor={serviceUrlFieldId}>
{t('External_service_url')}
</FieldLabel>
<FieldRow>
<Controller
name={serviceUrlFieldName}
control={control}
defaultValue=''
rules={{
required: t('Required_field', { field: t('External_service_url') }),
validate: testExternalService,
deps: serviceTimeoutFieldName,
}}
render={({ field }) => {
return <TextInput {...field} disabled={webhookTest.isPending || disabled} error={serviceUrlError?.message} />;
}}
/>
</FieldRow>
{serviceUrlError && <FieldError>{serviceUrlError.message}</FieldError>}
<FieldHint>{t('External_service_test_hint')}</FieldHint>
<Button loading={webhookTest.isPending} disabled={disabled || isSuccessMessageVisible} onClick={() => trigger(serviceUrlFieldName)}>
{isSuccessMessageVisible ? (
<Box is='span' color='status-font-on-success'>
<Icon name='success-circle' size='x20' verticalAlign='middle' /> {t('Success')}!
</Box>
) : (
t('Send_Test')
)}
</Button>
</Field>
);
};

View File

@@ -0,0 +1,112 @@
import {
Box,
Field,
FieldGroup,
FieldHint,
FieldLabel,
FieldRow,
Option,
SelectLegacy,
Tag,
type SelectOption,
} from '@rocket.chat/fuselage';
import type { TranslationKey } from '@rocket.chat/ui-contexts';
import type { ComponentProps } from 'react';
import { useCallback, useId, useMemo } from 'react';
import type { Control, UseFormTrigger } from 'react-hook-form';
import { Controller, useWatch } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useHasLicenseModule } from '../../../../hooks/useHasLicenseModule';
import type { TriggersPayload } from '../EditTrigger';
import { getActionFormFields } from '../utils';
type SendMessageFormType = ComponentProps<typeof Field> & {
control: Control<TriggersPayload>;
trigger: UseFormTrigger<TriggersPayload>;
index: number;
};
const ACTION_HINTS: Record<string, TranslationKey> = {
'use-external-service': 'External_service_action_hint',
} as const;
const PREMIUM_ACTIONS = ['use-external-service'];
export const ActionForm = ({ control, trigger, index, ...props }: SendMessageFormType) => {
const { t } = useTranslation();
const actionFieldId = useId();
const actionFieldName = `actions.${index}.name` as const;
const actionFieldValue = useWatch({ control, name: actionFieldName });
const { data: hasLicense = false } = useHasLicenseModule('livechat-enterprise');
const actionOptions = useMemo<SelectOption[]>(() => {
return [
['send-message', t('Send_a_message')],
['use-external-service', t('Send_a_message_external_service')],
];
}, [t]);
const ActionFormFields = getActionFormFields(actionFieldValue);
const actionHint = useMemo(() => ACTION_HINTS[actionFieldValue] || '', [actionFieldValue]);
const isOptionDisabled = useCallback((value: string) => !hasLicense && PREMIUM_ACTIONS.includes(value), [hasLicense]);
const renderOption = useCallback(
(label: TranslationKey, value: string) => {
return (
<>
{isOptionDisabled(value) ? (
<Box justifyContent='space-between' flexDirection='row' display='flex' width='100%'>
{t(label)}
<Tag variant='featured'>{t('Premium')}</Tag>
</Box>
) : (
t(label)
)}
</>
);
},
[isOptionDisabled, t],
);
return (
<FieldGroup {...props}>
<Field>
<FieldLabel htmlFor={actionFieldId}>{t('Action')}</FieldLabel>
<FieldRow>
<Controller
name={actionFieldName}
control={control}
render={({ field: { onChange, value, name, ref } }) => {
return (
// TODO: Remove SelectLegacy once we have a new Select component
<SelectLegacy
ref={ref}
name={name}
onChange={onChange}
value={value}
id={actionFieldId}
options={actionOptions}
renderSelected={({ label, value }) => <Box flexGrow='1'>{renderOption(label, value)}</Box>}
renderItem={({ label, value, onMouseDown, ...props }) => (
<Option
{...props}
onMouseDown={isOptionDisabled(value) ? (e) => e.preventDefault() : onMouseDown}
disabled={isOptionDisabled(value)}
label={renderOption(label, value)}
/>
)}
/>
);
}}
/>
</FieldRow>
{actionHint && <FieldHint>{t(actionHint)}</FieldHint>}
</Field>
<ActionFormFields control={control} trigger={trigger} index={index} />
</FieldGroup>
);
};

View File

@@ -0,0 +1,59 @@
import { FieldRow, Select, TextInput, type SelectOption, Field, FieldLabel } from '@rocket.chat/fuselage';
import type { ComponentProps } from 'react';
import { useId, useMemo } from 'react';
import type { Control } from 'react-hook-form';
import { Controller, useWatch } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import type { TriggersPayload } from '../EditTrigger';
type ActionSenderType = ComponentProps<typeof Field> & {
control: Control<TriggersPayload>;
index: number;
disabled?: boolean;
};
export const ActionSender = ({ control, index, disabled, ...props }: ActionSenderType) => {
const { t } = useTranslation();
const senderFieldId = useId();
const senderFieldName = `actions.${index}.params.sender` as const;
const senderNameFieldName = `actions.${index}.params.name` as const;
const senderNameFieldValue = useWatch({ control, name: senderFieldName });
const senderOptions: SelectOption[] = useMemo(
() => [
['queue', t('Impersonate_next_agent_from_queue')],
['custom', t('Custom_agent')],
],
[t],
);
return (
<Field {...props}>
<FieldLabel htmlFor={senderFieldId}>{t('Sender')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name={senderFieldName}
defaultValue='queue'
render={({ field }) => {
return <Select {...field} id={senderFieldId} options={senderOptions} placeholder={t('Select_an_option')} disabled={disabled} />;
}}
/>
</FieldRow>
{senderNameFieldValue === 'custom' && (
<FieldRow>
<Controller
control={control}
name={senderNameFieldName}
render={({ field }) => {
return <TextInput {...field} placeholder={t('Name_of_agent')} aria-label={t('Name_of_agent')} disabled={disabled} />;
}}
/>
</FieldRow>
)}
</Field>
);
};

View File

@@ -0,0 +1,108 @@
import { FieldError, Field, FieldHint, FieldLabel, FieldRow, NumberInput, TextAreaInput, FieldGroup } from '@rocket.chat/fuselage';
import { useId, type ComponentProps, type FocusEvent } from 'react';
import type { Control, UseFormTrigger } from 'react-hook-form';
import { Controller } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useHasLicenseModule } from '../../../../hooks/useHasLicenseModule';
import type { TriggersPayload } from '../EditTrigger';
import { useFieldError } from '../hooks';
import { ActionExternalServiceUrl } from './ActionExternalServiceUrl';
import { ActionSender } from './ActionSender';
type SendMessageActionFormType = ComponentProps<typeof Field> & {
index: number;
control: Control<TriggersPayload>;
trigger: UseFormTrigger<TriggersPayload>;
};
export const ExternalServiceActionForm = ({ control, trigger, index, ...props }: SendMessageActionFormType) => {
const { t } = useTranslation();
const { data: hasLicense = false } = useHasLicenseModule('livechat-enterprise');
const timeoutFieldId = useId();
const timeoutFieldName = `actions.${index}.params.serviceTimeout` as const;
const fallbackMessageFieldId = useId();
const fallbackMessageFieldName = `actions.${index}.params.serviceFallbackMessage` as const;
const [timeoutError, fallbackMessageError] = useFieldError({ control, name: [timeoutFieldName, fallbackMessageFieldName] });
return (
<FieldGroup {...props}>
<ActionSender disabled={!hasLicense} control={control} index={index} />
<ActionExternalServiceUrl disabled={!hasLicense} control={control} trigger={trigger} index={index} />
<Field>
<FieldLabel required htmlFor={timeoutFieldId}>
{t('Timeout_in_miliseconds')}
</FieldLabel>
<FieldRow>
<Controller
control={control}
name={timeoutFieldName}
defaultValue={10000}
rules={{
required: t('Required_field', { field: t('Timeout_in_miliseconds') }),
min: { value: 0, message: t('Timeout_in_miliseconds_cant_be_negative_number') },
}}
render={({ field }) => {
return (
<NumberInput
{...field}
error={timeoutError?.message}
aria-invalid={Boolean(timeoutError)}
aria-describedby={`${timeoutFieldId}-hint`}
aria-required={true}
onFocus={(v: FocusEvent<HTMLInputElement>) => v.currentTarget.select()}
disabled={!hasLicense}
/>
);
}}
/>
</FieldRow>
{timeoutError && (
<FieldError aria-live='assertive' id={`${timeoutFieldId}-error`}>
{timeoutError.message}
</FieldError>
)}
<FieldHint id={`${timeoutFieldId}-hint`}>{t('Timeout_in_miliseconds_hint')}</FieldHint>
</Field>
<Field>
<FieldLabel htmlFor={fallbackMessageFieldId}>{t('Fallback_message')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name={fallbackMessageFieldName}
defaultValue=''
render={({ field }) => (
<TextAreaInput
{...field}
id={fallbackMessageFieldId}
rows={3}
placeholder={t('Fallback_message')}
error={fallbackMessageError?.message}
aria-invalid={Boolean(fallbackMessageError)}
aria-describedby={`${fallbackMessageFieldId}-hint`}
aria-required={true}
disabled={!hasLicense}
/>
)}
/>
</FieldRow>
{fallbackMessageError && (
<FieldError aria-live='assertive' id={`${fallbackMessageFieldId}-error`}>
{fallbackMessageError.message}
</FieldError>
)}
<FieldHint id={`${fallbackMessageFieldId}-hint`}>{t('Service_fallback_message_hint')}</FieldHint>
</Field>
</FieldGroup>
);
};

View File

@@ -0,0 +1,58 @@
import { Field, FieldError, FieldLabel, FieldRow, TextAreaInput } from '@rocket.chat/fuselage';
import { useId, type ComponentProps } from 'react';
import type { Control } from 'react-hook-form';
import { Controller } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import type { TriggersPayload } from '../EditTrigger';
import { useFieldError } from '../hooks';
import { ActionSender } from './ActionSender';
type SendMessageActionFormType = ComponentProps<typeof Field> & {
index: number;
control: Control<TriggersPayload>;
};
export const SendMessageActionForm = ({ control, index, ...props }: SendMessageActionFormType) => {
const { t } = useTranslation();
const messageFieldId = useId();
const name = `actions.${index}.params.msg` as const;
const [messageError] = useFieldError({ control, name });
return (
<>
<ActionSender {...props} control={control} index={index} />
<Field {...props}>
<FieldLabel required htmlFor={messageFieldId}>
{t('Message')}
</FieldLabel>
<FieldRow>
<Controller
control={control}
name={name}
defaultValue=''
rules={{ required: t('Required_field', { field: t('Message') }) }}
render={({ field }) => (
<TextAreaInput
error={messageError?.message}
aria-invalid={Boolean(messageError)}
aria-describedby={`${messageFieldId}-error`}
aria-required={true}
{...field}
rows={3}
placeholder={`${t('Message')}*`}
/>
)}
/>
</FieldRow>
{messageError && (
<FieldError aria-live='assertive' id={`${messageFieldId}-error`}>
{messageError.message}
</FieldError>
)}
</Field>
</>
);
};

View File

@@ -0,0 +1 @@
export * from './useFieldError';

View File

@@ -0,0 +1,13 @@
import type { Control, FieldError, FieldPath, FieldValues } from 'react-hook-form';
import { get, useFormState } from 'react-hook-form';
type UseFieldErrorProps<TFieldValues extends FieldValues> = {
control: Control<TFieldValues>;
name: FieldPath<TFieldValues> | FieldPath<TFieldValues>[];
};
export const useFieldError = <TFieldValues extends FieldValues>({ control, name }: UseFieldErrorProps<TFieldValues>) => {
const names = Array.isArray(name) ? name : [name];
const { errors } = useFormState<TFieldValues>({ control, name });
return names.map<FieldError | undefined>((name) => get(errors, name));
};

View File

@@ -0,0 +1,13 @@
import { ExternalServiceActionForm } from '../actions/ExternalServiceActionForm';
import { SendMessageActionForm } from '../actions/SendMessageActionForm';
type TriggerActions = 'send-message' | 'use-external-service';
const actionForms = {
'send-message': SendMessageActionForm,
'use-external-service': ExternalServiceActionForm,
} as const;
export const getActionFormFields = (actionName: TriggerActions) => {
return actionForms[actionName] || actionForms['send-message'];
};

View File

@@ -0,0 +1 @@
export * from './getActionFormFields';