Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat: add alert condition component (#9008)

Amlan Kumar Nandy39c2738ef903
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/AlertCondition.tsx b/frontend/src/container/CreateAlertV2/AlertCondition/AlertCondition.tsx
new file mode 100644
index 0000000000..e45a44d2d2
--- /dev/null
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/AlertCondition.tsx
@@ -0,0 +1,82 @@
+import './styles.scss';
+
+import { Button, Tooltip } from 'antd';
+import classNames from 'classnames';
+import { Activity, ChartLine } from 'lucide-react';
+import { AlertTypes } from 'types/api/alerts/alertTypes';
+
+import { useCreateAlertState } from '../context';
+import Stepper from '../Stepper';
+import AlertThreshold from './AlertThreshold';
+import AnomalyThreshold from './AnomalyThreshold';
+import { ANOMALY_TAB_TOOLTIP, THRESHOLD_TAB_TOOLTIP } from './constants';
+
+function AlertCondition(): JSX.Element {
+ const { alertType, setAlertType } = useCreateAlertState();
+
+ const showMultipleTabs =
+ alertType === AlertTypes.ANOMALY_BASED_ALERT ||
+ alertType === AlertTypes.METRICS_BASED_ALERT;
+
+ const tabs = [
+ {
+ label: 'Threshold',
+ icon: <ChartLine size={14} data-testid="threshold-view" />,
+ value: AlertTypes.METRICS_BASED_ALERT,
+ },
+ ...(showMultipleTabs
+ ? [
+ {
+ label: 'Anomaly',
+ icon: <Activity size={14} data-testid="anomaly-view" />,
+ value: AlertTypes.ANOMALY_BASED_ALERT,
+ },
+ ]
+ : []),
+ ];
+
+ const handleAlertTypeChange = (value: AlertTypes): void => {
+ if (!showMultipleTabs) {
+ return;
+ }
+ setAlertType(value);
+ };
+
+ const getTabTooltip = (tab: { value: AlertTypes }): string => {
+ if (tab.value === AlertTypes.ANOMALY_BASED_ALERT) {
+ return ANOMALY_TAB_TOOLTIP;
+ }
+ return THRESHOLD_TAB_TOOLTIP;
+ };
+
+ return (
+ <div className="alert-condition-container">
+ <Stepper stepNumber={2} label="Set alert conditions" />
+ <div className="alert-condition">
+ <div className="alert-condition-tabs">
+ {tabs.map((tab) => (
+ <Tooltip key={tab.value} title={getTabTooltip(tab)}>
+ <Button
+ className={classNames('list-view-tab', 'explorer-view-option', {
+ 'active-tab': alertType === tab.value,
+ })}
+ onClick={(): void => {
+ if (alertType !== tab.value) {
+ handleAlertTypeChange(tab.value as AlertTypes);
+ }
+ }}
+ >
+ {tab.icon}
+ {tab.label}
+ </Button>
+ </Tooltip>
+ ))}
+ </div>
+ </div>
+ {alertType !== AlertTypes.ANOMALY_BASED_ALERT && <AlertThreshold />}
+ {alertType === AlertTypes.ANOMALY_BASED_ALERT && <AnomalyThreshold />}
+ </div>
+ );
+}
+
+export default AlertCondition;
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/AlertThreshold.tsx b/frontend/src/container/CreateAlertV2/AlertCondition/AlertThreshold.tsx
new file mode 100644
index 0000000000..1610602daf
--- /dev/null
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/AlertThreshold.tsx
@@ -0,0 +1,162 @@
+import './styles.scss';
+
+import { Button, Select, Typography } from 'antd';
+import getAllChannels from 'api/channels/getAll';
+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
+import { Plus } from 'lucide-react';
+import { useQuery } from 'react-query';
+import { SuccessResponseV2 } from 'types/api';
+import { Channels } from 'types/api/channels/getAll';
+import APIError from 'types/api/error';
+
+import { useCreateAlertState } from '../context';
+import {
+ INITIAL_INFO_THRESHOLD,
+ INITIAL_RANDOM_THRESHOLD,
+ INITIAL_WARNING_THRESHOLD,
+ THRESHOLD_MATCH_TYPE_OPTIONS,
+ THRESHOLD_OPERATOR_OPTIONS,
+} from '../context/constants';
+import ThresholdItem from './ThresholdItem';
+import { UpdateThreshold } from './types';
+import {
+ getCategoryByOptionId,
+ getCategorySelectOptionByName,
+ getQueryNames,
+} from './utils';
+
+function AlertThreshold(): JSX.Element {
+ const {
+ alertState,
+ thresholdState,
+ setThresholdState,
+ } = useCreateAlertState();
+ const { data, isLoading: isLoadingChannels } = useQuery<
+ SuccessResponseV2<Channels[]>,
+ APIError
+ >(['getChannels'], {
+ queryFn: () => getAllChannels(),
+ });
+ const channels = data?.data || [];
+
+ const { currentQuery } = useQueryBuilder();
+
+ const queryNames = getQueryNames(currentQuery);
+
+ const selectedCategory = getCategoryByOptionId(alertState.yAxisUnit || '');
+ const categorySelectOptions = getCategorySelectOptionByName(
+ selectedCategory || '',
+ );
+
+ const addThreshold = (): void => {
+ let newThreshold;
+ if (thresholdState.thresholds.length === 1) {
+ newThreshold = INITIAL_WARNING_THRESHOLD;
+ } else if (thresholdState.thresholds.length === 2) {
+ newThreshold = INITIAL_INFO_THRESHOLD;
+ } else {
+ newThreshold = INITIAL_RANDOM_THRESHOLD;
+ }
+ setThresholdState({
+ type: 'SET_THRESHOLDS',
+ payload: [...thresholdState.thresholds, newThreshold],
+ });
+ };
+
+ const removeThreshold = (id: string): void => {
+ if (thresholdState.thresholds.length > 1) {
+ setThresholdState({
+ type: 'SET_THRESHOLDS',
+ payload: thresholdState.thresholds.filter((t) => t.id !== id),
+ });
+ }
+ };
+
+ const updateThreshold: UpdateThreshold = (id, field, value) => {
+ setThresholdState({
+ type: 'SET_THRESHOLDS',
+ payload: thresholdState.thresholds.map((t) =>
+ t.id === id ? { ...t, [field]: value } : t,
+ ),
+ });
+ };
+
+ return (
+ <div className="alert-threshold-container">
+ {/* Main condition sentence */}
+ <div className="alert-condition-sentences">
+ <div className="alert-condition-sentence">
+ <Typography.Text className="sentence-text">
+ Send a notification when
+ </Typography.Text>
+ <Select
+ value={thresholdState.selectedQuery}
+ onChange={(value): void => {
+ setThresholdState({
+ type: 'SET_SELECTED_QUERY',
+ payload: value,
+ });
+ }}
+ style={{ width: 80 }}
+ options={queryNames}
+ />
+ </div>
+ <div className="alert-condition-sentence">
+ <Select
+ value={thresholdState.operator}
+ onChange={(value): void => {
+ setThresholdState({
+ type: 'SET_OPERATOR',
+ payload: value,
+ });
+ }}
+ style={{ width: 120 }}
+ options={THRESHOLD_OPERATOR_OPTIONS}
+ />
+ <Typography.Text className="sentence-text">
+ the threshold(s)
+ </Typography.Text>
+ <Select
+ value={thresholdState.matchType}
+ onChange={(value): void => {
+ setThresholdState({
+ type: 'SET_MATCH_TYPE',
+ payload: value,
+ });
+ }}
+ style={{ width: 140 }}
+ options={THRESHOLD_MATCH_TYPE_OPTIONS}
+ />
+ <Typography.Text className="sentence-text">
+ during the <strong>Evaluation Window.</strong>
+ </Typography.Text>
+ </div>
+ </div>
+
+ <div className="thresholds-section">
+ {thresholdState.thresholds.map((threshold, index) => (
+ <ThresholdItem
+ key={threshold.id}
+ threshold={threshold}
+ updateThreshold={updateThreshold}
+ removeThreshold={removeThreshold}
+ showRemoveButton={index !== 0 && thresholdState.thresholds.length > 1}
+ channels={channels}
+ isLoadingChannels={isLoadingChannels}
+ units={categorySelectOptions}
+ />
+ ))}
+ <Button
+ type="dashed"
+ icon={<Plus size={16} />}
+ onClick={addThreshold}
+ className="add-threshold-btn"
+ >
+ Add Threshold
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+export default AlertThreshold;
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/AnomalyThreshold.tsx b/frontend/src/container/CreateAlertV2/AlertCondition/AnomalyThreshold.tsx
new file mode 100644
index 0000000000..a39b3a72a4
--- /dev/null
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/AnomalyThreshold.tsx
@@ -0,0 +1,174 @@
+import { Select, Typography } from 'antd';
+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
+import { useMemo } from 'react';
+
+import { useCreateAlertState } from '../context';
+import {
+ ANOMALY_ALGORITHM_OPTIONS,
+ ANOMALY_SEASONALITY_OPTIONS,
+ ANOMALY_THRESHOLD_MATCH_TYPE_OPTIONS,
+ ANOMALY_THRESHOLD_OPERATOR_OPTIONS,
+ ANOMALY_TIME_DURATION_OPTIONS,
+} from '../context/constants';
+import { getQueryNames } from './utils';
+
+function AnomalyThreshold(): JSX.Element {
+ const { thresholdState, setThresholdState } = useCreateAlertState();
+
+ const { currentQuery } = useQueryBuilder();
+
+ const queryNames = getQueryNames(currentQuery);
+
+ const deviationOptions = useMemo(() => {
+ const options = [];
+ for (let i = 1; i <= 7; i++) {
+ options.push({ label: i.toString(), value: i });
+ }
+ return options;
+ }, []);
+
+ const updateThreshold = (id: string, field: string, value: string): void => {
+ setThresholdState({
+ type: 'SET_THRESHOLDS',
+ payload: thresholdState.thresholds.map((t) =>
+ t.id === id ? { ...t, [field]: value } : t,
+ ),
+ });
+ };
+
+ return (
+ <div className="anomaly-threshold-container">
+ <div className="alert-condition-sentences">
+ {/* Sentence 1 */}
+ <div className="alert-condition-sentence">
+ <Typography.Text data-testid="notification-text" className="sentence-text">
+ Send notification when the observed value for
+ </Typography.Text>
+ <Select
+ value={thresholdState.selectedQuery}
+ data-testid="query-select"
+ onChange={(value): void => {
+ setThresholdState({
+ type: 'SET_SELECTED_QUERY',
+ payload: value,
+ });
+ }}
+ style={{ width: 80 }}
+ options={queryNames}
+ />
+ <Typography.Text
+ data-testid="evaluation-window-text"
+ className="sentence-text"
+ >
+ during the last
+ </Typography.Text>
+ <Select
+ value={thresholdState.evaluationWindow}
+ data-testid="evaluation-window-select"
+ onChange={(value): void => {
+ setThresholdState({
+ type: 'SET_EVALUATION_WINDOW',
+ payload: value,
+ });
+ }}
+ style={{ width: 80 }}
+ options={ANOMALY_TIME_DURATION_OPTIONS}
+ />
+ </div>
+ {/* Sentence 2 */}
+ <div className="alert-condition-sentence">
+ <Typography.Text data-testid="threshold-text" className="sentence-text">
+ is
+ </Typography.Text>
+ <Select
+ value={thresholdState.thresholds[0].thresholdValue}
+ data-testid="threshold-value-select"
+ onChange={(value): void => {
+ updateThreshold(
+ thresholdState.thresholds[0].id,
+ 'thresholdValue',
+ value.toString(),
+ );
+ }}
+ style={{ width: 80 }}
+ options={deviationOptions}
+ />
+ <Typography.Text data-testid="deviations-text" className="sentence-text">
+ deviations
+ </Typography.Text>
+ <Select
+ value={thresholdState.operator}
+ data-testid="operator-select"
+ onChange={(value): void => {
+ setThresholdState({
+ type: 'SET_OPERATOR',
+ payload: value,
+ });
+ }}
+ style={{ width: 80 }}
+ options={ANOMALY_THRESHOLD_OPERATOR_OPTIONS}
+ />
+ <Typography.Text
+ data-testid="predicted-data-text"
+ className="sentence-text"
+ >
+ the predicted data
+ </Typography.Text>
+ <Select
+ value={thresholdState.matchType}
+ data-testid="match-type-select"
+ onChange={(value): void => {
+ setThresholdState({
+ type: 'SET_MATCH_TYPE',
+ payload: value,
+ });
+ }}
+ style={{ width: 80 }}
+ options={ANOMALY_THRESHOLD_MATCH_TYPE_OPTIONS}
+ />
+ </div>
+ {/* Sentence 3 */}
+ <div className="alert-condition-sentence">
+ <Typography.Text data-testid="using-the-text" className="sentence-text">
+ using the
+ </Typography.Text>
+ <Select
+ value={thresholdState.algorithm}
+ data-testid="algorithm-select"
+ onChange={(value): void => {
+ setThresholdState({
+ type: 'SET_ALGORITHM',
+ payload: value,
+ });
+ }}
+ style={{ width: 80 }}
+ options={ANOMALY_ALGORITHM_OPTIONS}
+ />
+ <Typography.Text
+ data-testid="algorithm-with-text"
+ className="sentence-text"
+ >
+ algorithm with
+ </Typography.Text>
+ <Select
+ value={thresholdState.seasonality}
+ data-testid="seasonality-select"
+ onChange={(value): void => {
+ setThresholdState({
+ type: 'SET_SEASONALITY',
+ payload: value,
+ });
+ }}
+ style={{ width: 80 }}
+ options={ANOMALY_SEASONALITY_OPTIONS}
+ />
+ <Typography.Text data-testid="seasonality-text" className="sentence-text">
+ seasonality
+ </Typography.Text>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default AnomalyThreshold;
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/ThresholdItem.tsx b/frontend/src/container/CreateAlertV2/AlertCondition/ThresholdItem.tsx
new file mode 100644
index 0000000000..1d59fddbeb
--- /dev/null
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/ThresholdItem.tsx
@@ -0,0 +1,135 @@
+import { Button, Input, Select, Space, Tooltip, Typography } from 'antd';
+import { ChartLine, CircleX } from 'lucide-react';
+import { useMemo, useState } from 'react';
+
+import { ThresholdItemProps } from './types';
+
+function ThresholdItem({
+ threshold,
+ updateThreshold,
+ removeThreshold,
+ showRemoveButton,
+ channels,
+ units,
+}: ThresholdItemProps): JSX.Element {
+ const [showRecoveryThreshold, setShowRecoveryThreshold] = useState(false);
+
+ const yAxisUnitSelect = useMemo(() => {
+ let component = (
+ <Select
+ placeholder="Unit"
+ value={threshold.unit ? threshold.unit : null}
+ onChange={(value): void => updateThreshold(threshold.id, 'unit', value)}
+ style={{ width: 150 }}
+ options={units}
+ disabled={units.length === 0}
+ />
+ );
+ if (units.length === 0) {
+ component = (
+ <Tooltip
+ trigger="hover"
+ title="Please select a Y-axis unit for the query first"
+ >
+ <Select
+ placeholder="Unit"
+ value={threshold.unit ? threshold.unit : null}
+ onChange={(value): void => updateThreshold(threshold.id, 'unit', value)}
+ style={{ width: 150 }}
+ options={units}
+ disabled={units.length === 0}
+ />
+ </Tooltip>
+ );
+ }
+ return component;
+ }, [units, threshold.unit, updateThreshold, threshold.id]);
+
+ return (
+ <div key={threshold.id} className="threshold-item">
+ <div className="threshold-row">
+ <div className="threshold-indicator">
+ <div
+ className="threshold-dot"
+ style={{ backgroundColor: threshold.color }}
+ />
+ </div>
+ <Space className="threshold-controls">
+ <div className="threshold-inputs">
+ <Input.Group>
+ <Input
+ placeholder="Enter threshold name"
+ value={threshold.label}
+ onChange={(e): void =>
+ updateThreshold(threshold.id, 'label', e.target.value)
+ }
+ style={{ width: 260 }}
+ />
+ <Input
+ placeholder="Enter threshold value"
+ value={threshold.thresholdValue}
+ onChange={(e): void =>
+ updateThreshold(threshold.id, 'thresholdValue', e.target.value)
+ }
+ style={{ width: 210 }}
+ />
+ {yAxisUnitSelect}
+ </Input.Group>
+ </div>
+ <Typography.Text className="sentence-text">to</Typography.Text>
+ <Select
+ value={threshold.channels}
+ onChange={(value): void =>
+ updateThreshold(threshold.id, 'channels', value)
+ }
+ style={{ width: 260 }}
+ options={channels.map((channel) => ({
+ value: channel.id,
+ label: channel.name,
+ }))}
+ mode="multiple"
+ placeholder="Select notification channels"
+ />
+ <Button.Group>
+ {!showRecoveryThreshold && (
+ <Button
+ type="default"
+ icon={<ChartLine size={16} />}
+ className="icon-btn"
+ onClick={(): void => setShowRecoveryThreshold(true)}
+ />
+ )}
+ {showRemoveButton && (
+ <Button
+ type="default"
+ icon={<CircleX size={16} />}
+ onClick={(): void => removeThreshold(threshold.id)}
+ className="icon-btn"
+ />
+ )}
+ </Button.Group>
+ </Space>
+ </div>
+ {showRecoveryThreshold && (
+ <Input.Group className="recovery-threshold-input-group">
+ <Input
+ placeholder="Recovery threshold"
+ disabled
+ style={{ width: 260 }}
+ className="recovery-threshold-label"
+ />
+ <Input
+ placeholder="Enter recovery threshold value"
+ value={threshold.recoveryThresholdValue}
+ onChange={(e): void =>
+ updateThreshold(threshold.id, 'recoveryThresholdValue', e.target.value)
+ }
+ style={{ width: 210 }}
+ />
+ </Input.Group>
+ )}
+ </div>
+ );
+}
+
+export default ThresholdItem;
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AlertCondition.test.tsx b/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AlertCondition.test.tsx
new file mode 100644
index 0000000000..7823616a10
--- /dev/null
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AlertCondition.test.tsx
@@ -0,0 +1,271 @@
+/* eslint-disable @typescript-eslint/no-explicit-any */
+/* eslint-disable react/jsx-props-no-spreading */
+import { fireEvent, render, screen } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from 'react-query';
+import { MemoryRouter } from 'react-router-dom';
+
+import { CreateAlertProvider } from '../../context';
+import AlertCondition from '../AlertCondition';
+
+jest.mock('uplot', () => {
+ const paths = {
+ spline: jest.fn(),
+ bars: jest.fn(),
+ };
+ const uplotMock: any = jest.fn(() => ({
+ paths,
+ }));
+ uplotMock.paths = paths;
+ return uplotMock;
+});
+
+const STEPPER_TEST_ID = 'stepper';
+const ALERT_THRESHOLD_TEST_ID = 'alert-threshold';
+const ANOMALY_THRESHOLD_TEST_ID = 'anomaly-threshold';
+const THRESHOLD_VIEW_TEST_ID = 'threshold-view';
+const ANOMALY_VIEW_TEST_ID = 'anomaly-view';
+const ANOMALY_TAB_TEXT = 'Anomaly';
+const THRESHOLD_TAB_TEXT = 'Threshold';
+const ACTIVE_TAB_CLASS = '.active-tab';
+
+// Mock the Stepper component
+jest.mock('../../Stepper', () => ({
+ __esModule: true,
+ default: function MockStepper({
+ stepNumber,
+ label,
+ }: {
+ stepNumber: number;
+ label: string;
+ }): JSX.Element {
+ return (
+ <div data-testid={STEPPER_TEST_ID}>{`Step ${stepNumber}: ${label}`}</div>
+ );
+ },
+}));
+
+// Mock the AlertThreshold component
+jest.mock('../AlertThreshold', () => ({
+ __esModule: true,
+ default: function MockAlertThreshold(): JSX.Element {
+ return (
+ <div data-testid={ALERT_THRESHOLD_TEST_ID}>Alert Threshold Component</div>
+ );
+ },
+}));
+
+// Mock the AnomalyThreshold component
+jest.mock('../AnomalyThreshold', () => ({
+ __esModule: true,
+ default: function MockAnomalyThreshold(): JSX.Element {
+ return (
+ <div data-testid={ANOMALY_THRESHOLD_TEST_ID}>
+ Anomaly Threshold Component
+ </div>
+ );
+ },
+}));
+
+// Mock useQueryBuilder hook
+jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
+ useQueryBuilder: (): {
+ currentQuery: {
+ builder: { queryData: unknown[]; queryFormulas: unknown[] };
+ dataSource: string;
+ queryName: string;
+ };
+ redirectWithQueryBuilderData: () => void;
+ } => ({
+ currentQuery: {
+ dataSource: 'METRICS',
+ queryName: 'A',
+ builder: {
+ queryData: [{ dataSource: 'METRICS' }],
+ queryFormulas: [],
+ },
+ },
+ redirectWithQueryBuilderData: jest.fn(),
+ }),
+}));
+
+const createTestQueryClient = (): QueryClient =>
+ new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ },
+ });
+
+const renderAlertCondition = (
+ alertType?: string,
+): ReturnType<typeof render> => {
+ const queryClient = createTestQueryClient();
+ const initialEntries = alertType ? [`/?alertType=${alertType}`] : undefined;
+ return render(
+ <MemoryRouter initialEntries={initialEntries}>
+ <QueryClientProvider client={queryClient}>
+ <CreateAlertProvider>
+ <AlertCondition />
+ </CreateAlertProvider>
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+};
+
+describe('AlertCondition', () => {
+ it('renders the stepper with correct step number and label', () => {
+ renderAlertCondition();
+ expect(screen.getByTestId(STEPPER_TEST_ID)).toHaveTextContent(
+ 'Step 2: Set alert conditions',
+ );
+ });
+
+ it('verifies default props and initial state', () => {
+ renderAlertCondition();
+
+ // Verify default alertType is METRICS_BASED_ALERT (shows AlertThreshold component)
+ expect(screen.getByTestId(ALERT_THRESHOLD_TEST_ID)).toBeInTheDocument();
+ expect(
+ screen.queryByTestId(ANOMALY_THRESHOLD_TEST_ID),
+ ).not.toBeInTheDocument();
+
+ // Verify threshold tab is active by default
+ const thresholdTab = screen.getByText(THRESHOLD_TAB_TEXT);
+ expect(thresholdTab.closest(ACTIVE_TAB_CLASS)).toBeInTheDocument();
+
+ // Verify both tabs are visible (METRICS_BASED_ALERT supports multiple tabs)
+ expect(screen.getByText(THRESHOLD_TAB_TEXT)).toBeInTheDocument();
+ expect(screen.getByText(ANOMALY_TAB_TEXT)).toBeInTheDocument();
+ });
+
+ it('renders threshold tab by default', () => {
+ renderAlertCondition();
+ expect(screen.getByText(THRESHOLD_TAB_TEXT)).toBeInTheDocument();
+ expect(screen.getByTestId(THRESHOLD_VIEW_TEST_ID)).toBeInTheDocument();
+
+ // Verify default props
+ expect(screen.getByTestId(ALERT_THRESHOLD_TEST_ID)).toBeInTheDocument();
+ expect(
+ screen.queryByTestId(ANOMALY_THRESHOLD_TEST_ID),
+ ).not.toBeInTheDocument();
+ });
+
+ it('renders anomaly tab when alert type supports multiple tabs', () => {
+ renderAlertCondition();
+ expect(screen.getByText(ANOMALY_TAB_TEXT)).toBeInTheDocument();
+ expect(screen.getByTestId(ANOMALY_VIEW_TEST_ID)).toBeInTheDocument();
+ });
+
+ it('shows AlertThreshold component when alert type is not anomaly based', () => {
+ renderAlertCondition();
+ expect(screen.getByTestId(ALERT_THRESHOLD_TEST_ID)).toBeInTheDocument();
+ expect(
+ screen.queryByTestId(ANOMALY_THRESHOLD_TEST_ID),
+ ).not.toBeInTheDocument();
+ });
+
+ it('shows AnomalyThreshold component when alert type is anomaly based', () => {
+ renderAlertCondition();
+
+ // Click on anomaly tab to switch to anomaly-based alert
+ const anomalyTab = screen.getByText(ANOMALY_TAB_TEXT);
+ fireEvent.click(anomalyTab);
+
+ expect(screen.getByTestId(ANOMALY_THRESHOLD_TEST_ID)).toBeInTheDocument();
+ expect(screen.queryByTestId(ALERT_THRESHOLD_TEST_ID)).not.toBeInTheDocument();
+ });
+
+ it('switches between threshold and anomaly tabs', () => {
+ renderAlertCondition();
+
+ // Initially shows threshold component
+ expect(screen.getByTestId(ALERT_THRESHOLD_TEST_ID)).toBeInTheDocument();
+
+ // Click anomaly tab
+ const anomalyTab = screen.getByText(ANOMALY_TAB_TEXT);
+ fireEvent.click(anomalyTab);
+
+ // Should show anomaly component
+ expect(screen.getByTestId(ANOMALY_THRESHOLD_TEST_ID)).toBeInTheDocument();
+ expect(screen.queryByTestId(ALERT_THRESHOLD_TEST_ID)).not.toBeInTheDocument();
+
+ // Click threshold tab
+ const thresholdTab = screen.getByText(THRESHOLD_TAB_TEXT);
+ fireEvent.click(thresholdTab);
+
+ // Should show threshold component again
+ expect(screen.getByTestId(ALERT_THRESHOLD_TEST_ID)).toBeInTheDocument();
+ expect(
+ screen.queryByTestId(ANOMALY_THRESHOLD_TEST_ID),
+ ).not.toBeInTheDocument();
+ });
+
+ it('applies active tab styling correctly', () => {
+ renderAlertCondition();
+
+ const thresholdTab = screen.getByText(THRESHOLD_TAB_TEXT);
+ const anomalyTab = screen.getByText(ANOMALY_TAB_TEXT);
+
+ // Threshold tab should be active by default
+ expect(thresholdTab.closest(ACTIVE_TAB_CLASS)).toBeInTheDocument();
+ expect(anomalyTab.closest(ACTIVE_TAB_CLASS)).not.toBeInTheDocument();
+
+ // Click anomaly tab
+ fireEvent.click(anomalyTab);
+
+ // Anomaly tab should be active now
+ expect(anomalyTab.closest(ACTIVE_TAB_CLASS)).toBeInTheDocument();
+ expect(thresholdTab.closest(ACTIVE_TAB_CLASS)).not.toBeInTheDocument();
+ });
+
+ it('shows multiple tabs for METRICS_BASED_ALERT', () => {
+ renderAlertCondition('METRIC_BASED_ALERT');
+
+ // Both tabs should be visible
+ expect(screen.getByText(THRESHOLD_TAB_TEXT)).toBeInTheDocument();
+ expect(screen.getByText(ANOMALY_TAB_TEXT)).toBeInTheDocument();
+ expect(screen.getByTestId(THRESHOLD_VIEW_TEST_ID)).toBeInTheDocument();
+ expect(screen.getByTestId(ANOMALY_VIEW_TEST_ID)).toBeInTheDocument();
+ });
+
+ it('shows multiple tabs for ANOMALY_BASED_ALERT', () => {
+ renderAlertCondition('ANOMALY_BASED_ALERT');
+
+ // Both tabs should be visible
+ expect(screen.getByText(THRESHOLD_TAB_TEXT)).toBeInTheDocument();
+ expect(screen.getByText(ANOMALY_TAB_TEXT)).toBeInTheDocument();
+ expect(screen.getByTestId(THRESHOLD_VIEW_TEST_ID)).toBeInTheDocument();
+ expect(screen.getByTestId(ANOMALY_VIEW_TEST_ID)).toBeInTheDocument();
+ });
+
+ it('shows only threshold tab for LOGS_BASED_ALERT', () => {
+ renderAlertCondition('LOGS_BASED_ALERT');
+
+ // Only threshold tab should be visible
+ expect(screen.getByText(THRESHOLD_TAB_TEXT)).toBeInTheDocument();
+ expect(screen.queryByText(ANOMALY_TAB_TEXT)).not.toBeInTheDocument();
+ expect(screen.getByTestId(THRESHOLD_VIEW_TEST_ID)).toBeInTheDocument();
+ expect(screen.queryByTestId(ANOMALY_VIEW_TEST_ID)).not.toBeInTheDocument();
+ });
+
+ it('shows only threshold tab for TRACES_BASED_ALERT', () => {
+ renderAlertCondition('TRACES_BASED_ALERT');
+
+ // Only threshold tab should be visible
+ expect(screen.getByText(THRESHOLD_TAB_TEXT)).toBeInTheDocument();
+ expect(screen.queryByText(ANOMALY_TAB_TEXT)).not.toBeInTheDocument();
+ expect(screen.getByTestId(THRESHOLD_VIEW_TEST_ID)).toBeInTheDocument();
+ expect(screen.queryByTestId(ANOMALY_VIEW_TEST_ID)).not.toBeInTheDocument();
+ });
+
+ it('shows only threshold tab for EXCEPTIONS_BASED_ALERT', () => {
+ renderAlertCondition('EXCEPTIONS_BASED_ALERT');
+
+ // Only threshold tab should be visible
+ expect(screen.getByText(THRESHOLD_TAB_TEXT)).toBeInTheDocument();
+ expect(screen.queryByText(ANOMALY_TAB_TEXT)).not.toBeInTheDocument();
+ expect(screen.getByTestId(THRESHOLD_VIEW_TEST_ID)).toBeInTheDocument();
+ expect(screen.queryByTestId(ANOMALY_VIEW_TEST_ID)).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AlertThreshold.test.tsx b/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AlertThreshold.test.tsx
new file mode 100644
index 0000000000..dd4b6385f3
--- /dev/null
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AlertThreshold.test.tsx
@@ -0,0 +1,272 @@
+/* eslint-disable @typescript-eslint/no-explicit-any */
+/* eslint-disable react/jsx-props-no-spreading */
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from 'react-query';
+import { MemoryRouter } from 'react-router-dom';
+import { Channels } from 'types/api/channels/getAll';
+
+import { CreateAlertProvider } from '../../context';
+import AlertThreshold from '../AlertThreshold';
+
+jest.mock('uplot', () => {
+ const paths = {
+ spline: jest.fn(),
+ bars: jest.fn(),
+ };
+ const uplotMock: any = jest.fn(() => ({
+ paths,
+ }));
+ uplotMock.paths = paths;
+ return uplotMock;
+});
+
+// Mock the ThresholdItem component
+jest.mock('../ThresholdItem', () => ({
+ __esModule: true,
+ default: function MockThresholdItem({
+ threshold,
+ removeThreshold,
+ showRemoveButton,
+ }: {
+ threshold: Record<string, unknown>;
+ removeThreshold: (id: string) => void;
+ showRemoveButton: boolean;
+ }): JSX.Element {
+ return (
+ <div data-testid={`threshold-item-${threshold.id}`}>
+ <span>{threshold.label as string}</span>
+ {showRemoveButton && (
+ <button
+ type="button"
+ data-testid={`remove-threshold-${threshold.id}`}
+ onClick={(): void => removeThreshold(threshold.id as string)}
+ >
+ Remove
+ </button>
+ )}
+ </div>
+ );
+ },
+}));
+
+// Mock useQueryBuilder hook
+jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
+ useQueryBuilder: (): {
+ currentQuery: {
+ dataSource: string;
+ queryName: string;
+ builder: {
+ queryData: Array<{ queryName: string }>;
+ queryFormulas: Array<{ queryName: string }>;
+ };
+ unit: string;
+ };
+ } => ({
+ currentQuery: {
+ dataSource: 'METRICS',
+ queryName: 'A',
+ builder: {
+ queryData: [{ queryName: 'Query A' }, { queryName: 'Query B' }],
+ queryFormulas: [{ queryName: 'Formula 1' }],
+ },
+ unit: 'bytes',
+ },
+ }),
+}));
+
+// Mock getAllChannels API
+jest.mock('api/channels/getAll', () => ({
+ __esModule: true,
+ default: jest.fn(() =>
+ Promise.resolve({
+ data: [
+ { id: '1', name: 'Email Channel' },
+ { id: '2', name: 'Slack Channel' },
+ ] as Channels[],
+ }),
+ ),
+}));
+
+// Mock alert format categories
+jest.mock('container/NewWidget/RightContainer/alertFomatCategories', () => ({
+ getCategoryByOptionId: jest.fn(() => ({ name: 'bytes' })),
+ getCategorySelectOptionByName: jest.fn(() => [
+ { label: 'Bytes', value: 'bytes' },
+ { label: 'KB', value: 'kb' },
+ ]),
+}));
+
+const TEST_STRINGS = {
+ ADD_THRESHOLD: 'Add Threshold',
+ AT_LEAST_ONCE: 'AT LEAST ONCE',
+ IS_ABOVE: 'IS ABOVE',
+} as const;
+
+const createTestQueryClient = (): QueryClient =>
+ new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ },
+ });
+
+const renderAlertThreshold = (): ReturnType<typeof render> => {
+ const queryClient = createTestQueryClient();
+ return render(
+ <MemoryRouter>
+ <QueryClientProvider client={queryClient}>
+ <CreateAlertProvider>
+ <AlertThreshold />
+ </CreateAlertProvider>
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+};
+
+const verifySelectRenders = (title: string): void => {
+ const select = screen.getByTitle(title);
+ expect(select).toBeInTheDocument();
+};
+
+describe('AlertThreshold', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('renders the main condition sentence', () => {
+ renderAlertThreshold();
+ expect(screen.getByText('Send a notification when')).toBeInTheDocument();
+ expect(screen.getByText('the threshold(s)')).toBeInTheDocument();
+ expect(screen.getByText('during the')).toBeInTheDocument();
+ expect(screen.getByText('Evaluation Window.')).toBeInTheDocument();
+ });
+
+ it('renders query selection dropdown', async () => {
+ renderAlertThreshold();
+
+ await waitFor(() => {
+ const querySelect = screen.getByTitle('A');
+ expect(querySelect).toBeInTheDocument();
+ });
+ });
+
+ it('renders operator selection dropdown', () => {
+ renderAlertThreshold();
+ verifySelectRenders(TEST_STRINGS.IS_ABOVE);
+ });
+
+ it('renders match type selection dropdown', () => {
+ renderAlertThreshold();
+ verifySelectRenders(TEST_STRINGS.AT_LEAST_ONCE);
+ });
+
+ it('renders threshold items', () => {
+ renderAlertThreshold();
+ expect(screen.getByTestId(/threshold-item-/)).toBeInTheDocument();
+ });
+
+ it('renders add threshold button', () => {
+ renderAlertThreshold();
+ expect(screen.getByText(TEST_STRINGS.ADD_THRESHOLD)).toBeInTheDocument();
+ });
+
+ it('adds a new threshold when add button is clicked', () => {
+ renderAlertThreshold();
+
+ const addButton = screen.getByText(TEST_STRINGS.ADD_THRESHOLD);
+ fireEvent.click(addButton);
+
+ // Should now have multiple threshold items
+ const thresholdItems = screen.getAllByTestId(/threshold-item-/);
+ expect(thresholdItems).toHaveLength(2);
+ });
+
+ it('adds correct threshold types based on count', () => {
+ renderAlertThreshold();
+
+ const addButton = screen.getByText(TEST_STRINGS.ADD_THRESHOLD);
+
+ // First addition should add WARNING threshold
+ fireEvent.click(addButton);
+ expect(screen.getByText('WARNING')).toBeInTheDocument();
+
+ // Second addition should add INFO threshold
+ fireEvent.click(addButton);
+ expect(screen.getByText('INFO')).toBeInTheDocument();
+
+ // Third addition should add random threshold
+ fireEvent.click(addButton);
+ expect(screen.getAllByTestId(/threshold-item-/)).toHaveLength(4);
+ });
+
+ it('updates operator when operator dropdown changes', () => {
+ renderAlertThreshold();
+ verifySelectRenders(TEST_STRINGS.IS_ABOVE);
+ });
+
+ it('updates match type when match type dropdown changes', () => {
+ renderAlertThreshold();
+ verifySelectRenders(TEST_STRINGS.AT_LEAST_ONCE);
+ });
+
+ it('shows remove button for non-first thresholds', () => {
+ renderAlertThreshold();
+
+ // Add a threshold
+ const addButton = screen.getByText(TEST_STRINGS.ADD_THRESHOLD);
+ fireEvent.click(addButton);
+
+ // Second threshold should have remove button
+ expect(screen.getByTestId(/remove-threshold-/)).toBeInTheDocument();
+ });
+
+ it('does not show remove button for first threshold', () => {
+ renderAlertThreshold();
+
+ // First threshold should not have remove button
+ expect(screen.queryByTestId(/remove-threshold-/)).not.toBeInTheDocument();
+ });
+
+ it('removes threshold when remove button is clicked', () => {
+ renderAlertThreshold();
+
+ // Add a threshold first
+ const addButton = screen.getByText(TEST_STRINGS.ADD_THRESHOLD);
+ fireEvent.click(addButton);
+
+ // Get the remove button and click it
+ const removeButton = screen.getByTestId(/remove-threshold-/);
+ fireEvent.click(removeButton);
+
+ // Should be back to one threshold
+ expect(screen.getAllByTestId(/threshold-item-/)).toHaveLength(1);
+ });
+
+ it('does not remove threshold if only one remains', () => {
+ renderAlertThreshold();
+
+ // Should only have one threshold initially
+ expect(screen.getAllByTestId(/threshold-item-/)).toHaveLength(1);
+
+ // Try to remove (should not work)
+ const thresholdItems = screen.getAllByTestId(/threshold-item-/);
+ 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();
+
+ // Should have initial critical threshold
+ expect(screen.getByText('CRITICAL')).toBeInTheDocument();
+ verifySelectRenders(TEST_STRINGS.IS_ABOVE);
+ verifySelectRenders(TEST_STRINGS.AT_LEAST_ONCE);
+ });
+});
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AnomalyThreshold.test.tsx b/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AnomalyThreshold.test.tsx
new file mode 100644
index 0000000000..6729519830
--- /dev/null
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AnomalyThreshold.test.tsx
@@ -0,0 +1,89 @@
+/* eslint-disable react/jsx-props-no-spreading */
+/* eslint-disable @typescript-eslint/no-explicit-any */
+import { render, screen } from '@testing-library/react';
+import {
+ INITIAL_ALERT_STATE,
+ INITIAL_ALERT_THRESHOLD_STATE,
+} from 'container/CreateAlertV2/context/constants';
+
+import * as context from '../../context';
+import AnomalyThreshold from '../AnomalyThreshold';
+
+jest.mock('uplot', () => {
+ const paths = {
+ spline: jest.fn(),
+ bars: jest.fn(),
+ };
+ const uplotMock: any = jest.fn(() => ({
+ paths,
+ }));
+ uplotMock.paths = paths;
+ return uplotMock;
+});
+
+const mockSetAlertState = jest.fn();
+const mockSetThresholdState = jest.fn();
+jest.spyOn(context, 'useCreateAlertState').mockReturnValue({
+ alertState: INITIAL_ALERT_STATE,
+ setAlertState: mockSetAlertState,
+ thresholdState: INITIAL_ALERT_THRESHOLD_STATE,
+ setThresholdState: mockSetThresholdState,
+} as any);
+
+// Mock useQueryBuilder hook
+jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
+ useQueryBuilder: (): {
+ currentQuery: {
+ dataSource: string;
+ queryName: string;
+ builder: {
+ queryData: Array<{ queryName: string }>;
+ queryFormulas: Array<{ queryName: string }>;
+ };
+ };
+ } => ({
+ currentQuery: {
+ dataSource: 'METRICS',
+ queryName: 'A',
+ builder: {
+ queryData: [{ queryName: 'Query A' }, { queryName: 'Query B' }],
+ queryFormulas: [{ queryName: 'Formula 1' }],
+ },
+ },
+ }),
+}));
+
+const renderAnomalyThreshold = (): ReturnType<typeof render> =>
+ render(<AnomalyThreshold />);
+
+describe('AnomalyThreshold', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('renders the first condition sentence', () => {
+ renderAnomalyThreshold();
+ expect(screen.getByTestId('notification-text')).toBeInTheDocument();
+ expect(screen.getByTestId('evaluation-window-text')).toBeInTheDocument();
+ expect(screen.getByTestId('evaluation-window-select')).toBeInTheDocument();
+ });
+
+ it('renders the second condition sentence', () => {
+ renderAnomalyThreshold();
+ expect(screen.getByTestId('threshold-text')).toBeInTheDocument();
+ expect(screen.getByTestId('threshold-value-select')).toBeInTheDocument();
+ expect(screen.getByTestId('deviations-text')).toBeInTheDocument();
+ expect(screen.getByTestId('operator-select')).toBeInTheDocument();
+ expect(screen.getByTestId('predicted-data-text')).toBeInTheDocument();
+ expect(screen.getByTestId('match-type-select')).toBeInTheDocument();
+ });
+
+ it('renders the third condition sentence', () => {
+ renderAnomalyThreshold();
+ expect(screen.getByTestId('using-the-text')).toBeInTheDocument();
+ expect(screen.getByTestId('algorithm-select')).toBeInTheDocument();
+ expect(screen.getByTestId('algorithm-with-text')).toBeInTheDocument();
+ expect(screen.getByTestId('seasonality-select')).toBeInTheDocument();
+ expect(screen.getByTestId('seasonality-text')).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/ThresholdItem.test.tsx b/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/ThresholdItem.test.tsx
new file mode 100644
index 0000000000..01fcbf97ce
--- /dev/null
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/ThresholdItem.test.tsx
@@ -0,0 +1,398 @@
+/* eslint-disable @typescript-eslint/no-explicit-any */
+/* eslint-disable react/jsx-props-no-spreading */
+import { fireEvent, render, screen } from '@testing-library/react';
+import { DefaultOptionType } from 'antd/es/select';
+import { Channels } from 'types/api/channels/getAll';
+
+import ThresholdItem from '../ThresholdItem';
+import { ThresholdItemProps } from '../types';
+
+// Mock the enableRecoveryThreshold utility
+jest.mock('../../utils', () => ({
+ enableRecoveryThreshold: jest.fn(() => true),
+}));
+
+const TEST_CONSTANTS = {
+ THRESHOLD_ID: 'test-threshold-1',
+ CRITICAL_LABEL: 'CRITICAL',
+ WARNING_LABEL: 'WARNING',
+ INFO_LABEL: 'INFO',
+ CHANNEL_1: 'channel-1',
+ CHANNEL_2: 'channel-2',
+ CHANNEL_3: 'channel-3',
+ EMAIL_CHANNEL_NAME: 'Email Channel',
+ ENTER_THRESHOLD_NAME: 'Enter threshold name',
+ ENTER_THRESHOLD_VALUE: 'Enter threshold value',
+ ENTER_RECOVERY_THRESHOLD_VALUE: 'Enter recovery threshold value',
+} as const;
+
+const mockThreshold = {
+ id: TEST_CONSTANTS.THRESHOLD_ID,
+ label: TEST_CONSTANTS.CRITICAL_LABEL,
+ thresholdValue: 100,
+ recoveryThresholdValue: 80,
+ unit: 'bytes',
+ channels: [TEST_CONSTANTS.CHANNEL_1],
+ color: '#ff0000',
+};
+
+const mockChannels: Channels[] = [
+ {
+ 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 mockUnits: DefaultOptionType[] = [
+ { label: 'Bytes', value: 'bytes' },
+ { label: 'KB', value: 'kb' },
+ { label: 'MB', value: 'mb' },
+];
+
+const defaultProps: ThresholdItemProps = {
+ threshold: mockThreshold,
+ updateThreshold: jest.fn(),
+ removeThreshold: jest.fn(),
+ showRemoveButton: false,
+ channels: mockChannels,
+ isLoadingChannels: false,
+ units: mockUnits,
+};
+
+const renderThresholdItem = (
+ props: Partial<ThresholdItemProps> = {},
+): ReturnType<typeof render> => {
+ const mergedProps = { ...defaultProps, ...props };
+ return render(<ThresholdItem {...mergedProps} />);
+};
+
+const verifySelectorWidth = (
+ selectorIndex: number,
+ expectedWidth: string,
+): void => {
+ const selectors = screen.getAllByRole('combobox');
+ const selector = selectors[selectorIndex];
+ expect(selector.closest('.ant-select')).toHaveStyle(`width: ${expectedWidth}`);
+};
+
+const showRecoveryThreshold = (): void => {
+ const recoveryButton = screen.getByRole('button', { name: '' });
+ 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
+ expect(unitSelector).toBeDisabled();
+};
+
+describe('ThresholdItem', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('renders threshold indicator with correct color', () => {
+ renderThresholdItem();
+
+ // Find the threshold dot by its class
+ const thresholdDot = document.querySelector('.threshold-dot');
+ expect(thresholdDot).toHaveStyle('background-color: #ff0000');
+ });
+
+ it('renders threshold label input with correct value', () => {
+ renderThresholdItem();
+
+ const labelInput = screen.getByPlaceholderText(
+ TEST_CONSTANTS.ENTER_THRESHOLD_NAME,
+ );
+ expect(labelInput).toHaveValue(TEST_CONSTANTS.CRITICAL_LABEL);
+ });
+
+ it('renders threshold value input with correct value', () => {
+ renderThresholdItem();
+
+ const valueInput = screen.getByPlaceholderText(
+ TEST_CONSTANTS.ENTER_THRESHOLD_VALUE,
+ );
+ expect(valueInput).toHaveValue('100');
+ });
+
+ it('renders unit selector with correct value', () => {
+ renderThresholdItem();
+
+ // Check for the unit selector by looking for the displayed text
+ expect(screen.getByText('Bytes')).toBeInTheDocument();
+ });
+
+ it('renders channels selector with correct value', () => {
+ renderThresholdItem();
+
+ // Check for the channels selector by looking for the displayed text
+ expect(
+ screen.getByText(TEST_CONSTANTS.EMAIL_CHANNEL_NAME),
+ ).toBeInTheDocument();
+ });
+
+ it('updates threshold label when label input changes', () => {
+ const updateThreshold = jest.fn();
+ renderThresholdItem({ updateThreshold });
+
+ const labelInput = screen.getByPlaceholderText(
+ TEST_CONSTANTS.ENTER_THRESHOLD_NAME,
+ );
+ fireEvent.change(labelInput, {
+ target: { value: TEST_CONSTANTS.WARNING_LABEL },
+ });
+
+ expect(updateThreshold).toHaveBeenCalledWith(
+ TEST_CONSTANTS.THRESHOLD_ID,
+ 'label',
+ TEST_CONSTANTS.WARNING_LABEL,
+ );
+ });
+
+ it('updates threshold value when value input changes', () => {
+ const updateThreshold = jest.fn();
+ renderThresholdItem({ updateThreshold });
+
+ const valueInput = screen.getByPlaceholderText(
+ TEST_CONSTANTS.ENTER_THRESHOLD_VALUE,
+ );
+ fireEvent.change(valueInput, { target: { value: '200' } });
+
+ expect(updateThreshold).toHaveBeenCalledWith(
+ TEST_CONSTANTS.THRESHOLD_ID,
+ 'thresholdValue',
+ '200',
+ );
+ });
+
+ it('updates threshold unit when unit selector changes', () => {
+ const updateThreshold = jest.fn();
+ renderThresholdItem({ updateThreshold });
+
+ // Find the unit selector by its role and simulate change
+ const unitSelectors = screen.getAllByRole('combobox');
+ const unitSelector = unitSelectors[0]; // First combobox is the unit selector
+
+ // Simulate clicking to open the dropdown and selecting a value
+ fireEvent.click(unitSelector);
+
+ // The actual change event might not work the same way with Ant Design Select
+ // So we'll just verify the selector is present and can be interacted with
+ expect(unitSelector).toBeInTheDocument();
+ });
+
+ it('updates threshold channels when channels selector changes', () => {
+ const updateThreshold = jest.fn();
+ renderThresholdItem({ updateThreshold });
+
+ // Find the channels selector by its role and simulate change
+ const channelSelectors = screen.getAllByRole('combobox');
+ const channelSelector = channelSelectors[1]; // Second combobox is the channels selector
+
+ // Simulate clicking to open the dropdown
+ fireEvent.click(channelSelector);
+
+ // The actual change event might not work the same way with Ant Design Select
+ // So we'll just verify the selector is present and can be interacted with
+ expect(channelSelector).toBeInTheDocument();
+ });
+
+ it('shows remove button when showRemoveButton is true', () => {
+ renderThresholdItem({ showRemoveButton: true });
+
+ // The remove button is the second button (with circle-x icon)
+ const buttons = screen.getAllByRole('button');
+ expect(buttons).toHaveLength(2); // Recovery button + remove button
+ });
+
+ it('does not show remove button when showRemoveButton is false', () => {
+ renderThresholdItem({ showRemoveButton: false });
+
+ // Only the recovery button should be present
+ const buttons = screen.getAllByRole('button');
+ expect(buttons).toHaveLength(1); // Only recovery button
+ });
+
+ it('calls removeThreshold when remove button is clicked', () => {
+ const removeThreshold = jest.fn();
+ renderThresholdItem({ showRemoveButton: true, removeThreshold });
+
+ // The remove button is the second button (with circle-x icon)
+ const buttons = screen.getAllByRole('button');
+ const removeButton = buttons[1]; // Second button is the remove button
+ fireEvent.click(removeButton);
+
+ expect(removeThreshold).toHaveBeenCalledWith(TEST_CONSTANTS.THRESHOLD_ID);
+ });
+
+ it('shows recovery threshold button when recovery threshold is enabled', () => {
+ renderThresholdItem();
+
+ // The recovery button is the first button (with chart-line icon)
+ const buttons = screen.getAllByRole('button');
+ expect(buttons).toHaveLength(1); // Recovery button
+ });
+
+ it('shows recovery threshold inputs when recovery button is clicked', () => {
+ renderThresholdItem();
+
+ // The recovery button is the first button (with chart-line icon)
+ const buttons = screen.getAllByRole('button');
+ const recoveryButton = buttons[0]; // First button is the recovery button
+ fireEvent.click(recoveryButton);
+
+ expect(screen.getByPlaceholderText('Recovery threshold')).toBeInTheDocument();
+ expect(
+ screen.getByPlaceholderText(TEST_CONSTANTS.ENTER_RECOVERY_THRESHOLD_VALUE),
+ ).toBeInTheDocument();
+ });
+
+ it('updates recovery threshold value when input changes', () => {
+ const updateThreshold = jest.fn();
+ renderThresholdItem({ updateThreshold });
+
+ // Show recovery threshold first
+ const buttons = screen.getAllByRole('button');
+ const recoveryButton = buttons[0]; // First button is the recovery button
+ fireEvent.click(recoveryButton);
+
+ const recoveryValueInput = screen.getByPlaceholderText(
+ TEST_CONSTANTS.ENTER_RECOVERY_THRESHOLD_VALUE,
+ );
+ fireEvent.change(recoveryValueInput, { target: { value: '90' } });
+
+ expect(updateThreshold).toHaveBeenCalledWith(
+ TEST_CONSTANTS.THRESHOLD_ID,
+ 'recoveryThresholdValue',
+ '90',
+ );
+ });
+
+ it('disables unit selector when no units are available', () => {
+ renderThresholdItem({ units: [] });
+ verifyUnitSelectorDisabled();
+ });
+
+ it('shows tooltip when no units are available', () => {
+ renderThresholdItem({ units: [] });
+
+ // The tooltip should be present when hovering over disabled unit selector
+ verifyUnitSelectorDisabled();
+ });
+
+ it('renders channels as multiple select options', () => {
+ renderThresholdItem();
+
+ // Check that channels are rendered as multiple select
+ expect(
+ screen.getByText(TEST_CONSTANTS.EMAIL_CHANNEL_NAME),
+ ).toBeInTheDocument();
+
+ // Should be able to select multiple channels
+ const channelSelectors = screen.getAllByRole('combobox');
+ const channelSelector = channelSelectors[1]; // Second combobox is the channels selector
+ fireEvent.change(channelSelector, {
+ target: { value: [TEST_CONSTANTS.CHANNEL_1, TEST_CONSTANTS.CHANNEL_2] },
+ });
+ });
+
+ it('handles empty threshold values correctly', () => {
+ const emptyThreshold = {
+ ...mockThreshold,
+ label: '',
+ thresholdValue: 0,
+ unit: '',
+ channels: [],
+ };
+
+ renderThresholdItem({ threshold: emptyThreshold });
+
+ expect(screen.getByPlaceholderText('Enter threshold name')).toHaveValue('');
+ expect(screen.getByPlaceholderText('Enter threshold value')).toHaveValue('0');
+ });
+
+ it('renders with correct input widths', () => {
+ renderThresholdItem();
+
+ const labelInput = screen.getByPlaceholderText(
+ TEST_CONSTANTS.ENTER_THRESHOLD_NAME,
+ );
+ const valueInput = screen.getByPlaceholderText(
+ TEST_CONSTANTS.ENTER_THRESHOLD_VALUE,
+ );
+
+ expect(labelInput).toHaveStyle('width: 260px');
+ expect(valueInput).toHaveStyle('width: 210px');
+ });
+
+ it('renders channels selector with correct width', () => {
+ renderThresholdItem();
+ verifySelectorWidth(1, '260px');
+ });
+
+ it('renders unit selector with correct width', () => {
+ renderThresholdItem();
+ verifySelectorWidth(0, '150px');
+ });
+
+ it('handles loading channels state', () => {
+ renderThresholdItem({ isLoadingChannels: true });
+ verifyComponentRendersWithLoading();
+ });
+
+ it('renders recovery threshold with correct initial value', () => {
+ renderThresholdItem();
+ showRecoveryThreshold();
+
+ const recoveryValueInput = screen.getByPlaceholderText(
+ TEST_CONSTANTS.ENTER_RECOVERY_THRESHOLD_VALUE,
+ );
+ expect(recoveryValueInput).toHaveValue('80');
+ });
+
+ it('renders recovery threshold label as disabled', () => {
+ renderThresholdItem();
+ showRecoveryThreshold();
+
+ const recoveryLabelInput = screen.getByPlaceholderText('Recovery threshold');
+ expect(recoveryLabelInput).toBeDisabled();
+ });
+
+ it('renders correct channel options', () => {
+ renderThresholdItem();
+
+ // Check that channels are rendered
+ expect(
+ screen.getByText(TEST_CONSTANTS.EMAIL_CHANNEL_NAME),
+ ).toBeInTheDocument();
+
+ // Should be able to select different channels
+ const channelSelectors = screen.getAllByRole('combobox');
+ const channelSelector = channelSelectors[1]; // Second combobox is the channels selector
+ fireEvent.change(channelSelector, { target: { value: 'channel-2' } });
+ expect(screen.getByText('Slack Channel')).toBeInTheDocument();
+ });
+
+ it('handles threshold without channels', () => {
+ const thresholdWithoutChannels = {
+ ...mockThreshold,
+ channels: [],
+ };
+
+ renderThresholdItem({ threshold: thresholdWithoutChannels });
+
+ // Should render channels selector without selected values
+ const channelSelectors = screen.getAllByRole('combobox');
+ expect(channelSelectors).toHaveLength(2); // Should have both unit and channel selectors
+ });
+});
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/constants.ts b/frontend/src/container/CreateAlertV2/AlertCondition/constants.ts
new file mode 100644
index 0000000000..7ca78ae3ca
--- /dev/null
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/constants.ts
@@ -0,0 +1,5 @@
+export const THRESHOLD_TAB_TOOLTIP =
+ 'An alert is triggered when the metric crosses a threshold.';
+
+export const ANOMALY_TAB_TOOLTIP =
+ 'An alert is triggered whenever the metric deviates from an expected pattern.';
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/index.tsx b/frontend/src/container/CreateAlertV2/AlertCondition/index.tsx
new file mode 100644
index 0000000000..f33f67e32b
--- /dev/null
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/index.tsx
@@ -0,0 +1,3 @@
+import AlertCondition from './AlertCondition';
+
+export default AlertCondition;
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/styles.scss b/frontend/src/container/CreateAlertV2/AlertCondition/styles.scss
new file mode 100644
index 0000000000..bdde72598d
--- /dev/null
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/styles.scss
@@ -0,0 +1,277 @@
+.alert-condition-container {
+ margin: 0 16px;
+ margin-top: 24px;
+
+ .alert-condition {
+ display: flex;
+ align-items: center;
+ margin-left: 12px;
+ margin-top: 24px;
+
+ .alert-condition-tabs {
+ display: flex;
+ border-radius: 2px;
+ border: 1px solid var(--bg-slate-400);
+ background: var(--bg-ink-300);
+ flex-direction: row;
+ border-bottom: none;
+ margin-bottom: -1px;
+
+ .explorer-view-option {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-direction: row;
+ border: none;
+ padding: 9px;
+ box-shadow: none;
+ border-radius: 0px;
+ border-left: 0.5px solid var(--bg-slate-400);
+ border-bottom: 0.5px solid var(--bg-slate-400);
+ width: 120px;
+ height: 36px;
+
+ gap: 8px;
+
+ &.active-tab {
+ background-color: var(--bg-ink-500);
+ border-bottom: none;
+
+ &:hover {
+ background-color: var(--bg-ink-500) !important;
+ }
+ }
+
+ &:disabled {
+ background-color: var(--bg-ink-300);
+ opacity: 0.6;
+ }
+
+ &:first-child {
+ border-left: 1px solid transparent;
+ }
+
+ &:hover {
+ background-color: transparent !important;
+ border-left: 1px solid transparent !important;
+ color: var(--bg-vanilla-100);
+ }
+ }
+ }
+ }
+}
+
+.alert-threshold-container,
+.anomaly-threshold-container {
+ padding: 24px;
+ padding-right: 72px;
+ background-color: var(--bg-ink-500);
+ border: 1px solid var(--bg-slate-400);
+ width: fit-content;
+
+ .alert-condition-sentences {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+
+ .alert-condition-sentence {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+ flex-wrap: wrap;
+
+ .sentence-text {
+ color: var(--text-vanilla-400);
+ font-size: 14px;
+ line-height: 1.5;
+ }
+
+ .ant-select {
+ width: 240px !important;
+
+ .ant-select-selector {
+ background-color: var(--bg-ink-300);
+ border: 1px solid var(--bg-slate-400);
+ color: var(--text-vanilla-400);
+ font-family: 'Space Mono';
+
+ &:hover {
+ border-color: var(--bg-vanilla-300);
+ }
+
+ &:focus {
+ border-color: var(--bg-vanilla-300);
+ box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
+ }
+ }
+
+ .ant-select-selection-item {
+ color: var(--bg-vanilla-100);
+ }
+
+ .ant-select-arrow {
+ color: var(--bg-vanilla-400);
+ }
+ }
+ }
+ }
+
+ .thresholds-section {
+ margin-top: 16px;
+ margin-left: 24px;
+
+ .threshold-item {
+ display: flex;
+ flex-direction: column;
+ gap: 0;
+ margin-bottom: 16px;
+
+ .threshold-row {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+ margin-bottom: 2px;
+
+ .threshold-indicator {
+ .threshold-dot {
+ width: 12px;
+ height: 12px;
+ border-radius: 50%;
+ flex-shrink: 0;
+ }
+ }
+
+ .threshold-controls {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+
+ .ant-input {
+ background-color: var(--bg-ink-400);
+ border: 1px solid var(--bg-slate-400);
+ color: var(--bg-vanilla-100);
+ height: 32px;
+
+ &::placeholder {
+ font-family: 'Space Mono';
+ }
+
+ &:hover {
+ border-color: var(--bg-vanilla-300);
+ }
+
+ &:focus {
+ border-color: var(--bg-vanilla-300);
+ box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
+ }
+ }
+
+ .ant-select {
+ .ant-select-selector {
+ background-color: var(--bg-ink-400);
+ border: 1px solid var(--bg-slate-400);
+ color: var(--bg-vanilla-100);
+ height: 32px;
+
+ &:hover {
+ border-color: var(--bg-vanilla-300);
+ }
+
+ &:focus {
+ border-color: var(--bg-vanilla-300);
+ box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
+ }
+
+ .ant-select-selection-placeholder {
+ font-family: 'Space Mono';
+ }
+ }
+
+ .ant-select-selection-item {
+ color: var(--bg-vanilla-100);
+ }
+
+ .ant-select-arrow {
+ color: var(--bg-vanilla-400);
+ }
+ }
+
+ .icon-btn {
+ color: var(--bg-vanilla-400);
+ border: 1px solid var(--bg-slate-400);
+ border-radius: 4px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ }
+ }
+
+ .recovery-threshold-input-group {
+ display: flex;
+ align-items: center;
+ gap: 0;
+ margin-left: 28px;
+
+ .recovery-threshold-label {
+ pointer-events: none;
+ cursor: default;
+ }
+
+ .recovery-threshold-btn {
+ pointer-events: none;
+ cursor: default;
+ color: var(--bg-vanilla-400);
+ background-color: var(--bg-ink-400) !important;
+ border: 1px solid var(--bg-slate-400);
+ border-radius: 4px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+
+ .ant-input {
+ background-color: var(--bg-ink-400);
+ border: 1px solid var(--bg-slate-400);
+ color: var(--bg-vanilla-100);
+ height: 32px;
+
+ &::placeholder {
+ font-family: 'Space Mono';
+ }
+
+ &:hover {
+ border-color: var(--bg-vanilla-300);
+ }
+
+ &:focus {
+ border-color: var(--bg-vanilla-300);
+ box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
+ }
+ }
+ }
+ }
+
+ .add-threshold-btn {
+ margin-top: 8px;
+ border: 1px dashed var(--bg-slate-400);
+ color: var(--bg-vanilla-300);
+ background-color: transparent;
+ border-radius: 4px;
+ height: 32px;
+ padding: 0 16px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ &:hover {
+ border-color: var(--bg-vanilla-300);
+ color: var(--bg-vanilla-100);
+ }
+
+ .anticon {
+ margin-right: 8px;
+ }
+ }
+ }
+}
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/types.ts b/frontend/src/container/CreateAlertV2/AlertCondition/types.ts
new file mode 100644
index 0000000000..382955b58a
--- /dev/null
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/types.ts
@@ -0,0 +1,23 @@
+import { DefaultOptionType } from 'antd/es/select';
+import { Channels } from 'types/api/channels/getAll';
+
+import { Threshold } from '../context/types';
+
+export type UpdateThreshold = {
+ (thresholdId: string, field: 'channels', value: string[]): void;
+ (
+ thresholdId: string,
+ field: Exclude<keyof Threshold, 'channels'>,
+ value: string,
+ ): void;
+};
+
+export interface ThresholdItemProps {
+ threshold: Threshold;
+ updateThreshold: UpdateThreshold;
+ removeThreshold: (thresholdId: string) => void;
+ showRemoveButton: boolean;
+ channels: Channels[];
+ isLoadingChannels: boolean;
+ units: DefaultOptionType[];
+}
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/utils.tsx b/frontend/src/container/CreateAlertV2/AlertCondition/utils.tsx
new file mode 100644
index 0000000000..af4d89c47f
--- /dev/null
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/utils.tsx
@@ -0,0 +1,46 @@
+import { BaseOptionType, DefaultOptionType, SelectProps } from 'antd/es/select';
+import { getInvolvedQueriesInTraceOperator } from 'components/QueryBuilderV2/QueryV2/TraceOperator/utils/utils';
+import { Y_AXIS_CATEGORIES } from 'components/YAxisUnitSelector/constants';
+import { getSelectedQueryOptions } from 'container/FormAlertRules/utils';
+import { Query } from 'types/api/queryBuilder/queryBuilderData';
+import { EQueryType } from 'types/common/dashboard';
+
+export function getQueryNames(currentQuery: Query): BaseOptionType[] {
+ const involvedQueriesInTraceOperator = getInvolvedQueriesInTraceOperator(
+ currentQuery.builder.queryTraceOperator,
+ );
+ const queryConfig: Record<EQueryType, () => SelectProps['options']> = {
+ [EQueryType.QUERY_BUILDER]: () => [
+ ...(getSelectedQueryOptions(currentQuery.builder.queryData)?.filter(
+ (option) =>
+ !involvedQueriesInTraceOperator.includes(option.value as string),
+ ) || []),
+ ...(getSelectedQueryOptions(currentQuery.builder.queryFormulas) || []),
+ ...(getSelectedQueryOptions(currentQuery.builder.queryTraceOperator) || []),
+ ],
+ [EQueryType.PROM]: () => getSelectedQueryOptions(currentQuery.promql),
+ [EQueryType.CLICKHOUSE]: () =>
+ getSelectedQueryOptions(currentQuery.clickhouse_sql),
+ };
+
+ return queryConfig[currentQuery.queryType]?.() || [];
+}
+
+export function getCategoryByOptionId(id: string): string | undefined {
+ return Y_AXIS_CATEGORIES.find((category) =>
+ category.units.some((unit) => unit.id === id),
+ )?.name;
+}
+
+export function getCategorySelectOptionByName(
+ name: string,
+): DefaultOptionType[] {
+ return (
+ Y_AXIS_CATEGORIES.find((category) => category.name === name)?.units.map(
+ (unit) => ({
+ label: unit.name,
+ value: unit.id,
+ }),
+ ) || []
+ );
+}
diff --git a/frontend/src/container/CreateAlertV2/CreateAlertHeader/CreateAlertHeader.tsx b/frontend/src/container/CreateAlertV2/CreateAlertHeader/CreateAlertHeader.tsx
index af6ad2612c..8ad31b7c59 100644
--- a/frontend/src/container/CreateAlertV2/CreateAlertHeader/CreateAlertHeader.tsx
+++ b/frontend/src/container/CreateAlertV2/CreateAlertHeader/CreateAlertHeader.tsx
@@ -1,5 +1,7 @@
import './styles.scss';
+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
+import { useCallback, useMemo } from 'react';
import { Labels } from 'types/api/alerts/def';
import { useCreateAlertState } from '../context';
@@ -8,6 +10,29 @@ import LabelsInput from './LabelsInput';
function CreateAlertHeader(): JSX.Element {
const { alertState, setAlertState } = useCreateAlertState();
+ const { currentQuery } = useQueryBuilder();
+
+ const groupByLabels = useMemo(() => {
+ const labels = new Array<string>();
+ currentQuery.builder.queryData.forEach((query) => {
+ query.groupBy.forEach((groupBy) => {
+ labels.push(groupBy.key);
+ });
+ });
+ return labels;
+ }, [currentQuery]);
+
+ // If the label key is a group by label, then it is not allowed to be used as a label key
+ const validateLabelsKey = useCallback(
+ (key: string): string | null => {
+ if (groupByLabels.includes(key)) {
+ return `Cannot use ${key} as a key`;
+ }
+ return null;
+ },
+ [groupByLabels],
+ );
+
return (
<div className="alert-header">
<div className="alert-header__tab-bar">
@@ -38,6 +63,7 @@ function CreateAlertHeader(): JSX.Element {
onLabelsChange={(labels: Labels): void =>
setAlertState({ type: 'SET_ALERT_LABELS', payload: labels })
}
+ validateLabelsKey={validateLabelsKey}
/>
</div>
</div>
diff --git a/frontend/src/container/CreateAlertV2/CreateAlertHeader/LabelsInput.tsx b/frontend/src/container/CreateAlertV2/CreateAlertHeader/LabelsInput.tsx
index 5b4bbfdb56..31c72eca7d 100644
--- a/frontend/src/container/CreateAlertV2/CreateAlertHeader/LabelsInput.tsx
+++ b/frontend/src/container/CreateAlertV2/CreateAlertHeader/LabelsInput.tsx
@@ -7,6 +7,7 @@ import { LabelInputState, LabelsInputProps } from './types';
function LabelsInput({
labels,
onLabelsChange,
+ validateLabelsKey,
}: LabelsInputProps): JSX.Element {
const { notifications } = useNotifications();
const [inputState, setInputState] = useState<LabelInputState>({
@@ -38,6 +39,13 @@ function LabelsInput({
});
return;
}
+ const error = validateLabelsKey(key.trim());
+ if (error) {
+ notifications.error({
+ message: error,
+ });
+ return;
+ }
// Add the label immediately
const newLabels = {
...labels,
@@ -55,6 +63,13 @@ function LabelsInput({
});
return;
}
+ const error = validateLabelsKey(inputState.key.trim());
+ if (error) {
+ notifications.error({
+ message: error,
+ });
+ return;
+ }
setInputState((prev) => ({ ...prev, isKeyInput: false }));
}
} else if (inputState.value.trim()) {
@@ -74,7 +89,7 @@ function LabelsInput({
setInputState({ key: '', value: '', isKeyInput: true });
}
},
- [inputState, labels, notifications, onLabelsChange],
+ [inputState, labels, notifications, onLabelsChange, validateLabelsKey],
);
const handleInputChange = useCallback(
diff --git a/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/LabelsInput.test.tsx b/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/LabelsInput.test.tsx
index ed040ae684..15cb6a083c 100644
--- a/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/LabelsInput.test.tsx
+++ b/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/LabelsInput.test.tsx
@@ -10,10 +10,12 @@ jest.mock('@ant-design/icons', () => ({
}));
const mockOnLabelsChange = jest.fn();
+const mockValidateLabelsKey = jest.fn().mockReturnValue(null);
const defaultProps: LabelsInputProps = {
labels: {},
onLabelsChange: mockOnLabelsChange,
+ validateLabelsKey: mockValidateLabelsKey,
};
const ADD_LABELS_TEXT = '+ Add labels';
@@ -33,6 +35,7 @@ const renderLabelsInput = (
describe('LabelsInput', () => {
beforeEach(() => {
jest.clearAllMocks();
+ mockValidateLabelsKey.mockReturnValue(null); // Reset validation to always pass
});
describe('Initial Rendering', () => {
@@ -483,7 +486,11 @@ describe('LabelsInput', () => {
// Simulate parent component updating labels
const firstLabels = { severity: 'high' };
rerender(
- <LabelsInput labels={firstLabels} onLabelsChange={mockOnLabelsChange} />,
+ <LabelsInput
+ labels={firstLabels}
+ onLabelsChange={mockOnLabelsChange}
+ validateLabelsKey={mockValidateLabelsKey}
+ />,
);
// Add second label
diff --git a/frontend/src/container/CreateAlertV2/CreateAlertHeader/types.ts b/frontend/src/container/CreateAlertV2/CreateAlertHeader/types.ts
index da7b6f9f89..e40ca9d88e 100644
--- a/frontend/src/container/CreateAlertV2/CreateAlertHeader/types.ts
+++ b/frontend/src/container/CreateAlertV2/CreateAlertHeader/types.ts
@@ -3,6 +3,7 @@ import { Labels } from 'types/api/alerts/def';
export interface LabelsInputProps {
labels: Labels;
onLabelsChange: (labels: Labels) => void;
+ validateLabelsKey: (key: string) => string | null;
}
export interface LabelInputState {
diff --git a/frontend/src/container/CreateAlertV2/CreateAlertV2.tsx b/frontend/src/container/CreateAlertV2/CreateAlertV2.tsx
index bdfededd13..589a18fc6c 100644
--- a/frontend/src/container/CreateAlertV2/CreateAlertV2.tsx
+++ b/frontend/src/container/CreateAlertV2/CreateAlertV2.tsx
@@ -4,6 +4,7 @@ import { initialQueriesMap } from 'constants/queryBuilder';
import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
+import AlertCondition from './AlertCondition';
import { CreateAlertProvider } from './context';
import CreateAlertHeader from './CreateAlertHeader';
import QuerySection from './QuerySection';
@@ -20,6 +21,7 @@ function CreateAlertV2({
<CreateAlertProvider>
<CreateAlertHeader />
<QuerySection />
+ <AlertCondition />
</CreateAlertProvider>
</div>
);
diff --git a/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsx b/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsx
index ae5876bc6a..97ca2980ef 100644
--- a/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsx
+++ b/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsx
@@ -6,19 +6,24 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useState } from 'react';
import { useSelector } from 'react-redux';
import { AppState } from 'store/reducers';
+import { AlertDef } from 'types/api/alerts/def';
import { EQueryType } from 'types/common/dashboard';
import { GlobalReducer } from 'types/reducer/globalTime';
-function ChartPreview(): JSX.Element {
+export interface ChartPreviewProps {
+ alertDef: AlertDef;
+}
+
+function ChartPreview({ alertDef }: ChartPreviewProps): JSX.Element {
const { currentQuery, panelType, stagedQuery } = useQueryBuilder();
+ const { thresholdState, alertState } = useCreateAlertState();
const { selectedTime: globalSelectedInterval } = useSelector<
AppState,
GlobalReducer
>((state) => state.globalTime);
const [, setQueryStatus] = useState<string>('');
- const { alertDef } = useCreateAlertState();
- const yAxisUnit = currentQuery.unit || '';
+ const yAxisUnit = alertState.yAxisUnit || '';
const renderQBChartPreview = (): JSX.Element => (
<ChartPreviewComponent
@@ -36,6 +41,7 @@ function ChartPreview(): JSX.Element {
graphType={panelType || PANEL_TYPES.TIME_SERIES}
setQueryStatus={setQueryStatus}
showSideLegend
+ additionalThresholds={thresholdState.thresholds}
/>
);
@@ -55,6 +61,7 @@ function ChartPreview(): JSX.Element {
graphType={panelType || PANEL_TYPES.TIME_SERIES}
setQueryStatus={setQueryStatus}
showSideLegend
+ additionalThresholds={thresholdState.thresholds}
/>
);
diff --git a/frontend/src/container/CreateAlertV2/QuerySection/QuerySection.tsx b/frontend/src/container/CreateAlertV2/QuerySection/QuerySection.tsx
index 644be2153d..ec6312923d 100644
--- a/frontend/src/container/CreateAlertV2/QuerySection/QuerySection.tsx
+++ b/frontend/src/container/CreateAlertV2/QuerySection/QuerySection.tsx
@@ -2,6 +2,7 @@ import './styles.scss';
import { Button } from 'antd';
import classNames from 'classnames';
+import YAxisUnitSelector from 'components/YAxisUnitSelector';
import { PANEL_TYPES } from 'constants/queryBuilder';
import QuerySectionComponent from 'container/FormAlertRules/QuerySection';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
@@ -11,10 +12,19 @@ import { AlertTypes } from 'types/api/alerts/alertTypes';
import { useCreateAlertState } from '../context';
import Stepper from '../Stepper';
import ChartPreview from './ChartPreview';
+import { buildAlertDefForChartPreview } from './utils';
function QuerySection(): JSX.Element {
const { currentQuery, handleRunQuery } = useQueryBuilder();
- const { alertType, setAlertType, alertDef } = useCreateAlertState();
+ const {
+ alertState,
+ setAlertState,
+ alertType,
+ setAlertType,
+ thresholdState,
+ } = useCreateAlertState();
+
+ const alertDef = buildAlertDefForChartPreview({ alertType, thresholdState });
const tabs = [
{
@@ -45,7 +55,13 @@ function QuerySection(): JSX.Element {
stepNumber={1}
label="Define the query you want to set an alert on"
/>
- <ChartPreview />
+ <ChartPreview alertDef={alertDef} />
+ <YAxisUnitSelector
+ value={alertState.yAxisUnit}
+ onChange={(value): void => {
+ setAlertState({ type: 'SET_Y_AXIS_UNIT', payload: value });
+ }}
+ />
<div className="query-section-tabs">
<div className="query-section-query-actions">
{tabs.map((tab) => (
diff --git a/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsx b/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsx
index f2c560c754..0689a6920a 100644
--- a/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsx
+++ b/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsx
@@ -2,16 +2,21 @@
/* eslint-disable react/destructuring-assignment */
import { render, screen } from '@testing-library/react';
import { PANEL_TYPES } from 'constants/queryBuilder';
+import {
+ INITIAL_ALERT_STATE,
+ INITIAL_ALERT_THRESHOLD_STATE,
+} from 'container/CreateAlertV2/context/constants';
+import { buildInitialAlertDef } from 'container/CreateAlertV2/context/utils';
import { QueryClient, QueryClientProvider } from 'react-query';
import { Provider } from 'react-redux';
import { MemoryRouter } from 'react-router-dom';
import store from 'store';
+import { AlertTypes } from 'types/api/alerts/alertTypes';
import { EQueryType } from 'types/common/dashboard';
import { CreateAlertProvider } from '../../context';
import ChartPreview from '../ChartPreview/ChartPreview';
-// Constants for duplicate strings
const REQUESTS_PER_SEC = 'requests/sec';
const CHART_PREVIEW_NAME = 'Chart Preview';
const QUERY_TYPE_TEST_ID = 'query-type';
@@ -109,13 +114,28 @@ const mockUseQueryBuilder = {
},
};
+const mockAlertDef = buildInitialAlertDef(AlertTypes.METRICS_BASED_ALERT);
+
+jest.mock('../../context', () => ({
+ ...jest.requireActual('../../context'),
+ useCreateAlertState: (): any => ({
+ alertState: {
+ ...INITIAL_ALERT_STATE,
+ yAxisUnit: REQUESTS_PER_SEC,
+ },
+ thresholdState: INITIAL_ALERT_THRESHOLD_STATE,
+ setAlertState: jest.fn(),
+ setThresholdState: jest.fn(),
+ }),
+}));
+
const renderChartPreview = (): ReturnType<typeof render> =>
render(
<Provider store={store}>
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<CreateAlertProvider>
- <ChartPreview />
+ <ChartPreview alertDef={mockAlertDef} />
</CreateAlertProvider>
</MemoryRouter>
</QueryClientProvider>
diff --git a/frontend/src/container/CreateAlertV2/QuerySection/styles.scss b/frontend/src/container/CreateAlertV2/QuerySection/styles.scss
index 3faed92151..25efc08557 100644
--- a/frontend/src/container/CreateAlertV2/QuerySection/styles.scss
+++ b/frontend/src/container/CreateAlertV2/QuerySection/styles.scss
@@ -70,6 +70,17 @@
}
}
+ .y-axis-unit-selector-component {
+ margin-top: 16px;
+
+ .ant-select {
+ .ant-select-selector {
+ border: 1px solid var(--bg-slate-400);
+ background: var(--bg-ink-300);
+ }
+ }
+ }
+
.chart-preview-container {
margin-right: 4px;
.alert-chart-container {
diff --git a/frontend/src/container/CreateAlertV2/QuerySection/utils.tsx b/frontend/src/container/CreateAlertV2/QuerySection/utils.tsx
new file mode 100644
index 0000000000..29dfed0838
--- /dev/null
+++ b/frontend/src/container/CreateAlertV2/QuerySection/utils.tsx
@@ -0,0 +1,28 @@
+import { AlertDetectionTypes } from 'container/FormAlertRules';
+import { AlertTypes } from 'types/api/alerts/alertTypes';
+import { AlertDef } from 'types/api/alerts/def';
+
+import { AlertThresholdState } from '../context/types';
+import { buildInitialAlertDef } from '../context/utils';
+
+export function buildAlertDefForChartPreview({
+ alertType,
+ thresholdState,
+}: {
+ alertType: AlertTypes;
+ thresholdState: AlertThresholdState;
+}): AlertDef {
+ const initialAlertDef = buildInitialAlertDef(alertType);
+
+ return {
+ ...initialAlertDef,
+ ruleType:
+ alertType === AlertTypes.ANOMALY_BASED_ALERT
+ ? AlertDetectionTypes.ANOMALY_DETECTION_ALERT
+ : AlertDetectionTypes.THRESHOLD_ALERT,
+ condition: {
+ ...initialAlertDef.condition,
+ targetUnit: thresholdState.thresholds?.[0].unit,
+ },
+ };
+}
diff --git a/frontend/src/container/CreateAlertV2/context/constants.ts b/frontend/src/container/CreateAlertV2/context/constants.ts
index 989251873c..b138213227 100644
--- a/frontend/src/container/CreateAlertV2/context/constants.ts
+++ b/frontend/src/container/CreateAlertV2/context/constants.ts
@@ -1,7 +1,117 @@
-import { AlertState } from './types';
+import { Color } from '@signozhq/design-tokens';
+import getRandomColor from 'lib/getRandomColor';
+import { v4 } from 'uuid';
+
+import {
+ AlertState,
+ AlertThresholdMatchType,
+ AlertThresholdOperator,
+ AlertThresholdState,
+ Algorithm,
+ Seasonality,
+ Threshold,
+ TimeDuration,
+} from './types';
export const INITIAL_ALERT_STATE: AlertState = {
name: '',
description: '',
labels: {},
+ yAxisUnit: undefined,
+};
+
+export const INITIAL_CRITICAL_THRESHOLD: Threshold = {
+ id: v4(),
+ label: 'CRITICAL',
+ thresholdValue: 0,
+ recoveryThresholdValue: 0,
+ unit: '',
+ channels: [],
+ color: Color.BG_SAKURA_500,
+};
+
+export const INITIAL_WARNING_THRESHOLD: Threshold = {
+ id: v4(),
+ label: 'WARNING',
+ thresholdValue: 0,
+ recoveryThresholdValue: 0,
+ unit: '',
+ channels: [],
+ color: Color.BG_AMBER_500,
+};
+
+export const INITIAL_INFO_THRESHOLD: Threshold = {
+ id: v4(),
+ label: 'INFO',
+ thresholdValue: 0,
+ recoveryThresholdValue: 0,
+ unit: '',
+ channels: [],
+ color: Color.BG_ROBIN_500,
+};
+
+export const INITIAL_RANDOM_THRESHOLD: Threshold = {
+ id: v4(),
+ label: '',
+ thresholdValue: 0,
+ recoveryThresholdValue: 0,
+ unit: '',
+ channels: [],
+ color: getRandomColor(),
};
+
+export const INITIAL_ALERT_THRESHOLD_STATE: AlertThresholdState = {
+ selectedQuery: 'A',
+ operator: AlertThresholdOperator.IS_ABOVE,
+ matchType: AlertThresholdMatchType.AT_LEAST_ONCE,
+ evaluationWindow: TimeDuration.FIVE_MINUTES,
+ algorithm: Algorithm.STANDARD,
+ seasonality: Seasonality.HOURLY,
+ thresholds: [INITIAL_CRITICAL_THRESHOLD],
+};
+
+export const THRESHOLD_OPERATOR_OPTIONS = [
+ { value: AlertThresholdOperator.IS_ABOVE, label: 'IS ABOVE' },
+ { value: AlertThresholdOperator.IS_BELOW, label: 'IS BELOW' },
+ { value: AlertThresholdOperator.IS_EQUAL_TO, label: 'IS EQUAL TO' },
+ { value: AlertThresholdOperator.IS_NOT_EQUAL_TO, label: 'IS NOT EQUAL TO' },
+];
+
+export const ANOMALY_THRESHOLD_OPERATOR_OPTIONS = [
+ { value: AlertThresholdOperator.IS_ABOVE, label: 'IS ABOVE' },
+ { value: AlertThresholdOperator.IS_BELOW, label: 'IS BELOW' },
+ { value: AlertThresholdOperator.ABOVE_BELOW, label: 'ABOVE/BELOW' },
+];
+
+export const THRESHOLD_MATCH_TYPE_OPTIONS = [
+ { value: AlertThresholdMatchType.AT_LEAST_ONCE, label: 'AT LEAST ONCE' },
+ { value: AlertThresholdMatchType.ALL_THE_TIME, label: 'ALL THE TIME' },
+ { value: AlertThresholdMatchType.ON_AVERAGE, label: 'ON AVERAGE' },
+ { value: AlertThresholdMatchType.IN_TOTAL, label: 'IN TOTAL' },
+ { value: AlertThresholdMatchType.LAST, label: 'LAST' },
+];
+
+export const ANOMALY_THRESHOLD_MATCH_TYPE_OPTIONS = [
+ { value: AlertThresholdMatchType.AT_LEAST_ONCE, label: 'AT LEAST ONCE' },
+ { value: AlertThresholdMatchType.ALL_THE_TIME, label: 'ALL THE TIME' },
+];
+
+export const ANOMALY_TIME_DURATION_OPTIONS = [
+ { value: TimeDuration.FIVE_MINUTES, label: '5 minutes' },
+ { value: TimeDuration.TEN_MINUTES, label: '10 minutes' },
+ { value: TimeDuration.FIFTEEN_MINUTES, label: '15 minutes' },
+ { value: TimeDuration.ONE_HOUR, label: '1 hour' },
+ { value: TimeDuration.THREE_HOURS, label: '3 hours' },
+ { value: TimeDuration.FOUR_HOURS, label: '4 hours' },
+ { value: TimeDuration.TWENTY_FOUR_HOURS, label: '24 hours' },
+];
+
+export const ANOMALY_ALGORITHM_OPTIONS = [
+ { value: Algorithm.STANDARD, label: 'Standard' },
+];
+
+export const ANOMALY_SEASONALITY_OPTIONS = [
+ { value: Seasonality.HOURLY, label: 'Hourly' },
+ { value: Seasonality.DAILY, label: 'Daily' },
+ { value: Seasonality.WEEKLY, label: 'Weekly' },
+];
diff --git a/frontend/src/container/CreateAlertV2/context/index.tsx b/frontend/src/container/CreateAlertV2/context/index.tsx
index 4f1d4d50d7..31fe57a2eb 100644
--- a/frontend/src/container/CreateAlertV2/context/index.tsx
+++ b/frontend/src/container/CreateAlertV2/context/index.tsx
@@ -5,18 +5,22 @@ import {
createContext,
useCallback,
useContext,
+ useEffect,
useMemo,
useReducer,
useState,
} from 'react';
import { useLocation } from 'react-router-dom';
import { AlertTypes } from 'types/api/alerts/alertTypes';
-import { AlertDef } from 'types/api/alerts/def';
-import { INITIAL_ALERT_STATE } from './constants';
+import {
+ INITIAL_ALERT_STATE,
+ INITIAL_ALERT_THRESHOLD_STATE,
+} from './constants';
import { ICreateAlertContextProps, ICreateAlertProviderProps } from './types';
import {
alertCreationReducer,
+ alertThresholdReducer,
buildInitialAlertDef,
getInitialAlertTypeFromURL,
} from './utils';
@@ -51,7 +55,6 @@ export function CreateAlertProvider(
const [alertType, setAlertType] = useState<AlertTypes>(() =>
getInitialAlertTypeFromURL(queryParams, currentQuery),
);
- const [alertDef] = useState<AlertDef>(buildInitialAlertDef(alertType));
const handleAlertTypeChange = useCallback(
(value: AlertTypes): void => {
@@ -72,15 +75,27 @@ export function CreateAlertProvider(
[redirectWithQueryBuilderData],
);
+ const [thresholdState, setThresholdState] = useReducer(
+ alertThresholdReducer,
+ INITIAL_ALERT_THRESHOLD_STATE,
+ );
+
+ useEffect(() => {
+ setThresholdState({
+ type: 'RESET',
+ });
+ }, [alertType]);
+
const contextValue: ICreateAlertContextProps = useMemo(
() => ({
alertState,
setAlertState,
alertType,
setAlertType: handleAlertTypeChange,
- alertDef,
+ thresholdState,
+ setThresholdState,
}),
- [alertState, alertType, handleAlertTypeChange, alertDef],
+ [alertState, alertType, handleAlertTypeChange, thresholdState],
);
return (
diff --git a/frontend/src/container/CreateAlertV2/context/types.ts b/frontend/src/container/CreateAlertV2/context/types.ts
index ee90b03b88..6b5db05de6 100644
--- a/frontend/src/container/CreateAlertV2/context/types.ts
+++ b/frontend/src/container/CreateAlertV2/context/types.ts
@@ -1,13 +1,14 @@
import { Dispatch } from 'react';
import { AlertTypes } from 'types/api/alerts/alertTypes';
-import { AlertDef, Labels } from 'types/api/alerts/def';
+import { Labels } from 'types/api/alerts/def';
export interface ICreateAlertContextProps {
alertState: AlertState;
setAlertState: Dispatch<CreateAlertAction>;
alertType: AlertTypes;
setAlertType: Dispatch<AlertTypes>;
- alertDef: AlertDef;
+ thresholdState: AlertThresholdState;
+ setThresholdState: Dispatch<AlertThresholdAction>;
}
export interface ICreateAlertProviderProps {
@@ -25,9 +26,78 @@ export interface AlertState {
name: string;
description: string;
labels: Labels;
+ yAxisUnit: string | undefined;
}
export type CreateAlertAction =
| { type: 'SET_ALERT_NAME'; payload: string }
| { type: 'SET_ALERT_DESCRIPTION'; payload: string }
- | { type: 'SET_ALERT_LABELS'; payload: Labels };
+ | { type: 'SET_ALERT_LABELS'; payload: Labels }
+ | { type: 'SET_Y_AXIS_UNIT'; payload: string | undefined };
+
+export interface Threshold {
+ id: string;
+ label: string;
+ thresholdValue: number;
+ recoveryThresholdValue: number;
+ unit: string;
+ channels: string[];
+ color: string;
+}
+
+export enum AlertThresholdOperator {
+ IS_ABOVE = '1',
+ IS_BELOW = '2',
+ IS_EQUAL_TO = '3',
+ IS_NOT_EQUAL_TO = '4',
+ ABOVE_BELOW = '7',
+}
+
+export enum AlertThresholdMatchType {
+ AT_LEAST_ONCE = '1',
+ ALL_THE_TIME = '2',
+ ON_AVERAGE = '3',
+ IN_TOTAL = '4',
+ LAST = '5',
+}
+
+export interface AlertThresholdState {
+ selectedQuery: string;
+ operator: AlertThresholdOperator;
+ matchType: AlertThresholdMatchType;
+ evaluationWindow: string;
+ algorithm: string;
+ seasonality: string;
+ thresholds: Threshold[];
+}
+
+export enum TimeDuration {
+ ONE_MINUTE = '1m0s',
+ FIVE_MINUTES = '5m0s',
+ TEN_MINUTES = '10m0s',
+ FIFTEEN_MINUTES = '15m0s',
+ ONE_HOUR = '1h0m0s',
+ THREE_HOURS = '3h0m0s',
+ FOUR_HOURS = '4h0m0s',
+ TWENTY_FOUR_HOURS = '24h0m0s',
+}
+
+export enum Algorithm {
+ STANDARD = 'standard',
+}
+
+export enum Seasonality {
+ HOURLY = 'hourly',
+ DAILY = 'daily',
+ WEEKLY = 'weekly',
+}
+
+export type AlertThresholdAction =
+ | { type: 'SET_SELECTED_QUERY'; payload: string }
+ | { type: 'SET_OPERATOR'; payload: AlertThresholdOperator }
+ | { type: 'SET_MATCH_TYPE'; payload: AlertThresholdMatchType }
+ | { type: 'SET_EVALUATION_WINDOW'; payload: string }
+ | { type: 'SET_ALGORITHM'; payload: string }
+ | { type: 'SET_SEASONALITY'; payload: string }
+ | { type: 'SET_THRESHOLDS'; payload: Threshold[] }
+ | { type: 'RESET' };
diff --git a/frontend/src/container/CreateAlertV2/context/utils.tsx b/frontend/src/container/CreateAlertV2/context/utils.tsx
index 9c427a6e9a..aa3bf8b910 100644
--- a/frontend/src/container/CreateAlertV2/context/utils.tsx
+++ b/frontend/src/container/CreateAlertV2/context/utils.tsx
@@ -11,7 +11,13 @@ import { AlertDef } from 'types/api/alerts/def';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
-import { AlertState, CreateAlertAction } from './types';
+import { INITIAL_ALERT_THRESHOLD_STATE } from './constants';
+import {
+ AlertState,
+ AlertThresholdAction,
+ AlertThresholdState,
+ CreateAlertAction,
+} from './types';
export const alertCreationReducer = (
state: AlertState,
@@ -33,6 +39,11 @@ export const alertCreationReducer = (
...state,
labels: action.payload,
};
+ case 'SET_Y_AXIS_UNIT':
+ return {
+ ...state,
+ yAxisUnit: action.payload,
+ };
default:
return state;
}
@@ -79,3 +90,23 @@ export function getInitialAlertTypeFromURL(
? (alertTypeFromURL as AlertTypes)
: getInitialAlertType(currentQuery);
}
+
+export const alertThresholdReducer = (
+ state: AlertThresholdState,
+ action: AlertThresholdAction,
+): AlertThresholdState => {
+ switch (action.type) {
+ case 'SET_SELECTED_QUERY':
+ return { ...state, selectedQuery: action.payload };
+ case 'SET_OPERATOR':
+ return { ...state, operator: action.payload };
+ case 'SET_MATCH_TYPE':
+ return { ...state, matchType: action.payload };
+ case 'SET_THRESHOLDS':
+ return { ...state, thresholds: action.payload };
+ case 'RESET':
+ return INITIAL_ALERT_THRESHOLD_STATE;
+ default:
+ return state;
+ }
+};
diff --git a/frontend/src/container/FormAlertRules/ChartPreview/index.tsx b/frontend/src/container/FormAlertRules/ChartPreview/index.tsx
index 4390da8f9f..068103de1d 100644
--- a/frontend/src/container/FormAlertRules/ChartPreview/index.tsx
+++ b/frontend/src/container/FormAlertRules/ChartPreview/index.tsx
@@ -8,6 +8,8 @@ import { FeatureKeys } from 'constants/features';
import { QueryParams } from 'constants/query';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import AnomalyAlertEvaluationView from 'container/AnomalyAlertEvaluationView';
+import { INITIAL_CRITICAL_THRESHOLD } from 'container/CreateAlertV2/context/constants';
+import { Threshold } from 'container/CreateAlertV2/context/types';
import { getLocalStorageGraphVisibilityState } from 'container/GridCardLayout/GridCard/utils';
import GridPanelSwitch from 'container/GridPanelSwitch';
import { populateMultipleResults } from 'container/NewWidget/LeftContainer/WidgetGraph/util';
@@ -51,7 +53,7 @@ import { getTimeRange } from 'utils/getTimeRange';
import { AlertDetectionTypes } from '..';
import { ChartContainer } from './styles';
-import { getThresholdLabel } from './utils';
+import { getThresholds } from './utils';
export interface ChartPreviewProps {
name: string;
@@ -66,6 +68,7 @@ export interface ChartPreviewProps {
yAxisUnit: string;
setQueryStatus?: (status: string) => void;
showSideLegend?: boolean;
+ additionalThresholds?: Threshold[];
}
// eslint-disable-next-line sonarjs/cognitive-complexity
@@ -82,10 +85,26 @@ function ChartPreview({
yAxisUnit,
setQueryStatus,
showSideLegend = false,
+ additionalThresholds,
}: ChartPreviewProps): JSX.Element | null {
const { t } = useTranslation('alerts');
const dispatch = useDispatch();
- const threshold = alertDef?.condition.target || 0;
+ const thresholds: Threshold[] = useMemo(
+ () =>
+ additionalThresholds || [
+ {
+ ...INITIAL_CRITICAL_THRESHOLD,
+ thresholdValue: alertDef?.condition.target || 0,
+ unit: alertDef?.condition.targetUnit || '',
+ },
+ ],
+ [
+ additionalThresholds,
+ alertDef?.condition.target,
+ alertDef?.condition.targetUnit,
+ ],
+ );
+
const [minTimeScale, setMinTimeScale] = useState<number>();
const [maxTimeScale, setMaxTimeScale] = useState<number>();
const [graphVisibility, setGraphVisibility] = useState<boolean[]>([]);
@@ -264,24 +283,7 @@ function ChartPreview({
maxTimeScale,
isDarkMode,
onDragSelect,
- thresholds: [
- {
- index: '0', // no impact
- keyIndex: 0,
- moveThreshold: (): void => {},
- selectedGraph: PANEL_TYPES.TIME_SERIES, // no impact
- thresholdValue: threshold,
- thresholdLabel: `${t(
- 'preview_chart_threshold_label',
- )} (y=${getThresholdLabel(
- optionName,
- threshold,
- alertDef?.condition.targetUnit,
- yAxisUnit,
- )})`,
- thresholdUnit: alertDef?.condition.targetUnit,
- },
- ],
+ thresholds: getThresholds(thresholds, t, optionName, yAxisUnit),
softMax: null,
softMin: null,
panelType: graphType,
@@ -303,10 +305,9 @@ function ChartPreview({
maxTimeScale,
isDarkMode,
onDragSelect,
- threshold,
+ thresholds,
t,
optionName,
- alertDef?.condition.targetUnit,
graphType,
timezone.value,
currentQuery,
@@ -386,6 +387,7 @@ ChartPreview.defaultProps = {
alertDef: undefined,
setQueryStatus: (): void => {},
showSideLegend: false,
+ additionalThresholds: undefined,
};
export default ChartPreview;
diff --git a/frontend/src/container/FormAlertRules/ChartPreview/utils.ts b/frontend/src/container/FormAlertRules/ChartPreview/utils.ts
index 1fc2a2e247..d79ebf98d2 100644
--- a/frontend/src/container/FormAlertRules/ChartPreview/utils.ts
+++ b/frontend/src/container/FormAlertRules/ChartPreview/utils.ts
@@ -1,3 +1,7 @@
+import { Color } from '@signozhq/design-tokens';
+import { PANEL_TYPES } from 'constants/queryBuilder';
+import { Threshold } from 'container/CreateAlertV2/context/types';
+import { ThresholdProps } from 'container/NewWidget/RightContainer/Threshold/types';
import {
BooleanFormats,
DataFormats,
@@ -6,6 +10,7 @@ import {
ThroughputFormats,
TimeFormats,
} from 'container/NewWidget/RightContainer/types';
+import { TFunction } from 'i18next';
import {
dataFormatConfig,
@@ -83,3 +88,57 @@ interface IUnit {
sourceUnit?: string;
targetUnit?: string;
}
+
+export const getThresholds = (
+ thresholds: Threshold[],
+ t: TFunction,
+ optionName: string,
+ yAxisUnit: string,
+): ThresholdProps[] => {
+ const thresholdsToReturn = new Array<ThresholdProps>();
+
+ thresholds.forEach((threshold, index) => {
+ // Push main threshold
+ const mainThreshold = {
+ index: index.toString(),
+ keyIndex: index,
+ moveThreshold: (): void => {},
+ selectedGraph: PANEL_TYPES.TIME_SERIES,
+ thresholdValue: threshold.thresholdValue,
+ thresholdLabel:
+ threshold.label ||
+ `${t('preview_chart_threshold_label')} (y=${getThresholdLabel(
+ optionName,
+ threshold.thresholdValue,
+ threshold.unit,
+ yAxisUnit,
+ )})`,
+ thresholdUnit: threshold.unit,
+ thresholdColor: threshold.color || Color.TEXT_SAKURA_500,
+ };
+ thresholdsToReturn.push(mainThreshold);
+
+ // Push recovery threshold
+ if (threshold.recoveryThresholdValue) {
+ const recoveryThreshold = {
+ index: (thresholds.length + index).toString(),
+ keyIndex: thresholds.length + index,
+ moveThreshold: (): void => {},
+ selectedGraph: PANEL_TYPES.TIME_SERIES, // no impact
+ thresholdValue: threshold.recoveryThresholdValue,
+ thresholdLabel: threshold.label
+ ? `${threshold.label} (Recovery)`
+ : `${t('preview_chart_threshold_label')} (y=${getThresholdLabel(
+ optionName,
+ threshold.thresholdValue,
+ threshold.unit,
+ yAxisUnit,
+ )})`,
+ thresholdUnit: threshold.unit,
+ thresholdColor: threshold.color || Color.TEXT_SAKURA_500,
+ };
+ thresholdsToReturn.push(recoveryThreshold);
+ }
+ });
+ return thresholdsToReturn;
+};