mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-23 08:40:42 +00:00
Compare commits
4 Commits
docs/css-m
...
feat/notif
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc2d6a9b7b | ||
|
|
b8c35ac2c9 | ||
|
|
d308206291 | ||
|
|
1b90a39d20 |
@@ -2,7 +2,6 @@ import { ReactNode } from 'react';
|
||||
import { Button, Tooltip } from 'antd';
|
||||
import classNames from 'classnames';
|
||||
import { Activity, ChartLine } from '@signozhq/icons';
|
||||
import { useChannelOptions } from 'hooks/notificationChannels/useChannelOptions';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
|
||||
import { useCreateAlertState } from '../context';
|
||||
@@ -26,13 +25,6 @@ function AlertCondition(): JSX.Element {
|
||||
const { alertType, setAlertType } = useCreateAlertState();
|
||||
useAnomalyFunctionSync();
|
||||
|
||||
const {
|
||||
data: channels,
|
||||
isLoading: isLoadingChannels,
|
||||
isError: isErrorChannels,
|
||||
refetch: refreshChannels,
|
||||
} = useChannelOptions();
|
||||
|
||||
const isAnomalyDetectionEnabled = useIsAnomalyDetectionAvailable();
|
||||
|
||||
// Anomaly rules stay editable even without a cloud or enterprise license.
|
||||
@@ -111,22 +103,8 @@ function AlertCondition(): JSX.Element {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{alertType !== AlertTypes.ANOMALY_BASED_ALERT && (
|
||||
<AlertThreshold
|
||||
channels={channels}
|
||||
isLoadingChannels={isLoadingChannels}
|
||||
isErrorChannels={isErrorChannels}
|
||||
refreshChannels={refreshChannels}
|
||||
/>
|
||||
)}
|
||||
{alertType === AlertTypes.ANOMALY_BASED_ALERT && (
|
||||
<AnomalyThreshold
|
||||
channels={channels}
|
||||
isLoadingChannels={isLoadingChannels}
|
||||
isErrorChannels={isErrorChannels}
|
||||
refreshChannels={refreshChannels}
|
||||
/>
|
||||
)}
|
||||
{alertType !== AlertTypes.ANOMALY_BASED_ALERT && <AlertThreshold />}
|
||||
{alertType === AlertTypes.ANOMALY_BASED_ALERT && <AnomalyThreshold />}
|
||||
<div className="condensed-advanced-options-container">
|
||||
<AdvancedOptions />
|
||||
</div>
|
||||
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
import EvaluationSettings from '../EvaluationSettings/EvaluationSettings';
|
||||
import { normalizeMatchType, normalizeOperator } from '../utils';
|
||||
import ThresholdItem from './ThresholdItem';
|
||||
import { AnomalyAndThresholdProps } from './types';
|
||||
import { useThresholdList } from './useThresholdList';
|
||||
import {
|
||||
getCategoryByOptionId,
|
||||
@@ -32,12 +31,7 @@ import {
|
||||
import './styles.scss';
|
||||
import '../EvaluationSettings/styles.scss';
|
||||
|
||||
function AlertThreshold({
|
||||
channels,
|
||||
isLoadingChannels,
|
||||
isErrorChannels,
|
||||
refreshChannels,
|
||||
}: AnomalyAndThresholdProps): JSX.Element {
|
||||
function AlertThreshold(): JSX.Element {
|
||||
const {
|
||||
alertState,
|
||||
thresholdState,
|
||||
@@ -248,11 +242,7 @@ function AlertThreshold({
|
||||
updateThreshold={updateThreshold}
|
||||
removeThreshold={removeThreshold}
|
||||
showRemoveButton={index !== 0 && thresholdState.thresholds.length > 1}
|
||||
channels={channels}
|
||||
isLoadingChannels={isLoadingChannels}
|
||||
units={categorySelectOptions}
|
||||
isErrorChannels={isErrorChannels}
|
||||
refreshChannels={refreshChannels}
|
||||
/>
|
||||
))}
|
||||
<Button
|
||||
|
||||
@@ -19,18 +19,12 @@ import {
|
||||
import EvaluationSettings from '../EvaluationSettings/EvaluationSettings';
|
||||
import { normalizeMatchType, normalizeOperator } from '../utils';
|
||||
import ThresholdItem from './ThresholdItem';
|
||||
import { AnomalyAndThresholdProps } from './types';
|
||||
import { useThresholdList } from './useThresholdList';
|
||||
import { getQueryNames, RoutingPolicyBanner } from './utils';
|
||||
|
||||
import styles from './AnomalyThreshold.module.scss';
|
||||
|
||||
function AnomalyThreshold({
|
||||
channels,
|
||||
isLoadingChannels,
|
||||
isErrorChannels,
|
||||
refreshChannels,
|
||||
}: AnomalyAndThresholdProps): JSX.Element {
|
||||
function AnomalyThreshold(): JSX.Element {
|
||||
const {
|
||||
thresholdState,
|
||||
setThresholdState,
|
||||
@@ -168,11 +162,7 @@ function AnomalyThreshold({
|
||||
updateThreshold={updateThreshold}
|
||||
removeThreshold={removeThreshold}
|
||||
showRemoveButton={index !== 0 && thresholdState.thresholds.length > 1}
|
||||
channels={channels}
|
||||
isLoadingChannels={isLoadingChannels}
|
||||
units={[]}
|
||||
isErrorChannels={isErrorChannels}
|
||||
refreshChannels={refreshChannels}
|
||||
isAnomaly
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -2,7 +2,9 @@ import { useMemo, useState } from 'react';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import { Button, Select, Tooltip } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { Spinner } from '@signozhq/ui/spinner';
|
||||
import { CircleX, Trash } from '@signozhq/icons';
|
||||
import { useChannelSearch } from 'hooks/notificationChannels/useChannelSearch';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
|
||||
import { useCreateAlertState } from '../context';
|
||||
@@ -16,16 +18,21 @@ function ThresholdItem({
|
||||
updateThreshold,
|
||||
removeThreshold,
|
||||
showRemoveButton,
|
||||
channels,
|
||||
units,
|
||||
isErrorChannels,
|
||||
refreshChannels,
|
||||
isLoadingChannels,
|
||||
isAnomaly = false,
|
||||
}: ThresholdItemProps): JSX.Element {
|
||||
const { user } = useAppContext();
|
||||
const { thresholdState, notificationSettings } = useCreateAlertState();
|
||||
const [showRecoveryThreshold, setShowRecoveryThreshold] = useState(false);
|
||||
const {
|
||||
options: channelOptions,
|
||||
searchTerm: channelSearchTerm,
|
||||
setSearchTerm: setChannelSearchTerm,
|
||||
isSearching: isSearchingChannels,
|
||||
isError: isErrorChannels,
|
||||
refetch: refreshChannels,
|
||||
loadMoreOnScroll: loadMoreChannelsOnScroll,
|
||||
} = useChannelSearch();
|
||||
|
||||
const yAxisUnitSelect = useMemo(() => {
|
||||
let component = (
|
||||
@@ -140,29 +147,38 @@ function ThresholdItem({
|
||||
}
|
||||
data-testid="threshold-notification-channel-select"
|
||||
style={{ width: 350 }}
|
||||
options={channels.map((channel) => ({
|
||||
value: channel.name,
|
||||
label: channel.name,
|
||||
options={channelOptions.map((option) => ({
|
||||
...option,
|
||||
'data-testid': `threshold-notification-channel-option-${threshold.label}`,
|
||||
}))}
|
||||
mode="multiple"
|
||||
placeholder="Select notification channels"
|
||||
showSearch
|
||||
searchValue={channelSearchTerm}
|
||||
onSearch={setChannelSearchTerm}
|
||||
onSelect={(): void => setChannelSearchTerm('')}
|
||||
onDropdownVisibleChange={(open): void => {
|
||||
if (!open) {
|
||||
setChannelSearchTerm('');
|
||||
}
|
||||
}}
|
||||
onPopupScroll={loadMoreChannelsOnScroll}
|
||||
filterOption={false}
|
||||
maxTagCount={2}
|
||||
maxTagPlaceholder={(omittedValues): string =>
|
||||
`+${omittedValues.length} more`
|
||||
}
|
||||
maxTagTextLength={10}
|
||||
filterOption={(input, option): boolean =>
|
||||
option?.label?.toLowerCase().includes(input.toLowerCase()) || false
|
||||
}
|
||||
status={isErrorChannels ? 'error' : undefined}
|
||||
disabled={isLoadingChannels}
|
||||
notFoundContent={
|
||||
<NotificationChannelsNotFoundContent
|
||||
user={user}
|
||||
refreshChannels={refreshChannels}
|
||||
/>
|
||||
isSearchingChannels ? (
|
||||
<Spinner testId="threshold-notification-channel-spinner" />
|
||||
) : (
|
||||
<NotificationChannelsNotFoundContent
|
||||
user={user}
|
||||
refreshChannels={refreshChannels}
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</>
|
||||
|
||||
@@ -2,7 +2,6 @@ import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { TestRouter } from 'tests/router';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
|
||||
import { CreateAlertProvider } from '../../context';
|
||||
import {
|
||||
@@ -11,17 +10,6 @@ import {
|
||||
} from '../../context/constants';
|
||||
import AlertThreshold from '../AlertThreshold';
|
||||
|
||||
const mockChannels: ChannelOption[] = [];
|
||||
const mockRefreshChannels = jest.fn();
|
||||
const mockIsLoadingChannels = false;
|
||||
const mockIsErrorChannels = false;
|
||||
const mockProps = {
|
||||
channels: mockChannels,
|
||||
isLoadingChannels: mockIsLoadingChannels,
|
||||
isErrorChannels: mockIsErrorChannels,
|
||||
refreshChannels: mockRefreshChannels,
|
||||
};
|
||||
|
||||
jest.mock('uplot', () => {
|
||||
const paths = {
|
||||
spline: jest.fn(),
|
||||
@@ -88,20 +76,6 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock getAllChannels API
|
||||
jest.mock('hooks/notificationChannels/useChannelOptions', () => ({
|
||||
__esModule: true,
|
||||
useChannelOptions: jest.fn(() => ({
|
||||
data: [
|
||||
{ id: '1', name: 'Email Channel' },
|
||||
{ id: '2', name: 'Slack Channel' },
|
||||
] as ChannelOption[],
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
refetch: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
// Mock alert format categories
|
||||
jest.mock('constants/formats/alertFormatCategories', () => ({
|
||||
getCategoryByOptionId: jest.fn(() => ({ name: 'bytes' })),
|
||||
@@ -136,7 +110,7 @@ const renderAlertThreshold = (): ReturnType<typeof render> => {
|
||||
<TestRouter>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<CreateAlertProvider initialAlertType={AlertTypes.METRICS_BASED_ALERT}>
|
||||
<AlertThreshold {...mockProps} />
|
||||
<AlertThreshold />
|
||||
</CreateAlertProvider>
|
||||
</QueryClientProvider>
|
||||
</TestRouter>,
|
||||
@@ -278,13 +252,6 @@ describe('AlertThreshold', () => {
|
||||
expect(thresholdItems).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('handles loading state for channels', () => {
|
||||
renderAlertThreshold();
|
||||
|
||||
// Component should render even while channels are loading
|
||||
expect(screen.getByText('Send a notification when')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders with correct initial state', () => {
|
||||
renderAlertThreshold();
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { createMockAlertContextState } from 'container/CreateAlertV2/EvaluationSettings/__tests__/testUtils';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
|
||||
import * as context from '../../context';
|
||||
import { AlertThresholdMatchType } from '../../context/types';
|
||||
@@ -49,17 +48,8 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
const channels: ChannelOption[] = [{ id: '1', name: 'slack-alerts' }];
|
||||
|
||||
const renderAnomalyThreshold = (): ReturnType<typeof render> =>
|
||||
render(
|
||||
<AnomalyThreshold
|
||||
channels={channels}
|
||||
isLoadingChannels={false}
|
||||
isErrorChannels={false}
|
||||
refreshChannels={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
render(<AnomalyThreshold />);
|
||||
|
||||
describe('AnomalyThreshold', () => {
|
||||
beforeEach(() => {
|
||||
@@ -144,10 +134,10 @@ describe('AnomalyThreshold', () => {
|
||||
|
||||
it('picks channels by name when routing policies are off', async () => {
|
||||
renderAnomalyThreshold();
|
||||
await pickOption('threshold-notification-channel-select', 'slack-alerts');
|
||||
await pickOption('threshold-notification-channel-select', 'Dummy-Channel');
|
||||
expect(mockSetThresholdState).toHaveBeenCalledWith({
|
||||
type: 'SET_THRESHOLDS',
|
||||
payload: [expect.objectContaining({ channels: ['slack-alerts'] })],
|
||||
payload: [expect.objectContaining({ channels: ['Dummy-Channel'] })],
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { DefaultOptionType } from 'antd/es/select';
|
||||
import { createMockAlertContextState } from 'container/CreateAlertV2/EvaluationSettings/__tests__/testUtils';
|
||||
import { getAppContextMockState } from 'container/RoutingPolicies/__tests__/testUtils';
|
||||
import { notificationChannelsListResponse } from 'mocks-server/__mockdata__/alerts';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import * as appHooks from 'providers/App/App';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import * as context from '../../context';
|
||||
import ThresholdItem from '../ThresholdItem';
|
||||
@@ -38,9 +46,6 @@ const TEST_CONSTANTS = {
|
||||
WARNING_LABEL: 'WARNING',
|
||||
INFO_LABEL: 'INFO',
|
||||
CHANNEL_1: 'channel-1',
|
||||
CHANNEL_2: 'channel-2',
|
||||
CHANNEL_3: 'channel-3',
|
||||
EMAIL_CHANNEL_NAME: 'Email Channel',
|
||||
EMAIL_CHANNEL_TRUNCATED: 'Email Chan...',
|
||||
ENTER_THRESHOLD_NAME: 'Enter threshold name',
|
||||
ENTER_THRESHOLD_VALUE: 'Enter threshold value',
|
||||
@@ -57,14 +62,8 @@ const mockThreshold = {
|
||||
color: '#ff0000',
|
||||
};
|
||||
|
||||
const mockChannels: ChannelOption[] = [
|
||||
{
|
||||
id: TEST_CONSTANTS.CHANNEL_1,
|
||||
name: TEST_CONSTANTS.EMAIL_CHANNEL_NAME,
|
||||
} as any,
|
||||
{ id: TEST_CONSTANTS.CHANNEL_2, name: 'Slack Channel' } as any,
|
||||
{ id: TEST_CONSTANTS.CHANNEL_3, name: 'PagerDuty Channel' } as any,
|
||||
];
|
||||
const CHANNELS_URL = 'http://localhost/api/v2/notification_channels';
|
||||
const CHANNEL_SELECT = 'threshold-notification-channel-select';
|
||||
|
||||
const mockUnits: DefaultOptionType[] = [
|
||||
{ label: 'Bytes', value: 'bytes' },
|
||||
@@ -77,11 +76,7 @@ const defaultProps: ThresholdItemProps = {
|
||||
updateThreshold: jest.fn(),
|
||||
removeThreshold: jest.fn(),
|
||||
showRemoveButton: false,
|
||||
channels: mockChannels,
|
||||
isLoadingChannels: false,
|
||||
units: mockUnits,
|
||||
isErrorChannels: false,
|
||||
refreshChannels: jest.fn(),
|
||||
};
|
||||
|
||||
const renderThresholdItem = (
|
||||
@@ -106,12 +101,6 @@ const verifySelectorWidth = (
|
||||
// fireEvent.click(recoveryButton);
|
||||
// };
|
||||
|
||||
const verifyComponentRendersWithLoading = (): void => {
|
||||
expect(
|
||||
screen.getByPlaceholderText(TEST_CONSTANTS.ENTER_THRESHOLD_NAME),
|
||||
).toBeInTheDocument();
|
||||
};
|
||||
|
||||
const verifyUnitSelectorDisabled = (): void => {
|
||||
const unitSelectors = screen.getAllByRole('combobox');
|
||||
const unitSelector = unitSelectors[0]; // First combobox is the unit selector
|
||||
@@ -348,9 +337,106 @@ describe('ThresholdItem', () => {
|
||||
verifySelectorWidth(0, '150px');
|
||||
});
|
||||
|
||||
it('handles loading channels state', () => {
|
||||
renderThresholdItem({ isLoadingChannels: true });
|
||||
verifyComponentRendersWithLoading();
|
||||
it('searches channels on the server as the user types', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const requests: Record<string, string>[] = [];
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (req, res, ctx) => {
|
||||
requests.push(Object.fromEntries(req.url.searchParams));
|
||||
return res(
|
||||
ctx.json(
|
||||
notificationChannelsListResponse(
|
||||
req.url.searchParams.get('query')
|
||||
? ['Oncall PagerDuty']
|
||||
: ['Dummy-Channel', 'Oncall PagerDuty'],
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
renderThresholdItem();
|
||||
|
||||
const input = within(screen.getByTestId(CHANNEL_SELECT)).getByRole(
|
||||
'combobox',
|
||||
);
|
||||
await user.click(input);
|
||||
await screen.findByTitle('Dummy-Channel');
|
||||
await user.type(input, 'pager');
|
||||
|
||||
await expect(
|
||||
screen.findByTitle('Oncall PagerDuty'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.queryByTitle('Dummy-Channel')).not.toBeInTheDocument();
|
||||
expect(requests).toStrictEqual([
|
||||
expect.not.objectContaining({ query: expect.anything() }),
|
||||
expect.objectContaining({ query: 'pager', limit: '100', offset: '0' }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('shows a spinner, not the empty state, while a search is in flight', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (req, res, ctx) =>
|
||||
req.url.searchParams.get('query')
|
||||
? res(ctx.delay(5_000), ctx.json(notificationChannelsListResponse([])))
|
||||
: res(ctx.json(notificationChannelsListResponse([]))),
|
||||
),
|
||||
);
|
||||
renderThresholdItem();
|
||||
|
||||
const input = within(screen.getByTestId(CHANNEL_SELECT)).getByRole(
|
||||
'combobox',
|
||||
);
|
||||
await user.click(input);
|
||||
await expect(
|
||||
screen.findByText('No channels yet.'),
|
||||
).resolves.toBeInTheDocument();
|
||||
await user.type(input, 'pager');
|
||||
|
||||
expect(
|
||||
screen.getByTestId('threshold-notification-channel-spinner'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByText('No channels yet.')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('loads the next page when the list is scrolled to the bottom', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const offsets: string[] = [];
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (req, res, ctx) => {
|
||||
const offset = Number(req.url.searchParams.get('offset'));
|
||||
offsets.push(String(offset));
|
||||
const names = Array.from(
|
||||
{ length: offset === 0 ? 100 : 20 },
|
||||
(_, index) => `channel-${offset + index}`,
|
||||
);
|
||||
return res(ctx.json(notificationChannelsListResponse(names, 120)));
|
||||
}),
|
||||
);
|
||||
renderThresholdItem();
|
||||
|
||||
await user.click(
|
||||
within(screen.getByTestId(CHANNEL_SELECT)).getByRole('combobox'),
|
||||
);
|
||||
await screen.findByTitle('channel-0');
|
||||
fireEvent.scroll(
|
||||
document.querySelector('.rc-virtual-list-holder') as HTMLElement,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(offsets).toStrictEqual(['0', '100']));
|
||||
});
|
||||
|
||||
it('keeps the name of a saved channel the results do not include', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
renderThresholdItem({
|
||||
threshold: { ...mockThreshold, channels: ['old-pager'] },
|
||||
});
|
||||
const select = screen.getByTestId(CHANNEL_SELECT);
|
||||
|
||||
await user.click(within(select).getByRole('combobox'));
|
||||
await screen.findByTitle('Dummy-Channel');
|
||||
|
||||
expect(within(select).getByTitle('old-pager')).toHaveTextContent('old-pager');
|
||||
});
|
||||
|
||||
it.skip('renders recovery threshold with correct initial value', () => {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { DefaultOptionType } from 'antd/es/select';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
|
||||
import {
|
||||
NotificationSettingsAction,
|
||||
@@ -21,11 +20,7 @@ export interface ThresholdItemProps {
|
||||
updateThreshold: UpdateThreshold;
|
||||
removeThreshold: (thresholdId: string) => void;
|
||||
showRemoveButton: boolean;
|
||||
channels: ChannelOption[];
|
||||
isLoadingChannels: boolean;
|
||||
units: DefaultOptionType[];
|
||||
isErrorChannels: boolean;
|
||||
refreshChannels: () => void;
|
||||
isAnomaly?: boolean;
|
||||
}
|
||||
|
||||
@@ -35,13 +30,6 @@ export interface ThresholdList {
|
||||
updateThreshold: UpdateThreshold;
|
||||
}
|
||||
|
||||
export interface AnomalyAndThresholdProps {
|
||||
channels: ChannelOption[];
|
||||
isLoadingChannels: boolean;
|
||||
isErrorChannels: boolean;
|
||||
refreshChannels: () => void;
|
||||
}
|
||||
|
||||
export interface RoutingPolicyBannerProps {
|
||||
notificationSettings: NotificationSettingsState;
|
||||
setNotificationSettings: (
|
||||
|
||||
@@ -6,11 +6,10 @@ import { Switch } from '@signozhq/ui/switch';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { ALERTS_DATA_SOURCE_MAP } from 'constants/alerts';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { useChannelOptions } from 'hooks/notificationChannels/useChannelOptions';
|
||||
import { useChannelSearch } from 'hooks/notificationChannels/useChannelSearch';
|
||||
import { useNotificationChannelCollectionPermissions } from 'hooks/notificationChannels/useNotificationChannelCollectionPermissions';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { AlertDef, Labels } from 'types/api/alerts/def';
|
||||
import APIError from 'types/api/error';
|
||||
import { requireErrorMessage } from 'utils/form/requireErrorMessage';
|
||||
import { openInNewTab } from 'utils/navigation';
|
||||
import { popupContainer } from 'utils/selectPopupContainer';
|
||||
@@ -43,13 +42,7 @@ function BasicInfo({
|
||||
}: BasicInfoProps): JSX.Element {
|
||||
const { t } = useTranslation('alerts');
|
||||
|
||||
const {
|
||||
isLoading,
|
||||
data: channels,
|
||||
error,
|
||||
isError,
|
||||
refetch,
|
||||
} = useChannelOptions();
|
||||
const { isLoading, total: channelCount } = useChannelSearch();
|
||||
|
||||
const { canCreate: addNewChannelPermission } =
|
||||
useNotificationChannelCollectionPermissions();
|
||||
@@ -75,7 +68,7 @@ function BasicInfo({
|
||||
});
|
||||
};
|
||||
|
||||
const noChannels = channels.length === 0;
|
||||
const noChannels = !channelCount;
|
||||
const handleCreateNewChannels = useCallback(() => {
|
||||
logEvent('Alert: Create notification channel button clicked', {
|
||||
dataSource: ALERTS_DATA_SOURCE_MAP[alertDef?.alertType as AlertTypes],
|
||||
@@ -88,19 +81,15 @@ function BasicInfo({
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && isNewRule && !hasLoggedEvent.current) {
|
||||
logEvent('Alert: New alert creation page visited', {
|
||||
void logEvent('Alert: New alert creation page visited', {
|
||||
dataSource: ALERTS_DATA_SOURCE_MAP[alertDef?.alertType as AlertTypes],
|
||||
numberOfChannels: channels.length,
|
||||
numberOfChannels: channelCount ?? 0,
|
||||
});
|
||||
hasLoggedEvent.current = true;
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isLoading]);
|
||||
|
||||
const refetchChannels = async (): Promise<void> => {
|
||||
await refetch();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<StepHeading> {t('alert_form_step4')} </StepHeading>
|
||||
@@ -220,14 +209,9 @@ function BasicInfo({
|
||||
]}
|
||||
>
|
||||
<ChannelSelect
|
||||
onDropdownOpen={refetchChannels}
|
||||
disabled={shouldBroadCastToAllChannels}
|
||||
currentValue={alertDef.preferredChannels}
|
||||
handleCreateNewChannels={handleCreateNewChannels}
|
||||
channels={channels}
|
||||
isLoading={isLoading}
|
||||
hasError={isError}
|
||||
error={error as APIError}
|
||||
onSelectChannels={(preferredChannels): void => {
|
||||
setAlertDef({
|
||||
...alertDef,
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { setupAuthzDenyAll } from 'lib/authz/utils/authz-test-utils';
|
||||
import { notificationChannelsListResponse } from 'mocks-server/__mockdata__/alerts';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import ChannelSelect from '..';
|
||||
|
||||
const CHANNELS_URL = 'http://localhost/api/v2/notification_channels';
|
||||
const CHANNEL_SELECT = 'alert-channel-select';
|
||||
|
||||
const renderChannelSelect = (currentValue: string[] = []): void => {
|
||||
render(
|
||||
<ChannelSelect
|
||||
currentValue={currentValue}
|
||||
onSelectChannels={jest.fn()}
|
||||
handleCreateNewChannels={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
};
|
||||
|
||||
const channelInput = (): HTMLElement =>
|
||||
within(screen.getByTestId(CHANNEL_SELECT)).getByRole('combobox');
|
||||
|
||||
describe('ChannelSelect', () => {
|
||||
beforeEach(() => {
|
||||
server.use(setupAuthzDenyAll());
|
||||
});
|
||||
|
||||
it('searches channels on the server as the user types', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const queries: (string | null)[] = [];
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (req, res, ctx) => {
|
||||
const query = req.url.searchParams.get('query');
|
||||
queries.push(query);
|
||||
return res(
|
||||
ctx.json(
|
||||
notificationChannelsListResponse(
|
||||
query ? ['Oncall PagerDuty'] : ['Dummy-Channel', 'Oncall PagerDuty'],
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
renderChannelSelect();
|
||||
|
||||
await user.click(channelInput());
|
||||
await screen.findByTitle('Dummy-Channel');
|
||||
await user.type(channelInput(), 'pager');
|
||||
|
||||
await waitFor(() => expect(queries).toContain('pager'));
|
||||
await expect(
|
||||
screen.findByTitle('Oncall PagerDuty'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.queryByTitle('Dummy-Channel')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('refetches the channels each time the dropdown opens', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
let requestCount = 0;
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (_req, res, ctx) => {
|
||||
requestCount += 1;
|
||||
return res(ctx.json(notificationChannelsListResponse(['Dummy-Channel'])));
|
||||
}),
|
||||
);
|
||||
renderChannelSelect();
|
||||
await waitFor(() => expect(requestCount).toBe(1));
|
||||
|
||||
await user.click(channelInput());
|
||||
|
||||
await waitFor(() => expect(requestCount).toBe(2));
|
||||
});
|
||||
|
||||
it('loads the next page when the list is scrolled to the bottom', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const offsets: string[] = [];
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (req, res, ctx) => {
|
||||
const offset = Number(req.url.searchParams.get('offset'));
|
||||
offsets.push(String(offset));
|
||||
const names = Array.from(
|
||||
{ length: offset === 0 ? 100 : 20 },
|
||||
(_, index) => `channel-${offset + index}`,
|
||||
);
|
||||
return res(ctx.json(notificationChannelsListResponse(names, 120)));
|
||||
}),
|
||||
);
|
||||
renderChannelSelect();
|
||||
|
||||
await user.click(channelInput());
|
||||
await screen.findByTitle('channel-0');
|
||||
fireEvent.scroll(
|
||||
document.querySelector('.rc-virtual-list-holder') as HTMLElement,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(offsets).toContain('100'));
|
||||
});
|
||||
|
||||
it('keeps the name of a saved channel the results do not include', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (_req, res, ctx) =>
|
||||
res(ctx.json(notificationChannelsListResponse(['Dummy-Channel']))),
|
||||
),
|
||||
);
|
||||
renderChannelSelect(['old-pager']);
|
||||
|
||||
await user.click(channelInput());
|
||||
await screen.findByTitle('Dummy-Channel');
|
||||
|
||||
expect(
|
||||
within(screen.getByTestId(CHANNEL_SELECT)).getByTitle('old-pager'),
|
||||
).toHaveTextContent('old-pager');
|
||||
});
|
||||
});
|
||||
@@ -2,10 +2,10 @@ import { ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus } from '@signozhq/icons';
|
||||
import { Select, Spin } from 'antd';
|
||||
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import { useChannelSearch } from 'hooks/notificationChannels/useChannelSearch';
|
||||
import { useNotificationChannelCollectionPermissions } from 'hooks/notificationChannels/useNotificationChannelCollectionPermissions';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
import { StyledCreateChannelOption, StyledSelect } from './styles';
|
||||
|
||||
@@ -13,11 +13,6 @@ export interface ChannelSelectProps {
|
||||
disabled?: boolean;
|
||||
currentValue?: string[];
|
||||
onSelectChannels: (s: string[]) => void;
|
||||
onDropdownOpen: () => void;
|
||||
isLoading: boolean;
|
||||
channels: ChannelOption[];
|
||||
hasError: boolean;
|
||||
error: APIError;
|
||||
handleCreateNewChannels: () => void;
|
||||
}
|
||||
|
||||
@@ -25,17 +20,22 @@ function ChannelSelect({
|
||||
disabled,
|
||||
currentValue,
|
||||
onSelectChannels,
|
||||
onDropdownOpen,
|
||||
channels,
|
||||
isLoading,
|
||||
hasError,
|
||||
error,
|
||||
handleCreateNewChannels,
|
||||
}: ChannelSelectProps): JSX.Element | null {
|
||||
// init namespace for translations
|
||||
const { t } = useTranslation('alerts');
|
||||
|
||||
const { notifications } = useNotifications();
|
||||
const {
|
||||
options,
|
||||
searchTerm,
|
||||
setSearchTerm,
|
||||
isSearching,
|
||||
isError: hasError,
|
||||
error,
|
||||
refetch,
|
||||
loadMoreOnScroll,
|
||||
} = useChannelSearch();
|
||||
|
||||
const handleChange = (value: string[]): void => {
|
||||
if (value.includes('add-new-channel')) {
|
||||
@@ -46,9 +46,10 @@ function ChannelSelect({
|
||||
};
|
||||
|
||||
if (hasError) {
|
||||
const apiError = convertToApiError(error);
|
||||
notifications.error({
|
||||
message: error?.getErrorCode?.() || 'Error',
|
||||
description: error?.getErrorMessage?.() || 'Something went wrong',
|
||||
message: apiError?.getErrorCode?.() || 'Error',
|
||||
description: apiError?.getErrorMessage?.() || 'Something went wrong',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -58,7 +59,7 @@ function ChannelSelect({
|
||||
const renderOptions = (): ReactNode[] => {
|
||||
const children: ReactNode[] = [];
|
||||
|
||||
if (!isLoading && addNewChannelPermission) {
|
||||
if (!isSearching && addNewChannelPermission) {
|
||||
children.push(
|
||||
<Select.Option key="add-new-channel" value="add-new-channel">
|
||||
<StyledCreateChannelOption>
|
||||
@@ -69,14 +70,10 @@ function ChannelSelect({
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoading || channels.length === 0) {
|
||||
return children;
|
||||
}
|
||||
|
||||
channels.forEach((o) => {
|
||||
options.forEach((o) => {
|
||||
children.push(
|
||||
<Select.Option key={o.id} value={o.name}>
|
||||
{o.name}
|
||||
<Select.Option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</Select.Option>,
|
||||
);
|
||||
});
|
||||
@@ -93,10 +90,17 @@ function ChannelSelect({
|
||||
placeholder={t('placeholder_channel_select')}
|
||||
data-testid="alert-channel-select"
|
||||
value={currentValue}
|
||||
notFoundContent={isLoading && <Spin size="small" />}
|
||||
searchValue={searchTerm}
|
||||
onSearch={setSearchTerm}
|
||||
onSelect={(): void => setSearchTerm('')}
|
||||
filterOption={false}
|
||||
onPopupScroll={loadMoreOnScroll}
|
||||
notFoundContent={isSearching && <Spin size="small" />}
|
||||
onDropdownVisibleChange={(open): void => {
|
||||
if (open) {
|
||||
onDropdownOpen();
|
||||
refetch();
|
||||
} else {
|
||||
setSearchTerm('');
|
||||
}
|
||||
}}
|
||||
onChange={(value): void => {
|
||||
|
||||
@@ -33,11 +33,6 @@ function RoutingPolicies(): JSX.Element {
|
||||
isFetchingRoutingPolicies,
|
||||
isErrorRoutingPolicies,
|
||||
refetchRoutingPolicies,
|
||||
// Channels
|
||||
channels,
|
||||
isLoadingChannels,
|
||||
isErrorChannels,
|
||||
refreshChannels,
|
||||
// Search
|
||||
searchTerm,
|
||||
setSearchTerm,
|
||||
@@ -169,12 +164,8 @@ function RoutingPolicies(): JSX.Element {
|
||||
routingPolicy={selectedRoutingPolicy}
|
||||
closeModal={handlePolicyDetailsModalClose}
|
||||
mode={policyDetailsModalState.mode}
|
||||
channels={channels}
|
||||
isErrorChannels={isErrorChannels}
|
||||
isLoadingChannels={isLoadingChannels}
|
||||
handlePolicyDetailsModalAction={handlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={isPolicyDetailsModalActionLoading}
|
||||
refreshChannels={refreshChannels}
|
||||
/>
|
||||
)}
|
||||
{isDeleteModalOpen && (
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Button, Flex, Form, Input, Modal, Select } from 'antd';
|
||||
import { Spinner } from '@signozhq/ui/spinner';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { ModalTitle } from 'container/PipelinePage/PipelineListsView/styles';
|
||||
import { Check, Loader, X } from '@signozhq/icons';
|
||||
import { useChannelSearch } from 'hooks/notificationChannels/useChannelSearch';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
import { openInNewTab } from 'utils/navigation';
|
||||
@@ -17,16 +19,21 @@ import {
|
||||
function RoutingPolicyDetails({
|
||||
closeModal,
|
||||
mode,
|
||||
channels,
|
||||
isErrorChannels,
|
||||
isLoadingChannels,
|
||||
routingPolicy,
|
||||
handlePolicyDetailsModalAction,
|
||||
isPolicyDetailsModalActionLoading,
|
||||
refreshChannels,
|
||||
}: RoutingPolicyDetailsProps): JSX.Element {
|
||||
const [form] = Form.useForm();
|
||||
const { user } = useAppContext();
|
||||
const {
|
||||
options: channelOptions,
|
||||
searchTerm: channelSearchTerm,
|
||||
setSearchTerm: setChannelSearchTerm,
|
||||
isSearching: isSearchingChannels,
|
||||
isError: isErrorChannels,
|
||||
refetch: refreshChannels,
|
||||
loadMoreOnScroll: loadMoreChannelsOnScroll,
|
||||
} = useChannelSearch();
|
||||
|
||||
const initialFormState = useMemo(() => {
|
||||
if (mode === 'edit') {
|
||||
@@ -163,24 +170,34 @@ function RoutingPolicyDetails({
|
||||
]}
|
||||
>
|
||||
<Select
|
||||
options={channels.map((channel) => ({
|
||||
value: channel.name,
|
||||
label: channel.name,
|
||||
}))}
|
||||
options={channelOptions}
|
||||
mode="multiple"
|
||||
placeholder="Select notification channels"
|
||||
data-testid="routing-policy-channel-select"
|
||||
showSearch
|
||||
searchValue={channelSearchTerm}
|
||||
onSearch={setChannelSearchTerm}
|
||||
onSelect={(): void => setChannelSearchTerm('')}
|
||||
onDropdownVisibleChange={(open): void => {
|
||||
if (!open) {
|
||||
setChannelSearchTerm('');
|
||||
}
|
||||
}}
|
||||
onPopupScroll={loadMoreChannelsOnScroll}
|
||||
filterOption={false}
|
||||
maxTagCount={3}
|
||||
maxTagPlaceholder={(omittedValues): string =>
|
||||
`+${omittedValues.length} more`
|
||||
}
|
||||
maxTagTextLength={10}
|
||||
filterOption={(input, option): boolean =>
|
||||
option?.label?.toLowerCase().includes(input.toLowerCase()) || false
|
||||
}
|
||||
status={isErrorChannels ? 'error' : undefined}
|
||||
disabled={isLoadingChannels}
|
||||
notFoundContent={notificationChannelsNotFoundContent}
|
||||
notFoundContent={
|
||||
isSearchingChannels ? (
|
||||
<Spinner testId="routing-policy-channel-spinner" />
|
||||
) : (
|
||||
notificationChannelsNotFoundContent
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
@@ -1,43 +1,66 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { notificationChannelsListResponse } from 'mocks-server/__mockdata__/alerts';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import * as appHooks from 'providers/App/App';
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import RoutingPolicyDetails from '../RoutingPolicyDetails';
|
||||
import {
|
||||
getAppContextMockState,
|
||||
MOCK_CHANNEL_1,
|
||||
MOCK_CHANNEL_2,
|
||||
MOCK_ROUTING_POLICY_1,
|
||||
} from './testUtils';
|
||||
import { RoutingPolicyDetailsProps } from '../types';
|
||||
import { getAppContextMockState, MOCK_ROUTING_POLICY_1 } from './testUtils';
|
||||
|
||||
jest.spyOn(appHooks, 'useAppContext').mockReturnValue(getAppContextMockState());
|
||||
|
||||
const mockHandlePolicyDetailsModalAction = jest.fn();
|
||||
const mockCloseModal = jest.fn();
|
||||
const mockChannels = [MOCK_CHANNEL_1, MOCK_CHANNEL_2];
|
||||
const mockRoutingPolicy = MOCK_ROUTING_POLICY_1;
|
||||
const mockRefreshChannels = jest.fn();
|
||||
|
||||
const CHANNELS_URL = 'http://localhost/api/v2/notification_channels';
|
||||
const CHANNEL_SELECT = 'routing-policy-channel-select';
|
||||
const CHANNEL_NAMES = ['Channel 1', 'Channel 2'];
|
||||
const NEW_NAME = 'New Name';
|
||||
const NEW_EXPRESSION = 'New Expression';
|
||||
const NEW_DESCRIPTION = 'New Description';
|
||||
const SAVE_BUTTON_TEXT = 'Save Routing Policy';
|
||||
const NO_CHANNELS_FOUND_TEXT = 'No channels yet.';
|
||||
|
||||
const serveChannels = (names: string[]): void => {
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (_req, res, ctx) =>
|
||||
res(ctx.json(notificationChannelsListResponse(names))),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const renderRoutingPolicyDetails = (
|
||||
props: Partial<RoutingPolicyDetailsProps> = {},
|
||||
): ReturnType<typeof render> =>
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="create"
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={false}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
|
||||
const channelInput = (): HTMLElement =>
|
||||
within(screen.getByTestId(CHANNEL_SELECT)).getByRole('combobox');
|
||||
|
||||
describe('RoutingPolicyDetails', () => {
|
||||
beforeEach(() => {
|
||||
serveChannels(CHANNEL_NAMES);
|
||||
});
|
||||
|
||||
it('renders base create layout with header, 3 inputs and footer', () => {
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="create"
|
||||
channels={mockChannels}
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={false}
|
||||
isErrorChannels={false}
|
||||
isLoadingChannels={false}
|
||||
refreshChannels={mockRefreshChannels}
|
||||
/>,
|
||||
);
|
||||
renderRoutingPolicyDetails();
|
||||
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
expect(screen.getByText('Create routing policy')).toBeInTheDocument();
|
||||
@@ -51,19 +74,7 @@ describe('RoutingPolicyDetails', () => {
|
||||
});
|
||||
|
||||
it('renders base edit layout with header, 3 inputs and footer', () => {
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="edit"
|
||||
channels={mockChannels}
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={false}
|
||||
isErrorChannels={false}
|
||||
isLoadingChannels={false}
|
||||
refreshChannels={mockRefreshChannels}
|
||||
/>,
|
||||
);
|
||||
renderRoutingPolicyDetails({ mode: 'edit' });
|
||||
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
expect(screen.getByText('Edit routing policy')).toBeInTheDocument();
|
||||
@@ -78,19 +89,7 @@ describe('RoutingPolicyDetails', () => {
|
||||
});
|
||||
|
||||
it('prefills inputs with existing policy values in edit mode', () => {
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="edit"
|
||||
channels={mockChannels}
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={false}
|
||||
isErrorChannels={false}
|
||||
isLoadingChannels={false}
|
||||
refreshChannels={mockRefreshChannels}
|
||||
/>,
|
||||
);
|
||||
renderRoutingPolicyDetails({ mode: 'edit' });
|
||||
|
||||
const nameInput = screen.getByDisplayValue(mockRoutingPolicy.name);
|
||||
expect(nameInput).toBeInTheDocument();
|
||||
@@ -100,23 +99,11 @@ describe('RoutingPolicyDetails', () => {
|
||||
);
|
||||
expect(expressionTextarea).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByText(MOCK_CHANNEL_1.name)).toBeInTheDocument();
|
||||
expect(screen.getByText(CHANNEL_NAMES[0])).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('creating and saving the routing policy works correctly', async () => {
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="create"
|
||||
channels={mockChannels}
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={false}
|
||||
isErrorChannels={false}
|
||||
isLoadingChannels={false}
|
||||
refreshChannels={mockRefreshChannels}
|
||||
/>,
|
||||
);
|
||||
renderRoutingPolicyDetails();
|
||||
|
||||
const nameInput = screen.getByPlaceholderText('e.g. Base routing policy...');
|
||||
expect(nameInput).toBeInTheDocument();
|
||||
@@ -135,8 +122,7 @@ describe('RoutingPolicyDetails', () => {
|
||||
fireEvent.change(expressionTextarea, { target: { value: NEW_EXPRESSION } });
|
||||
fireEvent.change(descriptionTextarea, { target: { value: NEW_DESCRIPTION } });
|
||||
|
||||
const channelSelect = screen.getByRole('combobox');
|
||||
fireEvent.mouseDown(channelSelect);
|
||||
fireEvent.mouseDown(channelInput());
|
||||
const channelOptions = await screen.findAllByText('Channel 1');
|
||||
fireEvent.click(channelOptions[1]);
|
||||
|
||||
@@ -164,19 +150,7 @@ describe('RoutingPolicyDetails', () => {
|
||||
});
|
||||
|
||||
it('editing and saving the routing policy works correctly', async () => {
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="edit"
|
||||
channels={mockChannels}
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={false}
|
||||
isErrorChannels={false}
|
||||
isLoadingChannels={false}
|
||||
refreshChannels={mockRefreshChannels}
|
||||
/>,
|
||||
);
|
||||
renderRoutingPolicyDetails({ mode: 'edit' });
|
||||
|
||||
const nameInput = screen.getByDisplayValue(mockRoutingPolicy.name);
|
||||
expect(nameInput).toBeInTheDocument();
|
||||
@@ -219,19 +193,7 @@ describe('RoutingPolicyDetails', () => {
|
||||
});
|
||||
|
||||
it('should close modal when cancel button is clicked', () => {
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="edit"
|
||||
channels={mockChannels}
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={false}
|
||||
isErrorChannels={false}
|
||||
isLoadingChannels={false}
|
||||
refreshChannels={mockRefreshChannels}
|
||||
/>,
|
||||
);
|
||||
renderRoutingPolicyDetails({ mode: 'edit' });
|
||||
|
||||
const cancelButton = screen.getByRole('button', { name: 'Cancel' });
|
||||
fireEvent.click(cancelButton);
|
||||
@@ -239,19 +201,10 @@ describe('RoutingPolicyDetails', () => {
|
||||
});
|
||||
|
||||
it('buttons should be disabled when loading', () => {
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="edit"
|
||||
channels={mockChannels}
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading
|
||||
isErrorChannels={false}
|
||||
isLoadingChannels={false}
|
||||
refreshChannels={mockRefreshChannels}
|
||||
/>,
|
||||
);
|
||||
renderRoutingPolicyDetails({
|
||||
mode: 'edit',
|
||||
isPolicyDetailsModalActionLoading: true,
|
||||
});
|
||||
|
||||
const cancelButton = screen.getByRole('button', { name: 'Cancel' });
|
||||
expect(cancelButton).toBeDisabled();
|
||||
@@ -268,19 +221,7 @@ describe('RoutingPolicyDetails', () => {
|
||||
});
|
||||
|
||||
it('submit should not be called when inputs are invalid', () => {
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="create"
|
||||
channels={mockChannels}
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={false}
|
||||
isErrorChannels={false}
|
||||
isLoadingChannels={false}
|
||||
refreshChannels={mockRefreshChannels}
|
||||
/>,
|
||||
);
|
||||
renderRoutingPolicyDetails();
|
||||
|
||||
const saveButton = screen.getByRole('button', {
|
||||
name: SAVE_BUTTON_TEXT,
|
||||
@@ -290,139 +231,155 @@ describe('RoutingPolicyDetails', () => {
|
||||
expect(mockHandlePolicyDetailsModalAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('notification channels select should be disabled when channels are loading', () => {
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="create"
|
||||
channels={[]}
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={false}
|
||||
isErrorChannels={false}
|
||||
isLoadingChannels
|
||||
refreshChannels={mockRefreshChannels}
|
||||
/>,
|
||||
it('shows a spinner in the channel list while channels load', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (_req, res, ctx) =>
|
||||
res(ctx.delay(1_000), ctx.json(notificationChannelsListResponse([]))),
|
||||
),
|
||||
);
|
||||
renderRoutingPolicyDetails();
|
||||
|
||||
const channelSelect = screen.getByRole('combobox');
|
||||
expect(channelSelect).toBeDisabled();
|
||||
await user.click(channelInput());
|
||||
|
||||
expect(
|
||||
screen.getByTestId('routing-policy-channel-spinner'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByText(NO_CHANNELS_FOUND_TEXT)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show error state when channels fail to load', () => {
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="create"
|
||||
channels={[]}
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={false}
|
||||
isErrorChannels
|
||||
isLoadingChannels={false}
|
||||
refreshChannels={mockRefreshChannels}
|
||||
/>,
|
||||
it('should show error state when channels fail to load', async () => {
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (_req, res, ctx) =>
|
||||
res(ctx.status(500), ctx.json({ status: 'error' })),
|
||||
),
|
||||
);
|
||||
renderRoutingPolicyDetails();
|
||||
|
||||
const channelSelect = screen.getByRole('combobox');
|
||||
const selectContainer = channelSelect.closest('.ant-select');
|
||||
expect(selectContainer).toHaveClass('ant-select-status-error');
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId(CHANNEL_SELECT)).toHaveClass(
|
||||
'ant-select-status-error',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('should show empty state when no channels are available', () => {
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="create"
|
||||
channels={[]}
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={false}
|
||||
isErrorChannels={false}
|
||||
isLoadingChannels={false}
|
||||
refreshChannels={mockRefreshChannels}
|
||||
/>,
|
||||
);
|
||||
it('should show empty state when no channels are available', async () => {
|
||||
serveChannels([]);
|
||||
renderRoutingPolicyDetails();
|
||||
|
||||
const channelSelect = screen.getByRole('combobox');
|
||||
fireEvent.mouseDown(channelSelect);
|
||||
fireEvent.mouseDown(channelInput());
|
||||
|
||||
expect(screen.getByText(NO_CHANNELS_FOUND_TEXT)).toBeInTheDocument();
|
||||
await expect(
|
||||
screen.findByText(NO_CHANNELS_FOUND_TEXT),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show create channel button for admin users in empty state', () => {
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="create"
|
||||
channels={[]}
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={false}
|
||||
isErrorChannels={false}
|
||||
isLoadingChannels={false}
|
||||
refreshChannels={mockRefreshChannels}
|
||||
/>,
|
||||
);
|
||||
it('should show create channel button for admin users in empty state', async () => {
|
||||
serveChannels([]);
|
||||
renderRoutingPolicyDetails();
|
||||
|
||||
const channelSelect = screen.getByRole('combobox');
|
||||
fireEvent.mouseDown(channelSelect);
|
||||
fireEvent.mouseDown(channelInput());
|
||||
|
||||
expect(screen.getByText(NO_CHANNELS_FOUND_TEXT)).toBeInTheDocument();
|
||||
await expect(
|
||||
screen.findByText(NO_CHANNELS_FOUND_TEXT),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText('Create one')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show admin message for non-admin users in empty state', () => {
|
||||
it('should show admin message for non-admin users in empty state', async () => {
|
||||
jest
|
||||
.spyOn(appHooks, 'useAppContext')
|
||||
.mockReturnValue(getAppContextMockState({ role: 'VIEWER' }));
|
||||
serveChannels([]);
|
||||
renderRoutingPolicyDetails();
|
||||
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="create"
|
||||
channels={[]}
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={false}
|
||||
isErrorChannels={false}
|
||||
isLoadingChannels={false}
|
||||
refreshChannels={mockRefreshChannels}
|
||||
/>,
|
||||
);
|
||||
fireEvent.mouseDown(channelInput());
|
||||
|
||||
const channelSelect = screen.getByRole('combobox');
|
||||
fireEvent.mouseDown(channelSelect);
|
||||
|
||||
expect(screen.getByText(NO_CHANNELS_FOUND_TEXT)).toBeInTheDocument();
|
||||
await expect(
|
||||
screen.findByText(NO_CHANNELS_FOUND_TEXT),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('Please ask your admin to create one.'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByText('Create one')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should call refreshChannels when refresh button is clicked in empty state', () => {
|
||||
render(
|
||||
<RoutingPolicyDetails
|
||||
routingPolicy={mockRoutingPolicy}
|
||||
closeModal={mockCloseModal}
|
||||
mode="create"
|
||||
channels={[]}
|
||||
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
|
||||
isPolicyDetailsModalActionLoading={false}
|
||||
isErrorChannels={false}
|
||||
isLoadingChannels={false}
|
||||
refreshChannels={mockRefreshChannels}
|
||||
/>,
|
||||
it('refetches channels when refresh is clicked in empty state', async () => {
|
||||
let requestCount = 0;
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (_req, res, ctx) => {
|
||||
requestCount += 1;
|
||||
return res(ctx.json(notificationChannelsListResponse([])));
|
||||
}),
|
||||
);
|
||||
renderRoutingPolicyDetails();
|
||||
|
||||
fireEvent.mouseDown(channelInput());
|
||||
fireEvent.click(await screen.findByText('Refresh'));
|
||||
|
||||
await waitFor(() => expect(requestCount).toBe(2));
|
||||
});
|
||||
|
||||
it('searches channels on the server as the user types', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const queries: (string | null)[] = [];
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (req, res, ctx) => {
|
||||
const query = req.url.searchParams.get('query');
|
||||
queries.push(query);
|
||||
return res(
|
||||
ctx.json(
|
||||
notificationChannelsListResponse(query ? ['Channel 2'] : CHANNEL_NAMES),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
renderRoutingPolicyDetails();
|
||||
|
||||
await user.click(channelInput());
|
||||
await screen.findByTitle('Channel 1');
|
||||
await user.type(channelInput(), '2');
|
||||
|
||||
await expect(screen.findByTitle('Channel 2')).resolves.toBeInTheDocument();
|
||||
expect(screen.queryByTitle('Channel 1')).not.toBeInTheDocument();
|
||||
expect(queries).toStrictEqual([null, '2']);
|
||||
});
|
||||
|
||||
it('loads the next page when the list is scrolled to the bottom', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const offsets: string[] = [];
|
||||
server.use(
|
||||
rest.get(CHANNELS_URL, (req, res, ctx) => {
|
||||
const offset = Number(req.url.searchParams.get('offset'));
|
||||
offsets.push(String(offset));
|
||||
const names = Array.from(
|
||||
{ length: offset === 0 ? 100 : 20 },
|
||||
(_, index) => `channel-${offset + index}`,
|
||||
);
|
||||
return res(ctx.json(notificationChannelsListResponse(names, 120)));
|
||||
}),
|
||||
);
|
||||
renderRoutingPolicyDetails();
|
||||
|
||||
await user.click(channelInput());
|
||||
await screen.findByTitle('channel-0');
|
||||
fireEvent.scroll(
|
||||
document.querySelector('.rc-virtual-list-holder') as HTMLElement,
|
||||
);
|
||||
|
||||
const channelSelect = screen.getByRole('combobox');
|
||||
fireEvent.mouseDown(channelSelect);
|
||||
await waitFor(() => expect(offsets).toStrictEqual(['0', '100']));
|
||||
});
|
||||
|
||||
const refreshButton = screen.getByText('Refresh');
|
||||
expect(refreshButton).toBeInTheDocument();
|
||||
it('keeps the name of a saved channel the results do not include', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
serveChannels(['Channel 2']);
|
||||
renderRoutingPolicyDetails({ mode: 'edit' });
|
||||
|
||||
fireEvent.click(refreshButton);
|
||||
expect(mockRefreshChannels).toHaveBeenCalledTimes(1);
|
||||
await user.click(channelInput());
|
||||
await screen.findByTitle('Channel 2');
|
||||
|
||||
expect(
|
||||
within(screen.getByTestId(CHANNEL_SELECT)).getByTitle('Channel 1'),
|
||||
).toHaveTextContent('Channel 1');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { ApiRoutingPolicy } from 'api/routingPolicies/getRoutingPolicies';
|
||||
import { IAppContext, IUser } from 'providers/App/types';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
|
||||
import { RoutingPolicy, UseRoutingPoliciesReturn } from '../types';
|
||||
|
||||
@@ -28,15 +27,6 @@ export const MOCK_ROUTING_POLICY_2: RoutingPolicy = {
|
||||
updatedBy: 'user2@signoz.io',
|
||||
};
|
||||
|
||||
export const MOCK_CHANNEL_1: ChannelOption = {
|
||||
name: 'Channel 1',
|
||||
id: '1',
|
||||
};
|
||||
export const MOCK_CHANNEL_2: ChannelOption = {
|
||||
name: 'Channel 2',
|
||||
id: '2',
|
||||
};
|
||||
|
||||
export function getUseRoutingPoliciesMockData(
|
||||
overrides?: Partial<UseRoutingPoliciesReturn>,
|
||||
): UseRoutingPoliciesReturn {
|
||||
@@ -45,8 +35,6 @@ export function getUseRoutingPoliciesMockData(
|
||||
routingPoliciesData: [MOCK_ROUTING_POLICY_1, MOCK_ROUTING_POLICY_2],
|
||||
isLoadingRoutingPolicies: false,
|
||||
isErrorRoutingPolicies: false,
|
||||
channels: [MOCK_CHANNEL_1, MOCK_CHANNEL_2],
|
||||
isLoadingChannels: false,
|
||||
searchTerm: '',
|
||||
setSearchTerm: jest.fn(),
|
||||
isDeleteModalOpen: false,
|
||||
@@ -62,8 +50,6 @@ export function getUseRoutingPoliciesMockData(
|
||||
handlePolicyDetailsModalOpen: jest.fn(),
|
||||
handlePolicyDetailsModalAction: jest.fn(),
|
||||
isPolicyDetailsModalActionLoading: false,
|
||||
isErrorChannels: false,
|
||||
refreshChannels: jest.fn(),
|
||||
isFetchingRoutingPolicies: false,
|
||||
refetchRoutingPolicies: jest.fn(),
|
||||
...overrides,
|
||||
|
||||
@@ -13,8 +13,6 @@ import { UseRoutingPoliciesReturn } from '../types';
|
||||
import useRoutingPolicies from '../useRoutingPolicies';
|
||||
import {
|
||||
convertRoutingPolicyToApiResponse,
|
||||
MOCK_CHANNEL_1,
|
||||
MOCK_CHANNEL_2,
|
||||
MOCK_ROUTING_POLICY_1,
|
||||
MOCK_ROUTING_POLICY_2,
|
||||
} from './testUtils';
|
||||
@@ -73,15 +71,6 @@ jest.mock('hooks/routingPolicies/useDeleteRoutingPolicy', () => ({
|
||||
isLoading: false,
|
||||
}),
|
||||
}));
|
||||
jest.mock('hooks/notificationChannels/useChannelOptions', () => ({
|
||||
__esModule: true,
|
||||
useChannelOptions: (): any => ({
|
||||
data: [MOCK_CHANNEL_1, MOCK_CHANNEL_2],
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
refetch: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
const ROUTING_POLICY_1_NAME = 'Routing Policy 1';
|
||||
const TEST_SEARCH_TERM = 'test search';
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { AlertmanagertypesGettableRoutePolicyDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type { TableColumnDef } from 'components/TanStackTableView';
|
||||
import type { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
|
||||
export type RoutingPolicy = AlertmanagertypesGettableRoutePolicyDTO;
|
||||
|
||||
@@ -44,12 +43,8 @@ export interface RoutingPolicyDetailsProps {
|
||||
routingPolicy: RoutingPolicy | null;
|
||||
closeModal: () => void;
|
||||
mode: PolicyDetailsModalMode;
|
||||
channels: ChannelOption[];
|
||||
isErrorChannels: boolean;
|
||||
isLoadingChannels: boolean;
|
||||
handlePolicyDetailsModalAction: HandlePolicyDetailsModalAction;
|
||||
isPolicyDetailsModalActionLoading: boolean;
|
||||
refreshChannels: () => void;
|
||||
}
|
||||
|
||||
export interface DeleteRoutingPolicyProps {
|
||||
@@ -67,11 +62,6 @@ export interface UseRoutingPoliciesReturn {
|
||||
isFetchingRoutingPolicies: boolean;
|
||||
isErrorRoutingPolicies: boolean;
|
||||
refetchRoutingPolicies: () => void;
|
||||
// Channels
|
||||
channels: ChannelOption[];
|
||||
isLoadingChannels: boolean;
|
||||
isErrorChannels: boolean;
|
||||
refreshChannels: () => void;
|
||||
// Search
|
||||
searchTerm: string;
|
||||
setSearchTerm: (searchTerm: string) => void;
|
||||
|
||||
@@ -7,7 +7,6 @@ import { GetRoutingPoliciesResponse } from 'api/routingPolicies/getRoutingPolici
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
import { useCreateRoutingPolicy } from 'hooks/routingPolicies/useCreateRoutingPolicy';
|
||||
import { useDeleteRoutingPolicy } from 'hooks/routingPolicies/useDeleteRoutingPolicy';
|
||||
import { useChannelOptions } from 'hooks/notificationChannels/useChannelOptions';
|
||||
import { useGetRoutingPolicies } from 'hooks/routingPolicies/useGetRoutingPolicies';
|
||||
import { useUpdateRoutingPolicy } from 'hooks/routingPolicies/useUpdateRoutingPolicy';
|
||||
import useDebouncedFn from 'hooks/useDebouncedFunction';
|
||||
@@ -93,18 +92,6 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
|
||||
);
|
||||
}, [routingPolicies, searchTerm]);
|
||||
|
||||
// Channels list
|
||||
const {
|
||||
data: channels,
|
||||
isLoading: isLoadingChannels,
|
||||
isError: isErrorChannels,
|
||||
refetch: refetchChannels,
|
||||
} = useChannelOptions();
|
||||
|
||||
const refreshChannels = (): void => {
|
||||
void refetchChannels();
|
||||
};
|
||||
|
||||
// Handlers
|
||||
const handlePolicyDetailsModalOpen = useCallback(
|
||||
(mode: PolicyDetailsModalMode, routingPolicy: RoutingPolicy | null): void => {
|
||||
@@ -243,11 +230,6 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
|
||||
isFetchingRoutingPolicies,
|
||||
isErrorRoutingPolicies,
|
||||
refetchRoutingPolicies,
|
||||
// Channels
|
||||
channels,
|
||||
isLoadingChannels,
|
||||
isErrorChannels,
|
||||
refreshChannels,
|
||||
// Search
|
||||
searchTerm,
|
||||
setSearchTerm: handleSearch,
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
import { useQuery, UseQueryResult } from 'react-query';
|
||||
import { listNotificationChannels } from 'api/generated/services/channels';
|
||||
import {
|
||||
AlertmanagertypesChannelListOrderDTO,
|
||||
AlertmanagertypesChannelListSortDTO,
|
||||
AlertmanagertypesListedNotificationChannelDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { range } from 'lodash-es';
|
||||
|
||||
const PAGE_SIZE = 100;
|
||||
|
||||
export const CHANNEL_OPTIONS_QUERY_KEY = ['notificationChannelOptions'];
|
||||
|
||||
export interface ChannelOption {
|
||||
id: string;
|
||||
/** The display name, which is what rules and routing policies reference. */
|
||||
name: string;
|
||||
}
|
||||
|
||||
export type UseChannelOptionsResult = Omit<
|
||||
UseQueryResult<ChannelOption[], Error>,
|
||||
'data'
|
||||
> & {
|
||||
data: ChannelOption[];
|
||||
};
|
||||
|
||||
function fetchPage(
|
||||
offset: number,
|
||||
): ReturnType<typeof listNotificationChannels> {
|
||||
return listNotificationChannels({
|
||||
limit: PAGE_SIZE,
|
||||
offset,
|
||||
sort: AlertmanagertypesChannelListSortDTO.name,
|
||||
order: AlertmanagertypesChannelListOrderDTO.asc,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Every channel, for the pickers that let a rule or a policy name one. The list
|
||||
* API is paginated and silently clamps a larger limit, so the first page reports
|
||||
* the total and any remainder is fetched alongside rather than truncating. One
|
||||
* request covers an org with a page's worth of channels or fewer.
|
||||
*/
|
||||
async function fetchAllChannels(): Promise<ChannelOption[]> {
|
||||
const first = await fetchPage(0);
|
||||
const rest = await Promise.all(
|
||||
range(PAGE_SIZE, first.data.total, PAGE_SIZE).map(fetchPage),
|
||||
);
|
||||
|
||||
const channels: AlertmanagertypesListedNotificationChannelDTO[] = [
|
||||
...first.data.channels,
|
||||
...rest.flatMap((page) => page.data.channels),
|
||||
];
|
||||
|
||||
return channels.map((channel) => ({
|
||||
id: channel.id,
|
||||
name: channel.displayName,
|
||||
}));
|
||||
}
|
||||
|
||||
export function useChannelOptions(): UseChannelOptionsResult {
|
||||
const query = useQuery<ChannelOption[], Error>(
|
||||
CHANNEL_OPTIONS_QUERY_KEY,
|
||||
fetchAllChannels,
|
||||
);
|
||||
|
||||
return { ...query, data: query.data ?? [] };
|
||||
}
|
||||
121
frontend/src/hooks/notificationChannels/useChannelSearch.ts
Normal file
121
frontend/src/hooks/notificationChannels/useChannelSearch.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
import { UIEvent, useCallback, useMemo, useState } from 'react';
|
||||
import { useInfiniteQuery } from 'react-query';
|
||||
import {
|
||||
listNotificationChannels,
|
||||
ListNotificationChannelsQueryError,
|
||||
} from 'api/generated/services/channels';
|
||||
import {
|
||||
AlertmanagertypesChannelListOrderDTO,
|
||||
AlertmanagertypesChannelListSortDTO,
|
||||
ListNotificationChannelsParams,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import useDebounce from 'hooks/useDebounce';
|
||||
|
||||
const PAGE_SIZE = 100;
|
||||
const SEARCH_DEBOUNCE_MS = 300;
|
||||
const LOAD_MORE_THRESHOLD_PX = 40;
|
||||
|
||||
export interface ChannelSelectOption {
|
||||
/** What a rule or routing policy stores: today the display name. */
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface UseChannelSearchResult {
|
||||
options: ChannelSelectOption[];
|
||||
/** How many channels match the current search, across every page. */
|
||||
total: number | undefined;
|
||||
searchTerm: string;
|
||||
setSearchTerm: (term: string) => void;
|
||||
/** A typed term is waiting on the debounce or on its first page. */
|
||||
isSearching: boolean;
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
error: ListNotificationChannelsQueryError | null;
|
||||
refetch: () => void;
|
||||
loadMoreOnScroll: (event: UIEvent<HTMLDivElement>) => void;
|
||||
}
|
||||
|
||||
export function useChannelSearch(): UseChannelSearchResult {
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const trimmedTerm = searchTerm.trim();
|
||||
const debouncedTerm = useDebounce(trimmedTerm, SEARCH_DEBOUNCE_MS);
|
||||
// Clearing the box skips the debounce: the unfiltered list is already cached.
|
||||
const query = trimmedTerm ? debouncedTerm : '';
|
||||
|
||||
const params: ListNotificationChannelsParams = {
|
||||
query: query || undefined,
|
||||
limit: PAGE_SIZE,
|
||||
sort: AlertmanagertypesChannelListSortDTO.name,
|
||||
order: AlertmanagertypesChannelListOrderDTO.asc,
|
||||
};
|
||||
|
||||
const {
|
||||
data,
|
||||
isLoading,
|
||||
isError,
|
||||
error,
|
||||
refetch,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
fetchNextPage,
|
||||
} = useInfiniteQuery<
|
||||
Awaited<ReturnType<typeof listNotificationChannels>>,
|
||||
ListNotificationChannelsQueryError
|
||||
>({
|
||||
queryKey: ['notificationChannelSearch', params],
|
||||
queryFn: ({ pageParam = 0, signal }) =>
|
||||
listNotificationChannels({ ...params, offset: pageParam }, signal),
|
||||
getNextPageParam: (lastPage, allPages) => {
|
||||
const loaded = allPages.reduce(
|
||||
(count, page) => count + page.data.channels.length,
|
||||
0,
|
||||
);
|
||||
return lastPage.data.channels.length > 0 && loaded < lastPage.data.total
|
||||
? loaded
|
||||
: undefined;
|
||||
},
|
||||
});
|
||||
|
||||
const isSearching = trimmedTerm !== query || isLoading;
|
||||
|
||||
const options = useMemo(
|
||||
() =>
|
||||
isSearching
|
||||
? []
|
||||
: (data?.pages ?? []).flatMap((page) =>
|
||||
page.data.channels.map((channel) => ({
|
||||
value: channel.displayName,
|
||||
label: channel.displayName,
|
||||
})),
|
||||
),
|
||||
[data, isSearching],
|
||||
);
|
||||
|
||||
const loadMoreOnScroll = useCallback(
|
||||
(event: UIEvent<HTMLDivElement>): void => {
|
||||
const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
|
||||
if (
|
||||
hasNextPage &&
|
||||
!isFetchingNextPage &&
|
||||
scrollHeight - scrollTop - clientHeight < LOAD_MORE_THRESHOLD_PX
|
||||
) {
|
||||
void fetchNextPage();
|
||||
}
|
||||
},
|
||||
[hasNextPage, isFetchingNextPage, fetchNextPage],
|
||||
);
|
||||
|
||||
return {
|
||||
options,
|
||||
total: data?.pages[0]?.data.total,
|
||||
searchTerm,
|
||||
setSearchTerm,
|
||||
isSearching,
|
||||
isLoading,
|
||||
isError,
|
||||
error,
|
||||
refetch,
|
||||
loadMoreOnScroll,
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
AlertmanagertypesChannelKindDTO,
|
||||
ListNotificationChannels200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
export const editAlertChannelInitialValue = {
|
||||
api_url:
|
||||
'https://discord.com/api/webhooks/dummy_webhook_id/dummy_webhook_token/slack',
|
||||
@@ -59,6 +64,25 @@ export const notificationChannelsV2 = [
|
||||
},
|
||||
];
|
||||
|
||||
/** A v2 list page with one channel per display name. */
|
||||
export const notificationChannelsListResponse = (
|
||||
displayNames: string[],
|
||||
total = displayNames.length,
|
||||
): ListNotificationChannels200 => ({
|
||||
status: 'success',
|
||||
data: {
|
||||
channels: displayNames.map((displayName, index) => ({
|
||||
id: `channel-${index}`,
|
||||
name: displayName.toLowerCase(),
|
||||
displayName,
|
||||
kind: AlertmanagertypesChannelKindDTO.slack,
|
||||
createdAt: '2024-02-03T04:45:19.239344617Z',
|
||||
updatedAt: '2024-06-28T11:37:14.841184399Z',
|
||||
})),
|
||||
total,
|
||||
},
|
||||
});
|
||||
|
||||
export const notificationChannelV2 = {
|
||||
id: '3',
|
||||
name: 'dummy-channel',
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
import {
|
||||
alertRuleByIdResponse,
|
||||
ALERT_SCHEMAS,
|
||||
notificationChannelsResponse,
|
||||
notificationChannelsPage,
|
||||
CHANNEL_MAX,
|
||||
FIRST_RULE_NAME,
|
||||
type AlertSchema,
|
||||
@@ -149,7 +149,9 @@ export const alertHistoryMocks = defineStoryMocks({
|
||||
|
||||
rest.get(
|
||||
'http://localhost/api/v2/notification_channels',
|
||||
response.json(() => notificationChannelsResponse(CHANNEL_MAX)),
|
||||
response.json((req) =>
|
||||
notificationChannelsPage(CHANNEL_MAX, req.url.searchParams),
|
||||
),
|
||||
),
|
||||
],
|
||||
config: () => ({
|
||||
|
||||
@@ -12,7 +12,7 @@ import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import {
|
||||
alertRuleByIdResponse,
|
||||
ALERT_SCHEMAS,
|
||||
notificationChannelsResponse,
|
||||
notificationChannelsPage,
|
||||
CHANNEL_MAX,
|
||||
RULE_KINDS,
|
||||
RULE_STATE_CHOICES,
|
||||
@@ -127,7 +127,9 @@ export const alertOverviewMocks = defineStoryMocks({
|
||||
|
||||
rest.get(
|
||||
'http://localhost/api/v2/notification_channels',
|
||||
response.json(() => notificationChannelsResponse(values.channels)),
|
||||
response.json((req) =>
|
||||
notificationChannelsPage(values.channels, req.url.searchParams),
|
||||
),
|
||||
),
|
||||
|
||||
rest.post(
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
import {
|
||||
CHANNEL_MAX,
|
||||
channelNames,
|
||||
notificationChannelsResponse,
|
||||
notificationChannelsPage,
|
||||
} from '../../stories/__story_mockdata__/alerts';
|
||||
import { AlertListSubTabs, AlertListTabs } from '../../types';
|
||||
|
||||
@@ -119,10 +119,12 @@ export const routingPoliciesMocks = defineStoryMocks({
|
||||
: res(ctx.status(200), ctx.json({ status: 'success', data: null })),
|
||||
),
|
||||
|
||||
rest.get('http://localhost/api/v2/notification_channels', (_req, res, ctx) =>
|
||||
rest.get('http://localhost/api/v2/notification_channels', (req, res, ctx) =>
|
||||
values.channelsState === 'error'
|
||||
? res(ctx.status(500), ctx.json({ status: 'error' }))
|
||||
: res(ctx.json(notificationChannelsResponse(values.channels))),
|
||||
: res(
|
||||
ctx.json(notificationChannelsPage(values.channels, req.url.searchParams)),
|
||||
),
|
||||
),
|
||||
],
|
||||
config: () => ({
|
||||
|
||||
@@ -781,23 +781,6 @@ const buildListedChannel = (
|
||||
};
|
||||
};
|
||||
|
||||
/** The v2 list, which is what the redesigned channels list reads. */
|
||||
export const notificationChannelsResponse = (
|
||||
count: number,
|
||||
): {
|
||||
status: string;
|
||||
data: {
|
||||
channels: AlertmanagertypesListedNotificationChannelDTO[];
|
||||
total: number;
|
||||
};
|
||||
} => {
|
||||
const channels = Array.from({ length: count }, (_unused, index) =>
|
||||
buildListedChannel(index),
|
||||
);
|
||||
|
||||
return { status: 'success', data: { channels, total: channels.length } };
|
||||
};
|
||||
|
||||
/**
|
||||
* The v2 list as the API answers it: search, kind and paging are applied on the
|
||||
* server, so the story has to narrow the rows rather than hand back all of them.
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
alertPreviewSeries,
|
||||
} from '../../AlertList/stories/__story_mockdata__/alertQuery';
|
||||
import {
|
||||
notificationChannelsResponse,
|
||||
notificationChannelsPage,
|
||||
CHANNEL_MAX,
|
||||
} from '../../AlertList/stories/__story_mockdata__/alerts';
|
||||
|
||||
@@ -128,7 +128,9 @@ export const createAlertMocks = defineStoryMocks({
|
||||
|
||||
rest.get(
|
||||
'http://localhost/api/v2/notification_channels',
|
||||
response.json(() => notificationChannelsResponse(values.channels)),
|
||||
response.json((req) =>
|
||||
notificationChannelsPage(values.channels, req.url.searchParams),
|
||||
),
|
||||
),
|
||||
|
||||
rest.post(
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
import {
|
||||
alertRuleByIdResponse,
|
||||
ALERT_SCHEMAS,
|
||||
notificationChannelsResponse,
|
||||
notificationChannelsPage,
|
||||
CHANNEL_MAX,
|
||||
type AlertSchema,
|
||||
} from '../../AlertList/stories/__story_mockdata__/alerts';
|
||||
@@ -78,7 +78,9 @@ export const editRulesMocks = defineStoryMocks({
|
||||
|
||||
rest.get(
|
||||
'http://localhost/api/v2/notification_channels',
|
||||
response.json(() => notificationChannelsResponse(values.channels)),
|
||||
response.json((req) =>
|
||||
notificationChannelsPage(values.channels, req.url.searchParams),
|
||||
),
|
||||
),
|
||||
|
||||
rest.post(
|
||||
|
||||
Reference in New Issue
Block a user