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,16 @@
|
||||
import { useRouteParameter } from '@rocket.chat/ui-contexts';
|
||||
|
||||
import EditIncomingWebhook from './incoming/EditIncomingWebhook';
|
||||
import EditOutgoingWebhook from './outgoing/EditOutgoingWebhook';
|
||||
|
||||
const EditIntegrationsPage = () => {
|
||||
const type = useRouteParameter('type');
|
||||
|
||||
if (type === 'outgoing') {
|
||||
return <EditOutgoingWebhook />;
|
||||
}
|
||||
|
||||
return <EditIncomingWebhook />;
|
||||
};
|
||||
|
||||
export default EditIntegrationsPage;
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { IIncomingIntegration } from '@rocket.chat/core-typings';
|
||||
import { Box, Skeleton } from '@rocket.chat/fuselage';
|
||||
import { useEndpoint } from '@rocket.chat/ui-contexts';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import EditIncomingWebhook from './incoming/EditIncomingWebhook';
|
||||
import EditOutgoingWebhook from './outgoing/EditOutgoingWebhook';
|
||||
|
||||
export type EditIntegrationsPageWithDataProps = { integrationId: IIncomingIntegration['_id'] };
|
||||
|
||||
const EditIntegrationsPageWithData = ({ integrationId }: EditIntegrationsPageWithDataProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const params = useMemo(() => ({ integrationId }), [integrationId]);
|
||||
const getIntegrations = useEndpoint('GET', '/v1/integrations.get');
|
||||
const { data, isPending, isError } = useQuery({
|
||||
queryKey: ['integrations', params],
|
||||
queryFn: async () => getIntegrations(params),
|
||||
});
|
||||
|
||||
if (isPending) {
|
||||
return (
|
||||
<Box width='full' padding={24}>
|
||||
<Skeleton marginBlockEnd={4} />
|
||||
<Skeleton marginBlockEnd={8} />
|
||||
<Skeleton marginBlockEnd={4} />
|
||||
<Skeleton marginBlockEnd={8} />
|
||||
<Skeleton marginBlockEnd={4} />
|
||||
<Skeleton marginBlockEnd={8} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return <Box marginBlockStart={16}>{t('Oops_page_not_found')}</Box>;
|
||||
}
|
||||
|
||||
if (data?.integration.type === 'webhook-outgoing') {
|
||||
return <EditOutgoingWebhook webhookData={data?.integration} />;
|
||||
}
|
||||
|
||||
return <EditIncomingWebhook webhookData={data?.integration} />;
|
||||
};
|
||||
|
||||
export default EditIntegrationsPageWithData;
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { IIntegration, Serialized } from '@rocket.chat/core-typings';
|
||||
import { Box } from '@rocket.chat/fuselage';
|
||||
import { GenericTableCell, GenericTableRow } from '@rocket.chat/ui-client';
|
||||
|
||||
import { useFormatDateAndTime } from '../../../hooks/useFormatDateAndTime';
|
||||
|
||||
export type IntegrationRowProps = {
|
||||
integration: Serialized<IIntegration>;
|
||||
isMobile: boolean;
|
||||
onClick: (_id: string, type: string) => () => void;
|
||||
};
|
||||
|
||||
const IntegrationRow = ({ integration, onClick, isMobile }: IntegrationRowProps) => {
|
||||
const formatDateAndTime = useFormatDateAndTime();
|
||||
const { _id, name, type, username, _createdAt, _createdBy, channel } = integration;
|
||||
|
||||
return (
|
||||
<GenericTableRow key={_id} onKeyDown={onClick(_id, type)} onClick={onClick(_id, type)} tabIndex={0} role='link' action>
|
||||
<GenericTableCell>
|
||||
<Box withTruncatedText>{name}</Box>
|
||||
</GenericTableCell>
|
||||
<GenericTableCell>
|
||||
<Box withTruncatedText>{channel.join(', ')}</Box>
|
||||
</GenericTableCell>
|
||||
<GenericTableCell>
|
||||
<Box withTruncatedText>{_createdBy?.username}</Box>
|
||||
</GenericTableCell>
|
||||
{!isMobile && (
|
||||
<GenericTableCell>
|
||||
<Box withTruncatedText>{formatDateAndTime(_createdAt)}</Box>
|
||||
</GenericTableCell>
|
||||
)}
|
||||
<GenericTableCell>
|
||||
<Box withTruncatedText>{username}</Box>
|
||||
</GenericTableCell>
|
||||
</GenericTableRow>
|
||||
);
|
||||
};
|
||||
|
||||
export default IntegrationRow;
|
||||
@@ -0,0 +1,55 @@
|
||||
import { Button, ButtonGroup, Tabs, TabsItem } from '@rocket.chat/fuselage';
|
||||
import { Page, PageHeader, PageContent } from '@rocket.chat/ui-client';
|
||||
import { useRouteParameter, useRouter } from '@rocket.chat/ui-contexts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import IntegrationsTable from './IntegrationsTable';
|
||||
import NewBot from './NewBot';
|
||||
import NewZapier from './NewZapier';
|
||||
|
||||
const IntegrationsPage = () => {
|
||||
const { t } = useTranslation();
|
||||
const router = useRouter();
|
||||
const context = useRouteParameter('context');
|
||||
|
||||
const showTable = !['zapier', 'bots'].includes(context || '');
|
||||
|
||||
return (
|
||||
<Page flexDirection='column'>
|
||||
<PageHeader title={t('Integrations')}>
|
||||
<ButtonGroup>
|
||||
<Button
|
||||
primary
|
||||
onClick={() => router.navigate(`/admin/integrations/new/${context === 'webhook-outgoing' ? 'outgoing' : 'incoming'}`)}
|
||||
>
|
||||
{t('New')}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</PageHeader>
|
||||
<Tabs>
|
||||
<TabsItem selected={!context} onClick={() => router.navigate('/admin/integrations')}>
|
||||
{t('All')}
|
||||
</TabsItem>
|
||||
<TabsItem selected={context === 'webhook-incoming'} onClick={() => router.navigate('/admin/integrations/webhook-incoming')}>
|
||||
{t('Incoming')}
|
||||
</TabsItem>
|
||||
<TabsItem selected={context === 'webhook-outgoing'} onClick={() => router.navigate('/admin/integrations/webhook-outgoing')}>
|
||||
{t('Outgoing')}
|
||||
</TabsItem>
|
||||
<TabsItem selected={context === 'zapier'} onClick={() => router.navigate('/admin/integrations/zapier')}>
|
||||
{t('Zapier')}
|
||||
</TabsItem>
|
||||
<TabsItem selected={context === 'bots'} onClick={() => router.navigate('/admin/integrations/bots')}>
|
||||
{t('Bots')}
|
||||
</TabsItem>
|
||||
</Tabs>
|
||||
<PageContent>
|
||||
{context === 'zapier' && <NewZapier />}
|
||||
{context === 'bots' && <NewBot />}
|
||||
{showTable && <IntegrationsTable type={context} />}
|
||||
</PageContent>
|
||||
</Page>
|
||||
);
|
||||
};
|
||||
|
||||
export default IntegrationsPage;
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useRouteParameter, useAtLeastOnePermission } from '@rocket.chat/ui-contexts';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import EditIntegrationsPage from './EditIntegrationsPage';
|
||||
import EditIntegrationsPageWithData from './EditIntegrationsPageWithData';
|
||||
import IntegrationsPage from './IntegrationsPage';
|
||||
import NotAuthorizedPage from '../../notAuthorized/NotAuthorizedPage';
|
||||
import OutgoingWebhookHistoryPage from './outgoing/history/OutgoingWebhookHistoryPage';
|
||||
|
||||
const IntegrationsRoute = () => {
|
||||
const context = useRouteParameter('context');
|
||||
const integrationId = useRouteParameter('id');
|
||||
|
||||
const canViewIntegrationsPage = useAtLeastOnePermission(
|
||||
useMemo(
|
||||
() => [
|
||||
'manage-incoming-integrations',
|
||||
'manage-outgoing-integrations',
|
||||
'manage-own-incoming-integrations',
|
||||
'manage-own-outgoing-integrations',
|
||||
],
|
||||
[],
|
||||
),
|
||||
);
|
||||
|
||||
if (!canViewIntegrationsPage) {
|
||||
return <NotAuthorizedPage />;
|
||||
}
|
||||
|
||||
if (context === 'new') {
|
||||
return <EditIntegrationsPage />;
|
||||
}
|
||||
|
||||
if (context === 'edit' && integrationId) {
|
||||
return <EditIntegrationsPageWithData integrationId={integrationId} />;
|
||||
}
|
||||
|
||||
if (context === 'history') {
|
||||
return <OutgoingWebhookHistoryPage />;
|
||||
}
|
||||
|
||||
return <IntegrationsPage />;
|
||||
};
|
||||
|
||||
export default IntegrationsRoute;
|
||||
@@ -0,0 +1,150 @@
|
||||
import { Pagination, States, StatesActions, StatesAction, StatesIcon, StatesTitle } from '@rocket.chat/fuselage';
|
||||
import { useDebouncedValue } from '@rocket.chat/fuselage-hooks';
|
||||
import { escapeRegExp } from '@rocket.chat/tools';
|
||||
import {
|
||||
GenericTable,
|
||||
GenericTableBody,
|
||||
GenericTableHeader,
|
||||
GenericTableHeaderCell,
|
||||
GenericTableLoadingTable,
|
||||
usePagination,
|
||||
useSort,
|
||||
} from '@rocket.chat/ui-client';
|
||||
import { useEndpoint, useRoute, useTranslation, useLayout } from '@rocket.chat/ui-contexts';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useMemo, useCallback, useState } from 'react';
|
||||
|
||||
import IntegrationRow from './IntegrationRow';
|
||||
import FilterByText from '../../../components/FilterByText';
|
||||
import GenericNoResults from '../../../components/GenericNoResults';
|
||||
|
||||
export type IntegrationsTableProps = { type?: string };
|
||||
|
||||
const IntegrationsTable = ({ type }: IntegrationsTableProps) => {
|
||||
const t = useTranslation();
|
||||
const { isMobile } = useLayout();
|
||||
|
||||
const [text, setText] = useState('');
|
||||
const router = useRoute('admin-integrations');
|
||||
const { sortBy, sortDirection, setSort } = useSort<'name' | 'channel' | '_createdBy' | '_createdAt' | 'username'>('name');
|
||||
const { current, itemsPerPage, setItemsPerPage: onSetItemsPerPage, setCurrent: onSetCurrent, ...paginationProps } = usePagination();
|
||||
|
||||
const query = useDebouncedValue(
|
||||
useMemo(
|
||||
() => ({
|
||||
name: escapeRegExp(text),
|
||||
type,
|
||||
sort: `{ "${sortBy}": ${sortDirection === 'asc' ? 1 : -1} }`,
|
||||
count: itemsPerPage,
|
||||
offset: current,
|
||||
}),
|
||||
[text, itemsPerPage, current, sortBy, sortDirection, type],
|
||||
),
|
||||
500,
|
||||
);
|
||||
|
||||
const getIntegrations = useEndpoint('GET', '/v1/integrations.list');
|
||||
const { data, isLoading, isSuccess, isError, refetch } = useQuery({
|
||||
queryKey: ['integrations', query],
|
||||
queryFn: async () => getIntegrations(query),
|
||||
});
|
||||
|
||||
const onClick = useCallback(
|
||||
(_id: string, type: string) => () =>
|
||||
router.push({
|
||||
context: 'edit',
|
||||
type: type === 'webhook-incoming' ? 'incoming' : 'outgoing',
|
||||
id: _id,
|
||||
}),
|
||||
[router],
|
||||
);
|
||||
|
||||
const headers = (
|
||||
<>
|
||||
<GenericTableHeaderCell
|
||||
key='name'
|
||||
direction={sortDirection}
|
||||
active={sortBy === 'name'}
|
||||
onClick={setSort}
|
||||
sort='name'
|
||||
{...(!isMobile && { width: 'x280' })}
|
||||
>
|
||||
{t('Name')}
|
||||
</GenericTableHeaderCell>
|
||||
<GenericTableHeaderCell key='channel' direction={sortDirection} active={sortBy === 'channel'} onClick={setSort} sort='channel'>
|
||||
{t('Post_to')}
|
||||
</GenericTableHeaderCell>
|
||||
<GenericTableHeaderCell
|
||||
key='_createdBy'
|
||||
direction={sortDirection}
|
||||
active={sortBy === '_createdBy'}
|
||||
onClick={setSort}
|
||||
sort='_createdBy'
|
||||
>
|
||||
{t('Created_by')}
|
||||
</GenericTableHeaderCell>
|
||||
{!isMobile && (
|
||||
<GenericTableHeaderCell
|
||||
key='_createdAt'
|
||||
direction={sortDirection}
|
||||
active={sortBy === '_createdAt'}
|
||||
onClick={setSort}
|
||||
sort='_createdAt'
|
||||
>
|
||||
{t('Created_at')}
|
||||
</GenericTableHeaderCell>
|
||||
)}
|
||||
<GenericTableHeaderCell key='username' direction={sortDirection} active={sortBy === 'username'} onClick={setSort} sort='username'>
|
||||
{t('Post_as')}
|
||||
</GenericTableHeaderCell>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<FilterByText placeholder={t('Search_Integrations')} value={text} onChange={(event) => setText(event.target.value)} />
|
||||
{isLoading && (
|
||||
<GenericTable>
|
||||
<GenericTableHeader>{headers}</GenericTableHeader>
|
||||
<GenericTableBody>
|
||||
<GenericTableLoadingTable headerCells={!isMobile ? 5 : 4} />
|
||||
</GenericTableBody>
|
||||
</GenericTable>
|
||||
)}
|
||||
{isSuccess && data && data.integrations.length > 0 && (
|
||||
<>
|
||||
<GenericTable aria-label={t('Integrations_table')}>
|
||||
<GenericTableHeader>{headers}</GenericTableHeader>
|
||||
<GenericTableBody>
|
||||
{isSuccess &&
|
||||
data?.integrations.map((integration) => (
|
||||
<IntegrationRow key={integration._id} integration={integration} isMobile={isMobile} onClick={onClick} />
|
||||
))}
|
||||
</GenericTableBody>
|
||||
</GenericTable>
|
||||
<Pagination
|
||||
divider
|
||||
current={current}
|
||||
itemsPerPage={itemsPerPage}
|
||||
count={data?.total || 0}
|
||||
onSetItemsPerPage={onSetItemsPerPage}
|
||||
onSetCurrent={onSetCurrent}
|
||||
{...paginationProps}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{isSuccess && data && data.integrations.length === 0 && <GenericNoResults />}
|
||||
{isError && (
|
||||
<States>
|
||||
<StatesIcon name='warning' variation='danger' />
|
||||
<StatesTitle>{t('Something_went_wrong')}</StatesTitle>
|
||||
<StatesActions>
|
||||
<StatesAction onClick={() => refetch()}>{t('Reload_page')}</StatesAction>
|
||||
</StatesActions>
|
||||
</States>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default IntegrationsTable;
|
||||
14
apps/meteor/client/views/admin/integrations/NewBot.tsx
Normal file
14
apps/meteor/client/views/admin/integrations/NewBot.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Box } from '@rocket.chat/fuselage';
|
||||
import { ExternalLink } from '@rocket.chat/ui-client';
|
||||
import { Trans } from 'react-i18next';
|
||||
|
||||
const NewBot = () => (
|
||||
<Box paddingBlock={20} fontScale='h4' key='bots'>
|
||||
<Trans
|
||||
i18nKey='additional_integrations_Bots'
|
||||
components={{ a: <ExternalLink to='https://github.com/RocketChat/hubot-rocketchat' /> }}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
|
||||
export default NewBot;
|
||||
82
apps/meteor/client/views/admin/integrations/NewZapier.tsx
Normal file
82
apps/meteor/client/views/admin/integrations/NewZapier.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import { Box, Skeleton, Margins, Callout } from '@rocket.chat/fuselage';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useOAuthAppQuery } from '../../oauth/hooks/useOAuthAppQuery';
|
||||
import PageLoading from '../../root/PageLoading';
|
||||
|
||||
const blogSpotStyleScriptImport = (src: string) =>
|
||||
new Promise((resolve) => {
|
||||
const script = document.createElement('script');
|
||||
script.type = 'text/javascript';
|
||||
document.body.appendChild(script);
|
||||
|
||||
const resolveFunc = (event: Event) => resolve(event.currentTarget);
|
||||
|
||||
script.addEventListener('readystatechange', (event) => resolveFunc(event));
|
||||
script.addEventListener('load', (event) => resolveFunc(event));
|
||||
script.src = src;
|
||||
});
|
||||
|
||||
const NewZapier = ({ ...props }) => {
|
||||
const { t } = useTranslation();
|
||||
const oauthAppQuery = useOAuthAppQuery('zapier');
|
||||
const zapierAvailable = !oauthAppQuery.isLoading && !oauthAppQuery.isError && oauthAppQuery.data;
|
||||
const [script, setScript] = useState<HTMLScriptElement>();
|
||||
|
||||
useEffect(() => {
|
||||
const importZapier = async () => {
|
||||
const scriptEl = await blogSpotStyleScriptImport(
|
||||
'https://zapier.com/apps/embed/widget.js?services=rocketchat&html_id=zapier-goes-here',
|
||||
);
|
||||
|
||||
setScript(scriptEl as HTMLScriptElement);
|
||||
};
|
||||
|
||||
if (!script && zapierAvailable) {
|
||||
importZapier();
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (script) {
|
||||
script.parentNode?.removeChild(script);
|
||||
}
|
||||
};
|
||||
}, [script, zapierAvailable]);
|
||||
|
||||
if (oauthAppQuery.isLoading) {
|
||||
return <PageLoading />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Callout
|
||||
type='warning'
|
||||
icon='warning'
|
||||
title={t(!zapierAvailable ? 'Zapier_integration_is_not_available' : 'Zapier_integration_has_been_deprecated')}
|
||||
marginBlockStart={16}
|
||||
marginBlockEnd={4}
|
||||
>
|
||||
{t(!zapierAvailable ? 'Install_Zapier_from_marketplace_new_workspaces' : 'Install_Zapier_from_marketplace')}
|
||||
</Callout>
|
||||
{zapierAvailable && (
|
||||
<>
|
||||
{!script && (
|
||||
<Box display='flex' flexDirection='column' alignItems='stretch' marginBlockStart={10}>
|
||||
<Margins blockEnd={14}>
|
||||
<Skeleton variant='rect' height={71} />
|
||||
<Skeleton variant='rect' height={71} />
|
||||
<Skeleton variant='rect' height={71} />
|
||||
<Skeleton variant='rect' height={71} />
|
||||
<Skeleton variant='rect' height={71} />
|
||||
</Margins>
|
||||
</Box>
|
||||
)}
|
||||
<Box id='zapier-goes-here' {...props} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default NewZapier;
|
||||
@@ -0,0 +1,13 @@
|
||||
const separator = ',';
|
||||
|
||||
export function triggerWordsToArray(s?: string): Array<string> {
|
||||
if (typeof s !== 'string' || s.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return s.split(separator);
|
||||
}
|
||||
|
||||
export function triggerWordsToString(triggerWords?: Array<string>): string {
|
||||
return triggerWords?.join(separator) ?? '';
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useEndpoint, useRouter, useToastMessageDispatch } from '@rocket.chat/ui-contexts';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export const useCreateIntegration = (integrationType: 'webhook-incoming' | 'webhook-outgoing') => {
|
||||
const { t } = useTranslation();
|
||||
const router = useRouter();
|
||||
const createIntegration = useEndpoint('POST', '/v1/integrations.create');
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: createIntegration,
|
||||
onSuccess: (data) => {
|
||||
dispatchToastMessage({ type: 'success', message: t('Integration_added') });
|
||||
router.navigate(
|
||||
`/admin/integrations/edit/${integrationType === 'webhook-incoming' ? 'incoming' : 'outgoing'}/${data.integration._id}`,
|
||||
);
|
||||
},
|
||||
onError: (error) => {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useEndpoint, useRouter, useSetModal, useToastMessageDispatch } from '@rocket.chat/ui-contexts';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export const useDeleteIntegration = (integrationType: 'webhook-incoming' | 'webhook-outgoing') => {
|
||||
const { t } = useTranslation();
|
||||
const router = useRouter();
|
||||
const setModal = useSetModal();
|
||||
|
||||
const createIntegration = useEndpoint('POST', '/v1/integrations.remove');
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: createIntegration,
|
||||
onSuccess: () => {
|
||||
dispatchToastMessage({ type: 'success', message: t('Your_entry_has_been_deleted') });
|
||||
router.navigate(`/admin/integrations/${integrationType}`);
|
||||
},
|
||||
onError: (error) => {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
},
|
||||
onSettled: () => {
|
||||
setModal(null);
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { INewIncomingIntegration } from '@rocket.chat/core-typings';
|
||||
import { useAbsoluteUrl } from '@rocket.chat/ui-contexts';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
type UseExampleDataParams = {
|
||||
additionalFields: Partial<INewIncomingIntegration>;
|
||||
url: string;
|
||||
};
|
||||
|
||||
export function useExampleData({
|
||||
additionalFields,
|
||||
url,
|
||||
}: UseExampleDataParams): [integrationObj: Partial<INewIncomingIntegration>, curl: string] {
|
||||
const imageUrl = useAbsoluteUrl()('/images/integration-attachment-example.png');
|
||||
return useMemo(() => {
|
||||
const exampleData = {
|
||||
...additionalFields,
|
||||
text: 'Example message',
|
||||
attachments: [
|
||||
{
|
||||
title: 'Rocket.Chat',
|
||||
title_link: 'https://rocket.chat',
|
||||
text: 'Rocket.Chat, the best open source chat',
|
||||
image_url: imageUrl,
|
||||
color: '#764FA5',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
return [exampleData, `curl -X POST -H 'Content-Type: application/json' --data '${JSON.stringify(exampleData)}' ${url}`];
|
||||
}, [additionalFields, url, imageUrl]);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useEndpoint, useRouter, useToastMessageDispatch } from '@rocket.chat/ui-contexts';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export const useUpdateIntegration = (integrationType: 'webhook-incoming' | 'webhook-outgoing') => {
|
||||
const { t } = useTranslation();
|
||||
const router = useRouter();
|
||||
const updateIntegration = useEndpoint('PUT', '/v1/integrations.update');
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: updateIntegration,
|
||||
onSuccess: () => {
|
||||
dispatchToastMessage({ type: 'success', message: t('Integration_updated') });
|
||||
router.navigate(`/admin/integrations/${integrationType}`);
|
||||
},
|
||||
onError: (error) => {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,134 @@
|
||||
import type { IIncomingIntegration, Serialized } from '@rocket.chat/core-typings';
|
||||
import { Button, ButtonGroup, Tabs, TabsItem } from '@rocket.chat/fuselage';
|
||||
import { GenericModal, Page, PageHeader, PageScrollableContentWithShadow, PageFooter } from '@rocket.chat/ui-client';
|
||||
import { useSetModal, useTranslation, useRouter, useRouteParameter } from '@rocket.chat/ui-contexts';
|
||||
import { useId, useCallback } from 'react';
|
||||
import { FormProvider, useForm } from 'react-hook-form';
|
||||
|
||||
import IncomingWebhookForm from './IncomingWebhookForm';
|
||||
import { useCreateIntegration } from '../hooks/useCreateIntegration';
|
||||
import { useDeleteIntegration } from '../hooks/useDeleteIntegration';
|
||||
import { useUpdateIntegration } from '../hooks/useUpdateIntegration';
|
||||
|
||||
export type EditIncomingWebhookFormData = {
|
||||
enabled: boolean;
|
||||
channel: string;
|
||||
username: string;
|
||||
name: string;
|
||||
alias: string;
|
||||
avatar: string;
|
||||
emoji: string;
|
||||
scriptEnabled: boolean;
|
||||
scriptEngine: 'isolated-vm';
|
||||
overrideDestinationChannelEnabled: boolean;
|
||||
script: string;
|
||||
};
|
||||
|
||||
const getInitialValue = (webhookData: Serialized<IIncomingIntegration> | undefined): EditIncomingWebhookFormData => ({
|
||||
enabled: webhookData?.enabled ?? true,
|
||||
channel: webhookData?.channel.join(', ') ?? '',
|
||||
username: webhookData?.username ?? '',
|
||||
name: webhookData?.name ?? '',
|
||||
alias: webhookData?.alias ?? '',
|
||||
avatar: webhookData?.avatar ?? '',
|
||||
emoji: webhookData?.emoji ?? '',
|
||||
scriptEnabled: webhookData?.scriptEnabled ?? false,
|
||||
scriptEngine: webhookData?.scriptEngine ?? 'isolated-vm',
|
||||
overrideDestinationChannelEnabled: webhookData?.overrideDestinationChannelEnabled ?? false,
|
||||
script: webhookData?.script ?? '',
|
||||
});
|
||||
|
||||
const INCOMING_TYPE = 'webhook-incoming';
|
||||
|
||||
export type EditIncomingWebhookProps = {
|
||||
webhookData?: Serialized<IIncomingIntegration>;
|
||||
};
|
||||
|
||||
const EditIncomingWebhook = ({ webhookData }: EditIncomingWebhookProps) => {
|
||||
const t = useTranslation();
|
||||
const router = useRouter();
|
||||
const setModal = useSetModal();
|
||||
const tab = useRouteParameter('type');
|
||||
|
||||
const deleteIntegration = useDeleteIntegration(INCOMING_TYPE);
|
||||
const updateIntegration = useUpdateIntegration(INCOMING_TYPE);
|
||||
const createIntegration = useCreateIntegration(INCOMING_TYPE);
|
||||
|
||||
const methods = useForm<EditIncomingWebhookFormData>({ mode: 'onBlur', values: getInitialValue(webhookData) });
|
||||
|
||||
const {
|
||||
reset,
|
||||
handleSubmit,
|
||||
formState: { isDirty },
|
||||
} = methods;
|
||||
|
||||
const handleDeleteIntegration = useCallback(() => {
|
||||
const onDelete = async () => {
|
||||
if (!webhookData?._id) {
|
||||
return;
|
||||
}
|
||||
|
||||
deleteIntegration.mutate({ integrationId: webhookData._id, type: INCOMING_TYPE });
|
||||
};
|
||||
|
||||
setModal(
|
||||
<GenericModal variant='danger' onConfirm={onDelete} onCancel={() => setModal(null)} confirmText={t('Delete')}>
|
||||
{t('Integration_Delete_Warning')}
|
||||
</GenericModal>,
|
||||
);
|
||||
}, [webhookData?._id, deleteIntegration, setModal, t]);
|
||||
|
||||
const handleSave = useCallback(
|
||||
async (formValues: EditIncomingWebhookFormData) => {
|
||||
if (webhookData?._id) {
|
||||
return updateIntegration.mutate({ integrationId: webhookData?._id, type: INCOMING_TYPE, ...formValues });
|
||||
}
|
||||
|
||||
return createIntegration.mutate({ type: INCOMING_TYPE, ...formValues });
|
||||
},
|
||||
[webhookData?._id, updateIntegration, createIntegration],
|
||||
);
|
||||
|
||||
const formId = useId();
|
||||
|
||||
return (
|
||||
<Page flexDirection='column'>
|
||||
<PageHeader title={t('Integration_Incoming_WebHook')} onClickBack={() => router.navigate('/admin/integrations/webhook-incoming')}>
|
||||
<ButtonGroup>
|
||||
{webhookData?._id && (
|
||||
<Button danger onClick={handleDeleteIntegration}>
|
||||
{t('Delete')}
|
||||
</Button>
|
||||
)}
|
||||
</ButtonGroup>
|
||||
</PageHeader>
|
||||
{!webhookData?._id && (
|
||||
<Tabs>
|
||||
<TabsItem selected={tab === 'incoming'} onClick={() => router.navigate('/admin/integrations/new/incoming')}>
|
||||
{t('Incoming')}
|
||||
</TabsItem>
|
||||
<TabsItem selected={tab === 'outgoing'} onClick={() => router.navigate('/admin/integrations/new/outgoing')}>
|
||||
{t('Outgoing')}
|
||||
</TabsItem>
|
||||
</Tabs>
|
||||
)}
|
||||
<PageScrollableContentWithShadow id={formId} is='form' onSubmit={handleSubmit(handleSave)}>
|
||||
<FormProvider {...methods}>
|
||||
<IncomingWebhookForm webhookData={webhookData} />
|
||||
</FormProvider>
|
||||
</PageScrollableContentWithShadow>
|
||||
<PageFooter isDirty={isDirty}>
|
||||
<ButtonGroup>
|
||||
<Button type='reset' onClick={() => reset()}>
|
||||
{t('Cancel')}
|
||||
</Button>
|
||||
<Button form={formId} primary type='submit'>
|
||||
{t('Save')}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</PageFooter>
|
||||
</Page>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditIncomingWebhook;
|
||||
@@ -0,0 +1,343 @@
|
||||
import type { IIncomingIntegration, Serialized } from '@rocket.chat/core-typings';
|
||||
import type { SelectOption } from '@rocket.chat/fuselage';
|
||||
import {
|
||||
FieldError,
|
||||
IconButton,
|
||||
Accordion,
|
||||
AccordionItem,
|
||||
Field,
|
||||
TextInput,
|
||||
Box,
|
||||
ToggleSwitch,
|
||||
Icon,
|
||||
TextAreaInput,
|
||||
FieldGroup,
|
||||
Select,
|
||||
FieldLabel,
|
||||
FieldRow,
|
||||
FieldHint,
|
||||
} from '@rocket.chat/fuselage';
|
||||
import { useAbsoluteUrl } from '@rocket.chat/ui-contexts';
|
||||
import DOMPurify from 'dompurify';
|
||||
import { useId, useMemo } from 'react';
|
||||
import { Controller, useFormContext } from 'react-hook-form';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
|
||||
import type { EditIncomingWebhookFormData } from './EditIncomingWebhook';
|
||||
import useClipboardWithToast from '../../../../hooks/useClipboardWithToast';
|
||||
import { useHighlightedCode } from '../../../../hooks/useHighlightedCode';
|
||||
import { useExampleData } from '../hooks/useExampleIncomingData';
|
||||
|
||||
export type IncomingWebhookFormProps = { webhookData?: Serialized<IIncomingIntegration> };
|
||||
|
||||
const IncomingWebhookForm = ({ webhookData }: IncomingWebhookFormProps) => {
|
||||
const { t } = useTranslation();
|
||||
const absoluteUrl = useAbsoluteUrl();
|
||||
|
||||
const {
|
||||
control,
|
||||
watch,
|
||||
formState: { errors },
|
||||
} = useFormContext<EditIncomingWebhookFormData>();
|
||||
const { alias, emoji, avatar } = watch();
|
||||
|
||||
const url = absoluteUrl(`hooks/${webhookData?._id}/${webhookData?.token}`);
|
||||
|
||||
const additionalFields = useMemo(
|
||||
() => ({
|
||||
...(alias && { alias }),
|
||||
...(emoji && { emoji }),
|
||||
...(avatar && { avatar }),
|
||||
}),
|
||||
[alias, avatar, emoji],
|
||||
);
|
||||
|
||||
const [exampleData, curlData] = useExampleData({
|
||||
additionalFields,
|
||||
url,
|
||||
});
|
||||
|
||||
const { copy: copyWebhookUrl } = useClipboardWithToast(url);
|
||||
const { copy: copyToken } = useClipboardWithToast(`${webhookData?._id}/${webhookData?.token}`);
|
||||
const { copy: copyCurlData } = useClipboardWithToast(curlData);
|
||||
|
||||
const scriptEngineOptions: SelectOption[] = useMemo(() => [['isolated-vm', t('Script_Engine_isolated_vm')]], [t]);
|
||||
|
||||
const hilightedExampleJson = useHighlightedCode('json', JSON.stringify(exampleData, null, 2));
|
||||
|
||||
const enabledField = useId();
|
||||
const nameField = useId();
|
||||
const channelField = useId();
|
||||
const usernameField = useId();
|
||||
const aliasField = useId();
|
||||
const avatarField = useId();
|
||||
const emojiField = useId();
|
||||
const overrideDestinationChannelEnabledField = useId();
|
||||
const scriptEnabledField = useId();
|
||||
const scriptEngineField = useId();
|
||||
const scriptField = useId();
|
||||
const webhookUrlField = useId();
|
||||
const tokenField = useId();
|
||||
const curlField = useId();
|
||||
|
||||
return (
|
||||
<Box maxWidth='x600' alignSelf='center' width='full'>
|
||||
<Accordion>
|
||||
<AccordionItem defaultExpanded={Boolean(webhookData?._id)} title={t('Instructions')}>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={webhookUrlField}>{t('Webhook_URL')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<TextInput
|
||||
id={webhookUrlField}
|
||||
value={webhookData?._id ? url : t('Will_be_available_here_after_saving')}
|
||||
readOnly
|
||||
endAddon={
|
||||
webhookData?._id ? <IconButton mini onClick={() => copyWebhookUrl()} title={t('Copy')} icon='copy' /> : undefined
|
||||
}
|
||||
aria-describedby={`${webhookUrlField}-hint`}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${webhookUrlField}-hint`}>{t('Send_your_JSON_payloads_to_this_URL')}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={tokenField}>{t('Token')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<TextInput
|
||||
id={tokenField}
|
||||
value={webhookData?._id ? `${webhookData?._id}/${webhookData?.token}` : t('Will_be_available_here_after_saving')}
|
||||
readOnly
|
||||
endAddon={webhookData?._id ? <IconButton mini onClick={() => copyToken()} title={t('Copy')} icon='copy' /> : undefined}
|
||||
/>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t('Example_payload')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Box fontScale='p2' withRichContent flexGrow={1}>
|
||||
<pre>
|
||||
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(hilightedExampleJson) }}></code>
|
||||
</pre>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
{webhookData?._id && (
|
||||
<Field>
|
||||
<FieldLabel htmlFor={curlField}>Curl</FieldLabel>
|
||||
<FieldRow>
|
||||
<TextInput
|
||||
id={curlField}
|
||||
value={curlData}
|
||||
readOnly
|
||||
endAddon={
|
||||
webhookData?._id ? <IconButton mini onClick={() => copyCurlData()} title={t('Copy')} icon='copy' /> : undefined
|
||||
}
|
||||
/>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
)}
|
||||
</FieldGroup>
|
||||
</AccordionItem>
|
||||
<AccordionItem title={t('Settings')} defaultExpanded>
|
||||
<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>
|
||||
<FieldLabel htmlFor={nameField}>{t('Name')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
render={({ field }) => <TextInput id={nameField} {...field} aria-describedby={`${nameField}-hint`} />}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${nameField}-hint`}>{t('You_should_name_it_to_easily_manage_your_integrations')}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={channelField} required>
|
||||
{t('Post_to_Channel')}
|
||||
</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='channel'
|
||||
control={control}
|
||||
rules={{ required: t('Required_field', { field: t('Post_to_Channel') }) }}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
id={channelField}
|
||||
{...field}
|
||||
endAddon={<Icon name='at' size='x20' />}
|
||||
aria-describedby={`${channelField}-hint-1 ${channelField}-hint-2 ${channelField}-error`}
|
||||
aria-required={true}
|
||||
aria-invalid={Boolean(errors?.channel)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${channelField}-hint-1`}>{t('Messages_that_are_sent_to_the_Incoming_WebHook_will_be_posted_here')}</FieldHint>
|
||||
<FieldHint id={`${channelField}-hint-2`}>
|
||||
<Trans i18nKey='Start_with_s_for_user_or_s_for_channel_Eg_s_or_s' components={{ code: <code className='inline' /> }} />
|
||||
</FieldHint>
|
||||
{errors?.channel && (
|
||||
<FieldError aria-live='assertive' id={`${channelField}-error`}>
|
||||
{errors?.channel.message}
|
||||
</FieldError>
|
||||
)}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={usernameField} required>
|
||||
{t('Post_as')}
|
||||
</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='username'
|
||||
control={control}
|
||||
rules={{ required: t('Required_field', { field: t('Post_as') }) }}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
id={usernameField}
|
||||
{...field}
|
||||
endAddon={<Icon name='user' size='x20' />}
|
||||
aria-describedby={`${usernameField}-hint-1 ${usernameField}-hint-2 ${usernameField}-error`}
|
||||
aria-required={true}
|
||||
aria-invalid={Boolean(errors?.username)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${usernameField}-hint-1`}>{t('Choose_the_username_that_this_integration_will_post_as')}</FieldHint>
|
||||
<FieldHint id={`${usernameField}-hint-2`}>
|
||||
{t('User_must_exist_and_have_permission', { permission: 'message-impersonate' })}
|
||||
</FieldHint>
|
||||
{errors?.username && (
|
||||
<FieldError aria-live='assertive' id={`${usernameField}-error`}>
|
||||
{errors.username.message}
|
||||
</FieldError>
|
||||
)}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={aliasField}>{t('Alias')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='alias'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
id={aliasField}
|
||||
{...field}
|
||||
aria-describedby={`${aliasField}-hint`}
|
||||
endAddon={<Icon name='edit' size='x20' />}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${aliasField}-hint`}>{t('Choose_the_alias_that_will_appear_before_the_username_in_messages')}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={avatarField}>{t('Avatar_URL')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='avatar'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
id={avatarField}
|
||||
{...field}
|
||||
aria-describedby={`${avatarField}-hint-1 ${avatarField}-hint-2`}
|
||||
endAddon={<Icon name='user-rounded' size='x20' alignSelf='center' />}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${avatarField}-hint-1`}>{t('You_can_change_a_different_avatar_too')}</FieldHint>
|
||||
<FieldHint id={`${avatarField}-hint-2`}>{t('Should_be_a_URL_of_an_image')}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={emojiField}>{t('Emoji')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='emoji'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
id={emojiField}
|
||||
{...field}
|
||||
aria-describedby={`${emojiField}-hint-1 ${emojiField}-hint-2`}
|
||||
endAddon={<Icon name='emoji' size='x20' alignSelf='center' />}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${emojiField}-hint-1`}>{t('You_can_use_an_emoji_as_avatar')}</FieldHint>
|
||||
<FieldHint id={`${emojiField}-hint-2`}>
|
||||
<Trans i18nKey='Example_s' values={{ value: ':ghost:' }} components={{ code: <code className='inline' /> }} />
|
||||
</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel htmlFor={overrideDestinationChannelEnabledField}>{t('Override_Destination_Channel')}</FieldLabel>
|
||||
<Controller
|
||||
name='overrideDestinationChannelEnabled'
|
||||
control={control}
|
||||
render={({ field: { value, ...field } }) => (
|
||||
<ToggleSwitch id={overrideDestinationChannelEnabledField} {...field} checked={value} />
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel htmlFor={scriptEnabledField}>{t('Script_Enabled')}</FieldLabel>
|
||||
<Controller
|
||||
name='scriptEnabled'
|
||||
control={control}
|
||||
render={({ field: { value, ...field } }) => <ToggleSwitch id={scriptEnabledField} {...field} checked={value} />}
|
||||
/>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={scriptEngineField}>{t('Script_Engine')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='scriptEngine'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
id={scriptEngineField}
|
||||
aria-describedby={`${scriptEngineField}-hint`}
|
||||
{...field}
|
||||
options={scriptEngineOptions}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${scriptEngineField}-hint`}>{t('Script_Engine_Description')}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={scriptField}>{t('Script')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='script'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextAreaInput id={scriptField} {...field} rows={10} endAddon={<Icon name='code' size='x20' alignSelf='center' />} />
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default IncomingWebhookForm;
|
||||
@@ -0,0 +1,170 @@
|
||||
import type { IOutgoingIntegration, OutgoingIntegrationEvent, Serialized } from '@rocket.chat/core-typings';
|
||||
import { Button, ButtonGroup, Tabs, TabsItem } from '@rocket.chat/fuselage';
|
||||
import { GenericModal, Page, PageHeader, PageScrollableContentWithShadow, PageFooter } from '@rocket.chat/ui-client';
|
||||
import { useSetModal, useTranslation, useRouter, useRouteParameter } from '@rocket.chat/ui-contexts';
|
||||
import { useId, useCallback } from 'react';
|
||||
import { FormProvider, useForm } from 'react-hook-form';
|
||||
|
||||
import OutgoingWebhookForm from './OutgoingWebhookForm';
|
||||
import { triggerWordsToArray, triggerWordsToString } from '../helpers/triggerWords';
|
||||
import { useCreateIntegration } from '../hooks/useCreateIntegration';
|
||||
import { useDeleteIntegration } from '../hooks/useDeleteIntegration';
|
||||
import { useUpdateIntegration } from '../hooks/useUpdateIntegration';
|
||||
|
||||
type EditOutgoingWebhookFormData = {
|
||||
enabled: boolean;
|
||||
impersonateUser: boolean;
|
||||
event: OutgoingIntegrationEvent;
|
||||
urls: string;
|
||||
token: string;
|
||||
triggerWords: string;
|
||||
targetRoom: string;
|
||||
channel: string;
|
||||
username: string;
|
||||
name: string;
|
||||
alias: string;
|
||||
avatar: string;
|
||||
emoji: string;
|
||||
scriptEnabled: boolean;
|
||||
scriptEngine: 'isolated-vm';
|
||||
script: string;
|
||||
retryFailedCalls: boolean;
|
||||
retryCount: number;
|
||||
retryDelay: string;
|
||||
triggerWordAnywhere: boolean;
|
||||
runOnEdits: boolean;
|
||||
};
|
||||
|
||||
const getInitialValue = (webhookData: Serialized<IOutgoingIntegration> | undefined, defaultToken: string): EditOutgoingWebhookFormData => ({
|
||||
enabled: webhookData?.enabled ?? true,
|
||||
impersonateUser: webhookData?.impersonateUser ?? false,
|
||||
event: webhookData?.event ?? 'sendMessage',
|
||||
urls: webhookData?.urls?.join('\n') ?? '',
|
||||
token: webhookData?.token ?? defaultToken,
|
||||
triggerWords: triggerWordsToString(webhookData?.triggerWords) ?? '',
|
||||
targetRoom: webhookData?.targetRoom ?? '',
|
||||
channel: webhookData?.channel.join(', ') ?? '',
|
||||
username: webhookData?.username ?? '',
|
||||
name: webhookData?.name ?? '',
|
||||
alias: webhookData?.alias ?? '',
|
||||
avatar: webhookData?.avatar ?? '',
|
||||
emoji: webhookData?.emoji ?? '',
|
||||
scriptEnabled: webhookData?.scriptEnabled ?? false,
|
||||
scriptEngine: webhookData?.scriptEngine ?? 'isolated-vm',
|
||||
script: webhookData?.script ?? '',
|
||||
retryFailedCalls: webhookData?.retryFailedCalls ?? true,
|
||||
retryCount: webhookData?.retryCount ?? 6,
|
||||
retryDelay: webhookData?.retryDelay ?? 'powers-of-ten',
|
||||
triggerWordAnywhere: webhookData?.triggerWordAnywhere ?? false,
|
||||
runOnEdits: webhookData?.runOnEdits ?? true,
|
||||
});
|
||||
|
||||
const OUTGOING_TYPE = 'webhook-outgoing';
|
||||
|
||||
export type EditOutgoingWebhookProps = {
|
||||
webhookData?: Serialized<IOutgoingIntegration>;
|
||||
};
|
||||
|
||||
const EditOutgoingWebhook = ({ webhookData }: EditOutgoingWebhookProps) => {
|
||||
const t = useTranslation();
|
||||
const setModal = useSetModal();
|
||||
const router = useRouter();
|
||||
|
||||
const tab = useRouteParameter('type');
|
||||
|
||||
const defaultToken = useId();
|
||||
|
||||
const methods = useForm<EditOutgoingWebhookFormData>({ mode: 'onBlur', values: getInitialValue(webhookData, defaultToken) });
|
||||
const {
|
||||
reset,
|
||||
handleSubmit,
|
||||
formState: { isDirty },
|
||||
watch,
|
||||
} = methods;
|
||||
|
||||
const deleteIntegration = useDeleteIntegration(OUTGOING_TYPE);
|
||||
const createIntegration = useCreateIntegration(OUTGOING_TYPE);
|
||||
const updateIntegration = useUpdateIntegration(OUTGOING_TYPE);
|
||||
|
||||
const handleDeleteIntegration = useCallback(() => {
|
||||
const onDelete = async () => {
|
||||
deleteIntegration.mutate({ type: OUTGOING_TYPE, integrationId: webhookData?._id });
|
||||
};
|
||||
|
||||
setModal(
|
||||
<GenericModal variant='danger' onConfirm={onDelete} onCancel={() => setModal(null)} confirmText={t('Delete')}>
|
||||
{t('Integration_Delete_Warning')}
|
||||
</GenericModal>,
|
||||
);
|
||||
}, [webhookData?._id, deleteIntegration, setModal, t]);
|
||||
|
||||
const { urls, triggerWords } = watch();
|
||||
|
||||
const handleSave = useCallback(
|
||||
async (formValues: EditOutgoingWebhookFormData) => {
|
||||
if (webhookData?._id) {
|
||||
return updateIntegration.mutate({
|
||||
type: OUTGOING_TYPE,
|
||||
integrationId: webhookData?._id,
|
||||
...formValues,
|
||||
triggerWords: triggerWordsToArray(triggerWords),
|
||||
urls: urls.split('\n'),
|
||||
});
|
||||
}
|
||||
|
||||
return createIntegration.mutate({
|
||||
type: OUTGOING_TYPE,
|
||||
...formValues,
|
||||
triggerWords: triggerWordsToArray(triggerWords),
|
||||
urls: urls.split('\n'),
|
||||
});
|
||||
},
|
||||
[webhookData?._id, createIntegration, updateIntegration, triggerWords, urls],
|
||||
);
|
||||
|
||||
const formId = useId();
|
||||
|
||||
return (
|
||||
<Page flexDirection='column'>
|
||||
<PageHeader title={t('Integration_Outgoing_WebHook')} onClickBack={() => router.navigate('/admin/integrations/webhook-outgoing')}>
|
||||
<ButtonGroup>
|
||||
{webhookData?._id && (
|
||||
<Button onClick={() => router.navigate(`/admin/integrations/history/outgoing/${webhookData._id}`)}>{t('History')}</Button>
|
||||
)}
|
||||
{webhookData?._id && (
|
||||
<Button danger onClick={handleDeleteIntegration}>
|
||||
{t('Delete')}
|
||||
</Button>
|
||||
)}
|
||||
</ButtonGroup>
|
||||
</PageHeader>
|
||||
{!webhookData?._id && (
|
||||
<Tabs>
|
||||
<TabsItem selected={tab === 'incoming'} onClick={() => router.navigate('/admin/integrations/new/incoming')}>
|
||||
{t('Incoming')}
|
||||
</TabsItem>
|
||||
<TabsItem selected={tab === 'outgoing'} onClick={() => router.navigate('/admin/integrations/new/outgoing')}>
|
||||
{t('Outgoing')}
|
||||
</TabsItem>
|
||||
</Tabs>
|
||||
)}
|
||||
<PageScrollableContentWithShadow is='form' id={formId} onSubmit={handleSubmit(handleSave)}>
|
||||
<FormProvider {...methods}>
|
||||
<OutgoingWebhookForm />
|
||||
</FormProvider>
|
||||
</PageScrollableContentWithShadow>
|
||||
<PageFooter isDirty={isDirty}>
|
||||
<ButtonGroup>
|
||||
<Button type='reset' onClick={() => reset()}>
|
||||
{t('Cancel')}
|
||||
</Button>
|
||||
<Button form={formId} primary type='submit'>
|
||||
{t('Save')}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</PageFooter>
|
||||
</Page>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditOutgoingWebhook;
|
||||
@@ -0,0 +1,527 @@
|
||||
import type { IOutgoingIntegration } from '@rocket.chat/core-typings';
|
||||
import type { SelectOption } from '@rocket.chat/fuselage';
|
||||
import {
|
||||
FieldError,
|
||||
AccordionItem,
|
||||
FieldHint,
|
||||
FieldLabel,
|
||||
FieldRow,
|
||||
Field,
|
||||
TextInput,
|
||||
Box,
|
||||
ToggleSwitch,
|
||||
Icon,
|
||||
TextAreaInput,
|
||||
FieldGroup,
|
||||
Select,
|
||||
Accordion,
|
||||
NumberInput,
|
||||
} from '@rocket.chat/fuselage';
|
||||
import DOMPurify from 'dompurify';
|
||||
import { useId, useMemo } from 'react';
|
||||
import { useFormContext, Controller } from 'react-hook-form';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
|
||||
import { outgoingEvents } from '../../../../../app/integrations/lib/outgoingEvents';
|
||||
import { useHighlightedCode } from '../../../../hooks/useHighlightedCode';
|
||||
import { useExampleData } from '../hooks/useExampleIncomingData';
|
||||
|
||||
type EditOutgoingWebhookPayload = Pick<
|
||||
IOutgoingIntegration,
|
||||
| 'enabled'
|
||||
| 'impersonateUser'
|
||||
| 'event'
|
||||
| 'urls'
|
||||
| 'token'
|
||||
| 'triggerWords'
|
||||
| 'targetRoom'
|
||||
| 'channel'
|
||||
| 'username'
|
||||
| 'name'
|
||||
| 'alias'
|
||||
| 'avatar'
|
||||
| 'emoji'
|
||||
| 'scriptEnabled'
|
||||
| 'scriptEngine'
|
||||
| 'script'
|
||||
| 'retryFailedCalls'
|
||||
| 'retryCount'
|
||||
| 'retryDelay'
|
||||
| 'triggerWordAnywhere'
|
||||
| 'runOnEdits'
|
||||
>;
|
||||
|
||||
const OutgoingWebhookForm = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const {
|
||||
control,
|
||||
watch,
|
||||
formState: { errors },
|
||||
} = useFormContext<EditOutgoingWebhookPayload>();
|
||||
const { event, alias, emoji, avatar } = watch();
|
||||
|
||||
const retryDelayOptions: SelectOption[] = useMemo(
|
||||
() => [
|
||||
['powers-of-ten', t('powers-of-ten')],
|
||||
['powers-of-two', t('powers-of-two')],
|
||||
['increments-of-two', t('increments-of-two')],
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
const eventOptions: SelectOption[] = useMemo(() => Object.entries(outgoingEvents).map(([key, val]) => [key, t(val.label)]), [t]);
|
||||
|
||||
const scriptEngineOptions: SelectOption[] = useMemo(() => [['isolated-vm', t('Script_Engine_isolated_vm')]], [t]);
|
||||
|
||||
const showChannel = useMemo(() => outgoingEvents[event].use.channel, [event]);
|
||||
const showTriggerWords = useMemo(() => outgoingEvents[event].use.triggerWords, [event]);
|
||||
const showTargetRoom = useMemo(() => outgoingEvents[event].use.targetRoom, [event]);
|
||||
|
||||
const additionalFields = useMemo(
|
||||
() => ({
|
||||
...(alias && { alias }),
|
||||
...(emoji && { emoji }),
|
||||
...(avatar && { avatar }),
|
||||
}),
|
||||
[alias, avatar, emoji],
|
||||
);
|
||||
|
||||
const [exampleData] = useExampleData({
|
||||
additionalFields,
|
||||
url: '',
|
||||
});
|
||||
|
||||
const hilightedExampleJson = useHighlightedCode('json', JSON.stringify(exampleData, null, 2));
|
||||
|
||||
const eventField = useId();
|
||||
const enabledField = useId();
|
||||
const nameField = useId();
|
||||
const channelField = useId();
|
||||
const triggerWordsField = useId();
|
||||
const targetRoomField = useId();
|
||||
const urlsField = useId();
|
||||
const impersonateUserField = useId();
|
||||
const usernameField = useId();
|
||||
const aliasField = useId();
|
||||
const avatarField = useId();
|
||||
const emojiField = useId();
|
||||
const tokenField = useId();
|
||||
const scriptEnabledField = useId();
|
||||
const scriptEngineField = useId();
|
||||
const scriptField = useId();
|
||||
const retryFailedCallsField = useId();
|
||||
const retryCountField = useId();
|
||||
const retryDelayField = useId();
|
||||
const triggerWordAnywhereField = useId();
|
||||
const runOnEditsField = useId();
|
||||
|
||||
return (
|
||||
<Box maxWidth='x600' alignSelf='center' width='full'>
|
||||
<Accordion>
|
||||
<AccordionItem defaultExpanded title={t('Settings')}>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={eventField}>{t('Event_Trigger')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='event'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<Select id={eventField} {...field} options={eventOptions} aria-description={`${eventField}-hint`} />
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${eventField}-hint`}>{t('Event_Trigger_Description')}</FieldHint>
|
||||
</Field>
|
||||
<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>
|
||||
<FieldLabel htmlFor={nameField}>{t('Name')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
render={({ field }) => <TextInput id={nameField} {...field} aria-describedby={`${nameField}-hint`} />}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${nameField}-hint`}>{t('You_should_name_it_to_easily_manage_your_integrations')}</FieldHint>
|
||||
</Field>
|
||||
{showChannel && (
|
||||
<Field>
|
||||
<FieldLabel htmlFor={channelField}>{t('Channel')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='channel'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
id={channelField}
|
||||
{...field}
|
||||
endAddon={<Icon name='at' size='x20' />}
|
||||
aria-describedby={`${channelField}-hint-1 ${channelField}-hint-2 ${channelField}-hint-3`}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${channelField}-hint-1`}>{t('Channel_to_listen_on')}</FieldHint>
|
||||
<FieldHint id={`${channelField}-hint-2`}>
|
||||
<Trans i18nKey='Start_with_s_for_user_or_s_for_channel_Eg_s_or_s' components={{ code: <code className='inline' /> }} />
|
||||
</FieldHint>
|
||||
<FieldHint id={`${channelField}-hint-3`}>
|
||||
<Trans i18nKey='Integrations_for_all_channels' />
|
||||
</FieldHint>
|
||||
</Field>
|
||||
)}
|
||||
{showTriggerWords && (
|
||||
<Field>
|
||||
<FieldLabel htmlFor={triggerWordsField}>{t('Trigger_Words')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='triggerWords'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
id={triggerWordsField}
|
||||
{...field}
|
||||
aria-describedby={`${triggerWordsField}-hint-1 ${triggerWordsField}-hint-2`}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${triggerWordsField}-hint-1`}>
|
||||
{t('When_a_line_starts_with_one_of_there_words_post_to_the_URLs_below')}
|
||||
</FieldHint>
|
||||
<FieldHint id={`${triggerWordsField}-hint-2`}>{t('Separate_multiple_words_with_commas')}</FieldHint>
|
||||
</Field>
|
||||
)}
|
||||
{showTargetRoom && (
|
||||
<Field>
|
||||
<FieldLabel htmlFor={targetRoomField}>{t('TargetRoom')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='targetRoom'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextInput id={targetRoomField} {...field} aria-describedby={`${targetRoomField}-hint-1 ${targetRoomField}-hint-2`} />
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${targetRoomField}-hint-1`}>{t('TargetRoom_Description')}</FieldHint>
|
||||
<FieldHint id={`${targetRoomField}-hint-2`}>
|
||||
<Trans i18nKey='Start_with_s_for_user_or_s_for_channel_Eg_s_or_s' components={{ code: <code className='inline' /> }} />
|
||||
</FieldHint>
|
||||
</Field>
|
||||
)}
|
||||
<Field>
|
||||
<FieldLabel htmlFor={urlsField} required>
|
||||
{t('URLs')}
|
||||
</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='urls'
|
||||
control={control}
|
||||
rules={{ required: t('Required_field', { field: t('URLs') }) }}
|
||||
render={({ field }) => (
|
||||
<TextAreaInput
|
||||
id={urlsField}
|
||||
{...field}
|
||||
rows={10}
|
||||
endAddon={<Icon name='permalink' size='x20' />}
|
||||
aria-describedby={`${urlsField}-error`}
|
||||
aria-required={true}
|
||||
aria-invalid={Boolean(errors?.urls)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
{errors?.urls && (
|
||||
<FieldError aria-live='assertive' id={`${urlsField}-error`}>
|
||||
{errors?.urls.message}
|
||||
</FieldError>
|
||||
)}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel htmlFor={impersonateUserField}>{t('Impersonate_user')}</FieldLabel>
|
||||
<Controller
|
||||
name='impersonateUser'
|
||||
control={control}
|
||||
render={({ field: { value, ...field } }) => <ToggleSwitch id={impersonateUserField} {...field} checked={value} />}
|
||||
/>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={usernameField} required>
|
||||
{t('Post_as')}
|
||||
</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='username'
|
||||
control={control}
|
||||
rules={{ required: t('Required_field', { field: t('Post_as') }) }}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
id={usernameField}
|
||||
{...field}
|
||||
endAddon={<Icon name='user' size='x20' />}
|
||||
aria-describedby={`${usernameField}-hint-1 ${usernameField}-hint-2 ${usernameField}-error`}
|
||||
aria-required={true}
|
||||
aria-invalid={Boolean(errors?.username)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${usernameField}-hint-1`}>{t('Choose_the_username_that_this_integration_will_post_as')}</FieldHint>
|
||||
<FieldHint id={`${usernameField}-hint-2`}>{t('Should_exists_a_user_with_this_username')}</FieldHint>
|
||||
{errors?.username && (
|
||||
<FieldError aria-live='assertive' id={`${usernameField}-error`}>
|
||||
{errors?.username.message}
|
||||
</FieldError>
|
||||
)}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={aliasField}>{t('Alias')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='alias'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
id={aliasField}
|
||||
{...field}
|
||||
endAddon={<Icon name='edit' size='x20' />}
|
||||
aria-describedby={`${aliasField}-hint`}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${aliasField}-hint`}>{t('Choose_the_alias_that_will_appear_before_the_username_in_messages')}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={avatarField}>{t('Avatar_URL')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='avatar'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
id={avatarField}
|
||||
{...field}
|
||||
endAddon={
|
||||
<Icon
|
||||
name='user-rounded'
|
||||
size='x20'
|
||||
alignSelf='center'
|
||||
aria-describedby={`${avatarField}-hint-1 ${avatarField}-hint-2`}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${avatarField}-hint-1`}>{t('You_can_change_a_different_avatar_too')}</FieldHint>
|
||||
<FieldHint id={`${avatarField}-hint-2`}>{t('Should_be_a_URL_of_an_image')}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={emojiField}>{t('Emoji')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='emoji'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
id={emojiField}
|
||||
{...field}
|
||||
endAddon={
|
||||
<Icon name='emoji' size='x20' alignSelf='center' aria-describedby={`${emojiField}-hint-1 ${emojiField}-hint-2`} />
|
||||
}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${emojiField}-hint-1`}>{t('You_can_use_an_emoji_as_avatar')}</FieldHint>
|
||||
<FieldHint id={`${emojiField}-hint-2`}>
|
||||
<Trans i18nKey='Example_s' values={{ value: ':ghost:' }} components={{ code: <code className='inline' /> }} />
|
||||
</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={tokenField} required>
|
||||
{t('Token')}
|
||||
</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='token'
|
||||
control={control}
|
||||
rules={{ required: t('Required_field', { field: t('Token') }) }}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
id={tokenField}
|
||||
{...field}
|
||||
endAddon={<Icon name='key' size='x20' />}
|
||||
aria-describedby={`${tokenField}-error`}
|
||||
aria-invalid={Boolean(errors?.token)}
|
||||
aria-required={true}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
{errors?.token && (
|
||||
<FieldError aria-live='assertive' id={`${tokenField}-error`}>
|
||||
{errors?.token.message}
|
||||
</FieldError>
|
||||
)}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel htmlFor={scriptEnabledField}>{t('Script_Enabled')}</FieldLabel>
|
||||
<Controller
|
||||
name='scriptEnabled'
|
||||
control={control}
|
||||
render={({ field: { value, ...field } }) => <ToggleSwitch id={scriptEnabledField} {...field} checked={value} />}
|
||||
/>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={scriptEngineField}>{t('Script_Engine')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='scriptEngine'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
id={scriptEngineField}
|
||||
{...field}
|
||||
options={scriptEngineOptions}
|
||||
aria-describedby={`${scriptEngineField}-hint`}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${scriptEngineField}-hint`}>{t('Script_Engine_Description')}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={scriptField}>{t('Script')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='script'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextAreaInput id={scriptField} rows={10} {...field} endAddon={<Icon name='code' size='x20' alignSelf='center' />} />
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t('Responding')}</FieldLabel>
|
||||
<FieldHint>{t('Response_description_pre')}</FieldHint>
|
||||
<FieldRow>
|
||||
<Box fontScale='p2' withRichContent flexGrow={1}>
|
||||
<pre>
|
||||
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(hilightedExampleJson) }}></code>
|
||||
</pre>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
<FieldHint>{t('Response_description_post')}</FieldHint>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</AccordionItem>
|
||||
<AccordionItem title={t('Integration_Advanced_Settings')}>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel htmlFor={retryFailedCallsField}>{t('Integration_Retry_Failed_Url_Calls')}</FieldLabel>
|
||||
<Controller
|
||||
name='retryFailedCalls'
|
||||
control={control}
|
||||
render={({ field: { value, ...field } }) => (
|
||||
<ToggleSwitch
|
||||
id={retryFailedCallsField}
|
||||
{...field}
|
||||
checked={value}
|
||||
aria-describedby={`${retryFailedCallsField}-hint`}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${retryFailedCallsField}-hint`}>{t('Integration_Retry_Failed_Url_Calls_Description')}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={retryCountField}>{t('Retry_Count')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='retryCount'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<NumberInput {...field} id={retryCountField} min='0' step='1' aria-describedby={`${retryCountField}-hint`} />
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${retryCountField}-hint`}>{t('Integration_Retry_Count_Description')}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor={retryDelayField}>{t('Integration_Retry_Delay')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='retryDelay'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<Select id={retryDelayField} {...field} options={retryDelayOptions} aria-describedby={`${retryDelayField}-hint`} />
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${retryDelayField}-hint`}>
|
||||
<Trans i18nKey='Integration_Retry_Delay_Description' components={{ code: <code className='inline' /> }} />
|
||||
</FieldHint>
|
||||
</Field>
|
||||
{event === 'sendMessage' && (
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel htmlFor={triggerWordAnywhereField}>{t('Integration_Word_Trigger_Placement')}</FieldLabel>
|
||||
<Controller
|
||||
name='triggerWordAnywhere'
|
||||
control={control}
|
||||
render={({ field: { value, ...field } }) => (
|
||||
<ToggleSwitch
|
||||
id={triggerWordAnywhereField}
|
||||
{...field}
|
||||
checked={value}
|
||||
aria-describedby={`${triggerWordAnywhereField}-hint`}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${triggerWordAnywhereField}-hint`}>{t('Integration_Word_Trigger_Placement_Description')}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel htmlFor={runOnEditsField}>{t('Integration_Run_When_Message_Is_Edited')}</FieldLabel>
|
||||
<Controller
|
||||
name='runOnEdits'
|
||||
control={control}
|
||||
render={({ field: { value, ...field } }) => (
|
||||
<ToggleSwitch id={runOnEditsField} {...field} checked={value} aria-describedby={`${runOnEditsField}-hint`} />
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint id={`${runOnEditsField}-hint`}>{t('Integration_Run_When_Message_Is_Edited_Description')}</FieldHint>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
)}
|
||||
</FieldGroup>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default OutgoingWebhookForm;
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { IIntegrationHistory, Serialized } from '@rocket.chat/core-typings';
|
||||
import { Skeleton, Box, Accordion } from '@rocket.chat/fuselage';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import HistoryItem from './HistoryItem';
|
||||
|
||||
export type HistoryContentProps = { data: Serialized<IIntegrationHistory>[]; isLoading: boolean };
|
||||
|
||||
const HistoryContent = ({ data, isLoading }: HistoryContentProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Box width='full' paddingBlock={24}>
|
||||
<Skeleton marginBlockEnd={4} />
|
||||
<Skeleton marginBlockEnd={8} />
|
||||
<Skeleton marginBlockEnd={4} />
|
||||
<Skeleton marginBlockEnd={8} />
|
||||
<Skeleton marginBlockEnd={4} />
|
||||
<Skeleton marginBlockEnd={8} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (data.length < 1) {
|
||||
return <Box marginBlockStart={16}>{t('Integration_Outgoing_WebHook_No_History')}</Box>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box display='flex' alignItems='center' flexDirection='column'>
|
||||
<Accordion width='full' maxWidth='x600' alignSelf='center' key='content'>
|
||||
{data.map((current) => (
|
||||
<HistoryItem data={current} key={current._id} />
|
||||
))}
|
||||
</Accordion>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default HistoryContent;
|
||||
@@ -0,0 +1,210 @@
|
||||
import type { IIntegrationHistory, Serialized } from '@rocket.chat/core-typings';
|
||||
import { Button, Icon, Box, AccordionItem, Field, FieldGroup, FieldLabel, FieldRow } from '@rocket.chat/fuselage';
|
||||
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
|
||||
import { useEndpoint } from '@rocket.chat/ui-contexts';
|
||||
import DOMPurify from 'dompurify';
|
||||
import type { MouseEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { outgoingEvents } from '../../../../../../app/integrations/lib/outgoingEvents';
|
||||
import { useFormatDateAndTime } from '../../../../../hooks/useFormatDateAndTime';
|
||||
import { useHighlightedCode } from '../../../../../hooks/useHighlightedCode';
|
||||
|
||||
export type HistoryItemProps = { data: Serialized<IIntegrationHistory> };
|
||||
|
||||
const HistoryItem = ({ data }: HistoryItemProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const replayOutgoingIntegration = useEndpoint('POST', '/v1/integrations.replayOutgoing');
|
||||
|
||||
const {
|
||||
_id,
|
||||
_createdAt,
|
||||
_updatedAt,
|
||||
httpResult,
|
||||
event,
|
||||
step,
|
||||
httpCallData,
|
||||
data: dataSentToTrigger,
|
||||
prepareSentMessage,
|
||||
processSentMessage,
|
||||
url,
|
||||
httpError,
|
||||
errorStack,
|
||||
error,
|
||||
integration: { _id: integrationId },
|
||||
} = data;
|
||||
|
||||
const createdAt = typeof _createdAt === 'string' ? _createdAt : (_createdAt as Date).toISOString();
|
||||
const updatedAt = typeof _updatedAt === 'string' ? _updatedAt : (_updatedAt as Date).toISOString();
|
||||
|
||||
const handleClickReplay = useStableCallback((e: MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
replayOutgoingIntegration({ integrationId, historyId: _id });
|
||||
});
|
||||
|
||||
const formatDateAndTime = useFormatDateAndTime();
|
||||
|
||||
const dataSentToTriggerCode = useHighlightedCode('json', JSON.stringify(dataSentToTrigger || '', null, 2));
|
||||
const prepareSentMessageCode = useHighlightedCode('json', JSON.stringify(prepareSentMessage || '', null, 2));
|
||||
const processSentMessageCode = useHighlightedCode('json', JSON.stringify(processSentMessage || '', null, 2));
|
||||
const httpCallDataCode = useHighlightedCode('json', JSON.stringify(httpCallData || '', null, 2));
|
||||
const httpErrorCode = useHighlightedCode('json', JSON.stringify(httpError || '', null, 2));
|
||||
const httpResultCode = useHighlightedCode('json', JSON.stringify(httpResult || '', null, 2));
|
||||
const errorStackCode = useHighlightedCode('json', JSON.stringify(errorStack || '', null, 2));
|
||||
|
||||
return (
|
||||
<AccordionItem
|
||||
title={
|
||||
<Box display='inline-flex' width='full' flexDirection='row' justifyContent='space-between'>
|
||||
<Box display='flex' flexDirection='row' alignItems='center'>
|
||||
<Icon name='info-circled' size='x16' marginInlineEnd={4} />
|
||||
{formatDateAndTime(_createdAt)}
|
||||
</Box>
|
||||
<Button secondary onClick={handleClickReplay}>
|
||||
{t('Replay')}
|
||||
</Button>
|
||||
</Box>
|
||||
}
|
||||
>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel>{t('Status')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Box withRichContent width='full'>
|
||||
<code>{error ? t('Failure') : t('Success')}</code>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Time_Triggered')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Box withRichContent width='full'>
|
||||
<code>{createdAt}</code>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Time_Ended_Or_Error')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Box withRichContent width='full'>
|
||||
<code>{updatedAt}</code>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t('Event_Trigger')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Box withRichContent width='full'>
|
||||
<code>{t(outgoingEvents[event].label)}</code>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Trigger_Step')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Box withRichContent width='full'>
|
||||
<code>{step}</code>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
{dataSentToTrigger && (
|
||||
<Field>
|
||||
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Data_Passed_To_Trigger')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Box withRichContent width='full'>
|
||||
<pre>
|
||||
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(dataSentToTriggerCode) }}></code>
|
||||
</pre>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
)}
|
||||
{prepareSentMessage && (
|
||||
<Field>
|
||||
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Messages_Sent_From_Prepare_Script')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Box withRichContent width='full'>
|
||||
<pre>
|
||||
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(prepareSentMessageCode) }}></code>
|
||||
</pre>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
)}
|
||||
{processSentMessage && (
|
||||
<Field>
|
||||
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Messages_Sent_From_Process_Script')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Box withRichContent width='full'>
|
||||
<pre>
|
||||
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(processSentMessageCode) }}></code>
|
||||
</pre>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
)}
|
||||
{url && (
|
||||
<Field>
|
||||
<FieldLabel>{t('URL')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Box withRichContent width='full'>
|
||||
<code>{url}</code>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
)}
|
||||
{httpCallData && (
|
||||
<Field>
|
||||
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Data_Passed_To_URL')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Box withRichContent width='full'>
|
||||
<pre>
|
||||
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(httpCallDataCode) }}></code>
|
||||
</pre>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
)}
|
||||
{httpError && (
|
||||
<Field>
|
||||
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Http_Response_Error')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Box withRichContent width='full'>
|
||||
<pre>
|
||||
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(httpErrorCode) }}></code>
|
||||
</pre>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
)}
|
||||
{httpResult && (
|
||||
<Field>
|
||||
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Http_Response')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Box withRichContent width='full'>
|
||||
<pre>
|
||||
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(httpResultCode) }}></code>
|
||||
</pre>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
)}
|
||||
{errorStack && (
|
||||
<Field>
|
||||
<FieldLabel>{t('Integration_Outgoing_WebHook_History_Error_Stacktrace')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Box withRichContent width='full'>
|
||||
<pre>
|
||||
<code dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(errorStackCode) }}></code>
|
||||
</pre>
|
||||
</Box>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
)}
|
||||
</FieldGroup>
|
||||
</AccordionItem>
|
||||
);
|
||||
};
|
||||
|
||||
export default HistoryItem;
|
||||
@@ -0,0 +1,133 @@
|
||||
import { Button, ButtonGroup, Pagination } from '@rocket.chat/fuselage';
|
||||
import { CustomScrollbars, usePagination, Page, PageHeader, PageContent } from '@rocket.chat/ui-client';
|
||||
import { useToastMessageDispatch, useRouteParameter, useTranslation, useEndpoint, useRouter } from '@rocket.chat/ui-contexts';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { useMemo, useState, useEffect } from 'react';
|
||||
|
||||
import HistoryContent from './HistoryContent';
|
||||
import { sdk } from '../../../../../lib/SDKClient';
|
||||
|
||||
const OutgoingWebhookHistoryPage = (props: ComponentProps<typeof Page>) => {
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
const t = useTranslation();
|
||||
const router = useRouter();
|
||||
|
||||
const { itemsPerPage, setItemsPerPage, current, setCurrent, itemsPerPageLabel, showingResultsLabel } = usePagination();
|
||||
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
const clearIntegrationHistory = useEndpoint('POST', '/v1/integrations.clearHistory');
|
||||
|
||||
const id = useRouteParameter('id') as string;
|
||||
|
||||
const query = useMemo(
|
||||
() => ({
|
||||
id,
|
||||
count: itemsPerPage,
|
||||
offset: current,
|
||||
}),
|
||||
[id, itemsPerPage, current],
|
||||
);
|
||||
|
||||
const fetchHistory = useEndpoint('GET', '/v1/integrations.history');
|
||||
|
||||
const queryKey = useMemo(() => ['integrations/history', id, itemsPerPage, current], [id, itemsPerPage, current]);
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
type HistoryData = Awaited<ReturnType<typeof fetchHistory>>;
|
||||
|
||||
const { data, isPending, refetch } = useQuery({
|
||||
queryKey,
|
||||
queryFn: async () => {
|
||||
const result = fetchHistory(query);
|
||||
setMounted(true);
|
||||
return result;
|
||||
},
|
||||
gcTime: 99999,
|
||||
staleTime: 99999,
|
||||
});
|
||||
|
||||
const handleClearHistory = async (): Promise<void> => {
|
||||
try {
|
||||
await clearIntegrationHistory({ integrationId: id });
|
||||
dispatchToastMessage({ type: 'success', message: t('Integration_History_Cleared') });
|
||||
refetch();
|
||||
setMounted(false);
|
||||
} catch (e) {
|
||||
dispatchToastMessage({ type: 'error', message: e });
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (mounted) {
|
||||
return sdk.stream('integrationHistory', [id], (integration) => {
|
||||
if (integration.type === 'inserted') {
|
||||
setTotal((total) => total + 1);
|
||||
queryClient.setQueryData<HistoryData>(queryKey, (oldData): HistoryData | undefined => {
|
||||
if (!oldData || !integration.data) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
...oldData,
|
||||
history: [integration.data as unknown as HistoryData['history'][number]].concat(oldData.history),
|
||||
total: oldData.total + 1,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
if (integration.type === 'updated') {
|
||||
queryClient.setQueryData<HistoryData>(queryKey, (oldData): HistoryData | undefined => {
|
||||
if (!oldData) {
|
||||
return;
|
||||
}
|
||||
const index = oldData.history.findIndex(({ _id }) => _id === id);
|
||||
if (index === -1) {
|
||||
return;
|
||||
}
|
||||
Object.assign(oldData.history[index], integration.diff);
|
||||
return { ...oldData };
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (integration.type === 'removed') {
|
||||
refetch();
|
||||
}
|
||||
}).stop;
|
||||
}
|
||||
}, [id, mounted, queryClient, queryKey, refetch]);
|
||||
|
||||
return (
|
||||
<Page flexDirection='column' {...props}>
|
||||
<PageHeader
|
||||
title={t('Integration_Outgoing_WebHook_History')}
|
||||
onClickBack={() => router.navigate(`/admin/integrations/edit/outgoing/${id}`)}
|
||||
>
|
||||
<ButtonGroup>
|
||||
<Button icon='trash' danger onClick={handleClearHistory} disabled={total === 0}>
|
||||
{t('clear_history')}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</PageHeader>
|
||||
<PageContent>
|
||||
<CustomScrollbars>
|
||||
<HistoryContent key='historyContent' data={data?.history || []} isLoading={isPending} />
|
||||
</CustomScrollbars>
|
||||
<Pagination
|
||||
current={current}
|
||||
itemsPerPage={itemsPerPage}
|
||||
itemsPerPageLabel={itemsPerPageLabel}
|
||||
showingResultsLabel={showingResultsLabel}
|
||||
count={data?.total || 0}
|
||||
onSetItemsPerPage={setItemsPerPage}
|
||||
onSetCurrent={setCurrent}
|
||||
/>
|
||||
</PageContent>
|
||||
</Page>
|
||||
);
|
||||
};
|
||||
|
||||
export default OutgoingWebhookHistoryPage;
|
||||
Reference in New Issue
Block a user