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.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
chore: alert type selection page improvements (#9724)
Amlan Kumar Nandyf2ef42bd7ff3
diff --git a/frontend/public/locales/en-GB/titles.json b/frontend/public/locales/en-GB/titles.jsonindex f5ce505de3..6e41568697 100644--- a/frontend/public/locales/en-GB/titles.json+++ b/frontend/public/locales/en-GB/titles.json@@ -45,6 +45,7 @@"DEFAULT": "Open source Observability Platform | SigNoz","ALERT_HISTORY": "SigNoz | Alert Rule History","ALERT_OVERVIEW": "SigNoz | Alert Rule Overview",+ "ALERT_TYPE_SELECTION": "SigNoz | Select Alert Type","INFRASTRUCTURE_MONITORING_HOSTS": "SigNoz | Infra Monitoring","INFRASTRUCTURE_MONITORING_KUBERNETES": "SigNoz | Infra Monitoring","METER_EXPLORER": "SigNoz | Meter Explorer",diff --git a/frontend/src/AppRoutes/routes.ts b/frontend/src/AppRoutes/routes.tsindex 2a33a4b720..5536ee67b1 100644--- a/frontend/src/AppRoutes/routes.ts+++ b/frontend/src/AppRoutes/routes.ts@@ -1,4 +1,5 @@import ROUTES from 'constants/routes';+import AlertTypeSelectionPage from 'pages/AlertTypeSelection';import MessagingQueues from 'pages/MessagingQueues';import MeterExplorer from 'pages/MeterExplorer';import { RouteProps } from 'react-router-dom';@@ -198,6 +199,13 @@ const routes: AppRoutes[] = [isPrivate: true,key: 'LIST_ALL_ALERT',},+ {+ path: ROUTES.ALERT_TYPE_SELECTION,+ exact: true,+ component: AlertTypeSelectionPage,+ isPrivate: true,+ key: 'ALERT_TYPE_SELECTION',+ },{path: ROUTES.ALERTS_NEW,exact: true,diff --git a/frontend/src/constants/query.ts b/frontend/src/constants/query.tsindex 5e5237c329..2fa5bf7f7c 100644--- a/frontend/src/constants/query.ts+++ b/frontend/src/constants/query.ts@@ -51,4 +51,6 @@ export enum QueryParams {thresholds = 'thresholds',selectedExplorerView = 'selectedExplorerView',variables = 'variables',+ version = 'version',+ showNewCreateAlertsPage = 'showNewCreateAlertsPage',}diff --git a/frontend/src/constants/routes.ts b/frontend/src/constants/routes.tsindex f46cb41c33..9699937389 100644--- a/frontend/src/constants/routes.ts+++ b/frontend/src/constants/routes.ts@@ -27,6 +27,7 @@ const ROUTES = {ALERTS_NEW: '/alerts/new',ALERT_HISTORY: '/alerts/history',ALERT_OVERVIEW: '/alerts/overview',+ ALERT_TYPE_SELECTION: '/alerts/type-selection',ALL_CHANNELS: '/settings/channels',CHANNELS_NEW: '/settings/channels/new',CHANNELS_EDIT: '/settings/channels/edit/:channelId',diff --git a/frontend/src/container/CreateAlertRule/AlertRuleDocumentationRedirection.test.tsx b/frontend/src/container/CreateAlertRule/AlertRuleDocumentationRedirection.test.tsxindex daa68df3ad..3f1205f5a5 100644--- a/frontend/src/container/CreateAlertRule/AlertRuleDocumentationRedirection.test.tsx+++ b/frontend/src/container/CreateAlertRule/AlertRuleDocumentationRedirection.test.tsx@@ -1,24 +1,12 @@import ROUTES from 'constants/routes';import * as usePrefillAlertConditions from 'container/FormAlertRules/usePrefillAlertConditions';+import AlertTypeSelectionPage from 'pages/AlertTypeSelection';import CreateAlertPage from 'pages/CreateAlert';import { act, fireEvent, render } from 'tests/test-utils';import { AlertTypes } from 'types/api/alerts/alertTypes';import { ALERT_TYPE_TO_TITLE, ALERT_TYPE_URL_MAP } from './constants';-jest.mock('react-router-dom', () => ({- ...jest.requireActual('react-router-dom'),- useLocation: (): { pathname: string } => ({- pathname: `${process.env.FRONTEND_API_ENDPOINT}${ROUTES.ALERTS_NEW}`,- }),-}));--jest.mock('hooks/useSafeNavigate', () => ({- useSafeNavigate: (): any => ({- safeNavigate: jest.fn(),- }),-}));-jest.spyOn(usePrefillAlertConditions, 'usePrefillAlertConditions').mockReturnValue({@@ -66,13 +54,20 @@ describe('Alert rule documentation redirection', () => {window.open = mockWindowOpen;});+ jest.mock('react-router-dom', () => ({+ ...jest.requireActual('react-router-dom'),+ useLocation: (): { pathname: string } => ({+ pathname: `${process.env.FRONTEND_API_ENDPOINT}${ROUTES.ALERT_TYPE_SELECTION}`,+ }),+ }));+beforeEach(() => {act(() => {renderResult = render(- <CreateAlertPage />,+ <AlertTypeSelectionPage />,{},{- initialRoute: ROUTES.ALERTS_NEW,+ initialRoute: ROUTES.ALERT_TYPE_SELECTION,},);});@@ -117,18 +112,20 @@ describe('Alert rule documentation redirection', () => {expect(mockWindowOpen).toHaveBeenCalledTimes(alertTypeCount);});+});+describe('Create alert page redirection', () => {Object.values(AlertTypes).filter((type) => type !== AlertTypes.ANOMALY_BASED_ALERT).forEach((alertType) => {it(`should redirect to create alert page for ${alertType} and "Check an example alert" should redirect to the correct documentation`, () => {- const { getByTestId, getByRole } = renderResult;-- const alertTypeLink = getByTestId(`alert-type-card-${alertType}`);-- act(() => {- fireEvent.click(alertTypeLink);- });+ const { getByRole } = render(+ <CreateAlertPage />,+ {},+ {+ initialRoute: `${ROUTES.ALERTS_NEW}?alertType=${alertType}`,+ },+ );act(() => {fireEvent.click(diff --git a/frontend/src/container/CreateAlertRule/__tests__/CreateAlertRule.test.tsx b/frontend/src/container/CreateAlertRule/__tests__/CreateAlertRule.test.tsxnew file mode 100644index 0000000000..9fc5e1b5e7--- /dev/null+++ b/frontend/src/container/CreateAlertRule/__tests__/CreateAlertRule.test.tsx@@ -0,0 +1,131 @@+import { render, screen } from '@testing-library/react';+import { QueryParams } from 'constants/query';+import { initialQueriesMap } from 'constants/queryBuilder';+import * as useCompositeQueryParamHooks from 'hooks/queryBuilder/useGetCompositeQueryParam';+import * as useUrlQueryHooks from 'hooks/useUrlQuery';+import { AlertTypes } from 'types/api/alerts/alertTypes';+import { DataSource } from 'types/common/queryBuilder';++import CreateAlertRule from '../index';++jest.mock('container/FormAlertRules', () => ({+ __esModule: true,+ default: function MockFormAlertRules({+ alertType,+ }: {+ alertType: AlertTypes;+ }): JSX.Element {+ return (+ <div>+ <h1>Form Alert Rules</h1>+ <p>{alertType}</p>+ </div>+ );+ },+ AlertDetectionTypes: {+ THRESHOLD_ALERT: 'threshold_rule',+ ANOMALY_DETECTION_ALERT: 'anomaly_rule',+ },+}));+jest.mock('container/CreateAlertV2', () => ({+ __esModule: true,+ default: function MockCreateAlertV2(): JSX.Element {+ return <div>Create Alert V2</div>;+ },+}));++const useCompositeQueryParamSpy = jest.spyOn(+ useCompositeQueryParamHooks,+ 'useGetCompositeQueryParam',+);+const useUrlQuerySpy = jest.spyOn(useUrlQueryHooks, 'default');++const mockSetUrlQuery = jest.fn();+const mockToString = jest.fn();+const mockGetUrlQuery = jest.fn();++const FORM_ALERT_RULES_TEXT = 'Form Alert Rules';+const CREATE_ALERT_V2_TEXT = 'Create Alert V2';++describe('CreateAlertRule', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ useUrlQuerySpy.mockReturnValue(({+ set: mockSetUrlQuery,+ toString: mockToString,+ get: mockGetUrlQuery,+ } as Partial<URLSearchParams>) as URLSearchParams);+ useCompositeQueryParamSpy.mockReturnValue(initialQueriesMap.metrics);+ });++ it('should render v1 flow when showNewCreateAlertsPage is false', () => {+ mockGetUrlQuery.mockReturnValue(null);+ render(<CreateAlertRule />);+ expect(screen.getByText(FORM_ALERT_RULES_TEXT)).toBeInTheDocument();+ });++ it('should render v2 flow when showNewCreateAlertsPage is true', () => {+ mockGetUrlQuery.mockImplementation((key: string) => {+ if (key === QueryParams.showNewCreateAlertsPage) {+ return 'true';+ }+ return null;+ });+ render(<CreateAlertRule />);+ expect(screen.getByText(CREATE_ALERT_V2_TEXT)).toBeInTheDocument();+ });++ it('should render v1 flow when ruleType is anomaly_rule even if showNewCreateAlertsPage is true', () => {+ mockGetUrlQuery.mockImplementation((key: string) => {+ if (key === QueryParams.showNewCreateAlertsPage) {+ return 'true';+ }+ if (key === QueryParams.ruleType) {+ return 'anomaly_rule';+ }+ return null;+ });+ render(<CreateAlertRule />);+ expect(screen.getByText(FORM_ALERT_RULES_TEXT)).toBeInTheDocument();+ expect(screen.queryByText(CREATE_ALERT_V2_TEXT)).not.toBeInTheDocument();+ });++ it('should use alertType from URL when provided', () => {+ mockGetUrlQuery.mockImplementation((key: string) => {+ if (key === QueryParams.alertType) {+ return AlertTypes.LOGS_BASED_ALERT;+ }+ return null;+ });+ render(<CreateAlertRule />);+ expect(screen.getByText(FORM_ALERT_RULES_TEXT)).toBeInTheDocument();+ expect(screen.getByText(AlertTypes.LOGS_BASED_ALERT)).toBeInTheDocument();+ });++ it('should use alertType from compositeQuery dataSource when alertType is not in URL', () => {+ mockGetUrlQuery.mockReturnValue(null);+ useCompositeQueryParamSpy.mockReturnValue({+ ...initialQueriesMap.metrics,+ builder: {+ ...initialQueriesMap.metrics.builder,+ queryData: [+ {+ ...initialQueriesMap.metrics.builder.queryData[0],+ dataSource: DataSource.TRACES,+ },+ ],+ },+ });+ render(<CreateAlertRule />);+ expect(screen.getByText(FORM_ALERT_RULES_TEXT)).toBeInTheDocument();+ expect(screen.getByText(AlertTypes.TRACES_BASED_ALERT)).toBeInTheDocument();+ });++ it('should default to METRICS_BASED_ALERT when no alertType and no compositeQuery', () => {+ mockGetUrlQuery.mockReturnValue(null);+ useCompositeQueryParamSpy.mockReturnValue(null);+ render(<CreateAlertRule />);+ expect(screen.getByText(FORM_ALERT_RULES_TEXT)).toBeInTheDocument();+ expect(screen.getByText(AlertTypes.METRICS_BASED_ALERT)).toBeInTheDocument();+ });+});diff --git a/frontend/src/container/CreateAlertRule/index.tsx b/frontend/src/container/CreateAlertRule/index.tsxindex b502dd0971..48e3815ae8 100644--- a/frontend/src/container/CreateAlertRule/index.tsx+++ b/frontend/src/container/CreateAlertRule/index.tsx@@ -1,133 +1,49 @@-import { Form, Row } from 'antd';-import logEvent from 'api/common/logEvent';+import { Form } from 'antd';import { ENTITY_VERSION_V5 } from 'constants/app';import { QueryParams } from 'constants/query';import CreateAlertV2 from 'container/CreateAlertV2';import FormAlertRules, { AlertDetectionTypes } from 'container/FormAlertRules';-import { ThresholdProps } from 'container/NewWidget/RightContainer/Threshold/types';import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';-import history from 'lib/history';-import { useEffect, useState } from 'react';-import { useLocation } from 'react-router-dom';+import useUrlQuery from 'hooks/useUrlQuery';+import { useMemo } from 'react';import { AlertTypes } from 'types/api/alerts/alertTypes';import { AlertDef } from 'types/api/alerts/def';import { ALERT_TYPE_VS_SOURCE_MAPPING } from './config';-import {- alertDefaults,- anamolyAlertDefaults,- exceptionAlertDefaults,- logAlertDefaults,- traceAlertDefaults,-} from './defaults';-import SelectAlertType from './SelectAlertType';+import { ALERTS_VALUES_MAP } from './defaults';function CreateRules(): JSX.Element {- const [initValues, setInitValues] = useState<AlertDef | null>(null);-- const location = useLocation();- const queryParams = new URLSearchParams(location.search);- const alertTypeFromURL = queryParams.get(QueryParams.ruleType);- const version = queryParams.get('version');- const alertTypeFromParams =- alertTypeFromURL === AlertDetectionTypes.ANOMALY_DETECTION_ALERT- ? AlertTypes.ANOMALY_BASED_ALERT- : queryParams.get(QueryParams.alertType);-- const { thresholds } = (location.state as {- thresholds: ThresholdProps[];- }) || {- thresholds: null,- };-- const compositeQuery = useGetCompositeQueryParam();- function getAlertTypeFromDataSource(): AlertTypes | null {- if (!compositeQuery) {- return null;- }- const dataSource = compositeQuery?.builder?.queryData[0]?.dataSource;-- return ALERT_TYPE_VS_SOURCE_MAPPING[dataSource];- }-- const [alertType, setAlertType] = useState<AlertTypes>(- (alertTypeFromParams as AlertTypes) || getAlertTypeFromDataSource(),- );-const [formInstance] = Form.useForm();+ const compositeQuery = useGetCompositeQueryParam();+ const queryParams = useUrlQuery();- const onSelectType = (typ: AlertTypes): void => {- setAlertType(typ);-- switch (typ) {- case AlertTypes.LOGS_BASED_ALERT:- setInitValues(logAlertDefaults);- break;- case AlertTypes.TRACES_BASED_ALERT:- setInitValues(traceAlertDefaults);- break;- case AlertTypes.EXCEPTIONS_BASED_ALERT:- setInitValues(exceptionAlertDefaults);- break;- case AlertTypes.ANOMALY_BASED_ALERT:- setInitValues({- ...anamolyAlertDefaults,- version: version || ENTITY_VERSION_V5,- ruleType: AlertDetectionTypes.ANOMALY_DETECTION_ALERT,- });- break;- default:- setInitValues({- ...alertDefaults,- version: version || ENTITY_VERSION_V5,- ruleType: AlertDetectionTypes.THRESHOLD_ALERT,- });- }-- queryParams.set(- QueryParams.alertType,- typ === AlertTypes.ANOMALY_BASED_ALERT- ? AlertTypes.METRICS_BASED_ALERT- : typ,- );+ const ruleTypeFromURL = queryParams.get(QueryParams.ruleType);+ const alertTypeFromURL = queryParams.get(QueryParams.alertType);+ const version = queryParams.get(QueryParams.version);+ const showNewCreateAlertsPageFlag =+ queryParams.get(QueryParams.showNewCreateAlertsPage) === 'true';- if (- typ === AlertTypes.ANOMALY_BASED_ALERT ||- alertTypeFromURL === AlertDetectionTypes.ANOMALY_DETECTION_ALERT- ) {- queryParams.set(- QueryParams.ruleType,- AlertDetectionTypes.ANOMALY_DETECTION_ALERT,- );- } else {- queryParams.set(QueryParams.ruleType, AlertDetectionTypes.THRESHOLD_ALERT);+ const alertType = useMemo(() => {+ if (ruleTypeFromURL === AlertDetectionTypes.ANOMALY_DETECTION_ALERT) {+ return AlertTypes.ANOMALY_BASED_ALERT;}-- const generatedUrl = `${location.pathname}?${queryParams.toString()}`;- history.replace(generatedUrl, {- thresholds,- });- };-- useEffect(() => {- if (alertType) {- onSelectType(alertType);- } else {- logEvent('Alert: New alert data source selection page visited', {});+ if (!alertTypeFromURL) {+ const dataSource = compositeQuery?.builder.queryData?.[0]?.dataSource;+ if (dataSource) {+ return ALERT_TYPE_VS_SOURCE_MAPPING[dataSource];+ }+ return AlertTypes.METRICS_BASED_ALERT;}- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [alertType]);-- if (!initValues) {- return (- <Row wrap={false}>- <SelectAlertType onSelect={onSelectType} />- </Row>- );- }-- const showNewCreateAlertsPageFlag =- queryParams.get('showNewCreateAlertsPage') === 'true';+ return alertTypeFromURL as AlertTypes;+ }, [alertTypeFromURL, ruleTypeFromURL, compositeQuery?.builder.queryData]);++ const initialAlertValue: AlertDef = useMemo(+ () => ({+ ...ALERTS_VALUES_MAP[alertType],+ version: version || ENTITY_VERSION_V5,+ }),+ [alertType, version],+ );if (showNewCreateAlertsPageFlag &&@@ -140,7 +56,7 @@ function CreateRules(): JSX.Element {<FormAlertRulesalertType={alertType}formInstance={formInstance}- initialValue={initValues}+ initialValue={initialAlertValue}ruleId=""/>);diff --git a/frontend/src/container/FormAlertRules/index.tsx b/frontend/src/container/FormAlertRules/index.tsxindex 11ba8c2430..0098156212 100644--- a/frontend/src/container/FormAlertRules/index.tsx+++ b/frontend/src/container/FormAlertRules/index.tsx@@ -230,16 +230,18 @@ function FormAlertRules({};useEffect(() => {- const ruleType =- detectionMethod === AlertDetectionTypes.ANOMALY_DETECTION_ALERT- ? AlertDetectionTypes.ANOMALY_DETECTION_ALERT- : AlertDetectionTypes.THRESHOLD_ALERT;+ if (detectionMethod) {+ const ruleType =+ detectionMethod === AlertDetectionTypes.ANOMALY_DETECTION_ALERT+ ? AlertDetectionTypes.ANOMALY_DETECTION_ALERT+ : AlertDetectionTypes.THRESHOLD_ALERT;- queryParams.set(QueryParams.ruleType, ruleType);+ queryParams.set(QueryParams.ruleType, ruleType);- const generatedUrl = `${location.pathname}?${queryParams.toString()}`;+ const generatedUrl = `${location.pathname}?${queryParams.toString()}`;- safeNavigate(generatedUrl);+ safeNavigate(generatedUrl);+ }// eslint-disable-next-line react-hooks/exhaustive-deps}, [detectionMethod]);diff --git a/frontend/src/container/ListAlertRules/ListAlert.tsx b/frontend/src/container/ListAlertRules/ListAlert.tsxindex 5743efcbff..075e200320 100644--- a/frontend/src/container/ListAlertRules/ListAlert.tsx+++ b/frontend/src/container/ListAlertRules/ListAlert.tsx@@ -29,8 +29,8 @@ import useComponentPermission from 'hooks/useComponentPermission';import useDebouncedFn from 'hooks/useDebouncedFunction';import useInterval from 'hooks/useInterval';import { useNotifications } from 'hooks/useNotifications';+import { useSafeNavigate } from 'hooks/useSafeNavigate';import useUrlQuery from 'hooks/useUrlQuery';-import history from 'lib/history';import { mapQueryDataFromApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataFromApi';import { useAppContext } from 'providers/App/App';import { useCallback, useState } from 'react';@@ -50,6 +50,7 @@ const { Search } = Input;function ListAlert({ allAlertRules, refetch }: ListAlertProps): JSX.Element {const { t } = useTranslation('common');+ const { safeNavigate } = useSafeNavigate();const { user } = useAppContext();const [addNewAlert, action] = useComponentPermission(['add_new_alert', 'action'],@@ -112,7 +113,8 @@ function ListAlert({ allAlertRules, refetch }: ListAlertProps): JSX.Element {number: allAlertRules?.length,layout: 'new',});- history.push(`${ROUTES.ALERTS_NEW}?showNewCreateAlertsPage=true`);+ params.set(QueryParams.showNewCreateAlertsPage, 'true');+ safeNavigate(`${ROUTES.ALERT_TYPE_SELECTION}?${params.toString()}`);// eslint-disable-next-line react-hooks/exhaustive-deps}, []);@@ -121,7 +123,7 @@ function ListAlert({ allAlertRules, refetch }: ListAlertProps): JSX.Element {number: allAlertRules?.length,layout: 'classic',});- history.push(ROUTES.ALERTS_NEW);+ safeNavigate(ROUTES.ALERT_TYPE_SELECTION);// eslint-disable-next-line react-hooks/exhaustive-deps}, []);@@ -161,7 +163,7 @@ function ListAlert({ allAlertRules, refetch }: ListAlertProps): JSX.Element {if (openInNewTab) {window.open(`${ROUTES.ALERT_OVERVIEW}?${params.toString()}`, '_blank');} else {- history.push(`${ROUTES.ALERT_OVERVIEW}?${params.toString()}`);+ safeNavigate(`${ROUTES.ALERT_OVERVIEW}?${params.toString()}`);}};@@ -190,7 +192,7 @@ function ListAlert({ allAlertRules, refetch }: ListAlertProps): JSX.Element {setTimeout(() => {const clonedAlert = refetchData.payload[refetchData.payload.length - 1];params.set(QueryParams.ruleId, String(clonedAlert.id));- history.push(`${ROUTES.EDIT_ALERTS}?${params.toString()}`);+ safeNavigate(`${ROUTES.EDIT_ALERTS}?${params.toString()}`);}, 2000);}if (status === 'error') {diff --git a/frontend/src/pages/AlertTypeSelection/AlertTypeSelection.tsx b/frontend/src/pages/AlertTypeSelection/AlertTypeSelection.tsxnew file mode 100644index 0000000000..e4d8904d1b--- /dev/null+++ b/frontend/src/pages/AlertTypeSelection/AlertTypeSelection.tsx@@ -0,0 +1,56 @@+import { Row } from 'antd';+import logEvent from 'api/common/logEvent';+import { QueryParams } from 'constants/query';+import ROUTES from 'constants/routes';+import SelectAlertType from 'container/CreateAlertRule/SelectAlertType';+import { AlertDetectionTypes } from 'container/FormAlertRules';+import { useSafeNavigate } from 'hooks/useSafeNavigate';+import useUrlQuery from 'hooks/useUrlQuery';+import { useCallback, useEffect } from 'react';+import { AlertTypes } from 'types/api/alerts/alertTypes';++function AlertTypeSelectionPage(): JSX.Element {+ const { safeNavigate } = useSafeNavigate();+ const queryParams = useUrlQuery();++ useEffect(() => {+ logEvent('Alert: New alert data source selection page visited', {});+ }, []);++ const handleSelectType = useCallback(+ (type: AlertTypes): void => {+ // For anamoly based alert, we need to set the ruleType to anomaly_rule+ // and alertType to metrics_based_alert+ if (type === AlertTypes.ANOMALY_BASED_ALERT) {+ queryParams.set(+ QueryParams.ruleType,+ AlertDetectionTypes.ANOMALY_DETECTION_ALERT,+ );+ queryParams.set(QueryParams.alertType, AlertTypes.METRICS_BASED_ALERT);+ // For other alerts, we need to set the ruleType to threshold_rule+ // and alertType to the selected type+ } else {+ queryParams.set(QueryParams.ruleType, AlertDetectionTypes.THRESHOLD_ALERT);+ queryParams.set(QueryParams.alertType, type);+ }++ const showNewCreateAlertsPageFlag = queryParams.get(+ QueryParams.showNewCreateAlertsPage,+ );+ if (showNewCreateAlertsPageFlag === 'true') {+ queryParams.set(QueryParams.showNewCreateAlertsPage, 'true');+ }++ safeNavigate(`${ROUTES.ALERTS_NEW}?${queryParams.toString()}`);+ },+ [queryParams, safeNavigate],+ );++ return (+ <Row wrap={false}>+ <SelectAlertType onSelect={handleSelectType} />+ </Row>+ );+}++export default AlertTypeSelectionPage;diff --git a/frontend/src/pages/AlertTypeSelection/__tests__/AlertTypeSelection.test.tsx b/frontend/src/pages/AlertTypeSelection/__tests__/AlertTypeSelection.test.tsxnew file mode 100644index 0000000000..63dbd8689c--- /dev/null+++ b/frontend/src/pages/AlertTypeSelection/__tests__/AlertTypeSelection.test.tsx@@ -0,0 +1,184 @@+import { fireEvent, render, screen } from '@testing-library/react';+import { FeatureKeys } from 'constants/features';+import { QueryParams } from 'constants/query';+import { AlertDetectionTypes } from 'container/FormAlertRules';+import { getAppContextMockState } from 'container/RoutingPolicies/__tests__/testUtils';+import * as navigateHooks from 'hooks/useSafeNavigate';+import * as useUrlQueryHooks from 'hooks/useUrlQuery';+import * as appHooks from 'providers/App/App';+import { AlertTypes } from 'types/api/alerts/alertTypes';++import AlertTypeSelection from '../AlertTypeSelection';++const useUrlQuerySpy = jest.spyOn(useUrlQueryHooks, 'default');+const useSafeNavigateSpy = jest.spyOn(navigateHooks, 'useSafeNavigate');+const useAppContextSpy = jest.spyOn(appHooks, 'useAppContext');++const mockSetUrlQuery = jest.fn();+const mockSafeNavigate = jest.fn();+const mockToString = jest.fn();+const mockGetUrlQuery = jest.fn();++describe('AlertTypeSelection', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ useAppContextSpy.mockReturnValue(getAppContextMockState());+ useUrlQuerySpy.mockReturnValue(({+ set: mockSetUrlQuery,+ toString: mockToString,+ get: mockGetUrlQuery,+ } as Partial<URLSearchParams>) as URLSearchParams);+ useSafeNavigateSpy.mockReturnValue({+ safeNavigate: mockSafeNavigate,+ });+ });++ it('should render all alert type options when anomaly detection is enabled', () => {+ useAppContextSpy.mockReturnValue({+ ...getAppContextMockState({}),+ featureFlags: [+ {+ name: FeatureKeys.ANOMALY_DETECTION,+ active: true,+ usage: 0,+ usage_limit: -1,+ route: '',+ },+ ],+ });++ render(<AlertTypeSelection />);++ expect(screen.getByText('metric_based_alert')).toBeInTheDocument();+ expect(screen.getByText('log_based_alert')).toBeInTheDocument();+ expect(screen.getByText('traces_based_alert')).toBeInTheDocument();+ expect(screen.getByText('exceptions_based_alert')).toBeInTheDocument();+ expect(screen.getByText('anomaly_based_alert')).toBeInTheDocument();+ });++ it('should render all alert type options except anomaly based alert when anomaly detection is disabled', () => {+ render(<AlertTypeSelection />);++ expect(screen.getByText('metric_based_alert')).toBeInTheDocument();+ expect(screen.getByText('log_based_alert')).toBeInTheDocument();+ expect(screen.getByText('traces_based_alert')).toBeInTheDocument();+ expect(screen.getByText('exceptions_based_alert')).toBeInTheDocument();+ expect(screen.queryByText('anomaly_based_alert')).not.toBeInTheDocument();+ });++ it('should navigate to metrics based alert with correct params', () => {+ render(<AlertTypeSelection />);+ fireEvent.click(screen.getByText('metric_based_alert'));++ expect(mockSetUrlQuery).toHaveBeenCalledTimes(2);+ expect(mockSetUrlQuery).toHaveBeenCalledWith(+ QueryParams.ruleType,+ AlertDetectionTypes.THRESHOLD_ALERT,+ );+ expect(mockSetUrlQuery).toHaveBeenCalledWith(+ QueryParams.alertType,+ AlertTypes.METRICS_BASED_ALERT,+ );+ expect(mockSafeNavigate).toHaveBeenCalled();+ });++ it('should navigate to anomaly based alert with correct params', () => {+ useAppContextSpy.mockReturnValue({+ ...getAppContextMockState({}),+ featureFlags: [+ {+ name: FeatureKeys.ANOMALY_DETECTION,+ active: true,+ usage: 0,+ usage_limit: -1,+ route: '',+ },+ ],+ });++ render(<AlertTypeSelection />);+ fireEvent.click(screen.getByText('anomaly_based_alert'));++ expect(mockSetUrlQuery).toHaveBeenCalledTimes(2);+ expect(mockSetUrlQuery).toHaveBeenCalledWith(+ QueryParams.ruleType,+ AlertDetectionTypes.ANOMALY_DETECTION_ALERT,+ );+ expect(mockSetUrlQuery).toHaveBeenCalledWith(+ QueryParams.alertType,+ AlertTypes.METRICS_BASED_ALERT,+ );+ expect(mockSafeNavigate).toHaveBeenCalled();+ });++ it('should navigate to log based alert with correct params', () => {+ render(<AlertTypeSelection />);+ fireEvent.click(screen.getByText('log_based_alert'));++ expect(mockSetUrlQuery).toHaveBeenCalledTimes(2);+ expect(mockSetUrlQuery).toHaveBeenCalledWith(+ QueryParams.ruleType,+ AlertDetectionTypes.THRESHOLD_ALERT,+ );+ expect(mockSetUrlQuery).toHaveBeenCalledWith(+ QueryParams.alertType,+ AlertTypes.LOGS_BASED_ALERT,+ );+ expect(mockSafeNavigate).toHaveBeenCalled();+ });++ it('should navigate to traces based alert with correct params', () => {+ render(<AlertTypeSelection />);+ fireEvent.click(screen.getByText('traces_based_alert'));+ expect(mockSetUrlQuery).toHaveBeenCalledTimes(2);+ expect(mockSetUrlQuery).toHaveBeenCalledWith(+ QueryParams.ruleType,+ AlertDetectionTypes.THRESHOLD_ALERT,+ );+ expect(mockSetUrlQuery).toHaveBeenCalledWith(+ QueryParams.alertType,+ AlertTypes.TRACES_BASED_ALERT,+ );+ expect(mockSafeNavigate).toHaveBeenCalled();+ });++ it('should navigate to exceptions based alert with correct params', () => {+ render(<AlertTypeSelection />);+ fireEvent.click(screen.getByText('exceptions_based_alert'));+ expect(mockSetUrlQuery).toHaveBeenCalledTimes(2);+ expect(mockSetUrlQuery).toHaveBeenCalledWith(+ QueryParams.ruleType,+ AlertDetectionTypes.THRESHOLD_ALERT,+ );+ expect(mockSetUrlQuery).toHaveBeenCalledWith(+ QueryParams.alertType,+ AlertTypes.EXCEPTIONS_BASED_ALERT,+ );+ expect(mockSafeNavigate).toHaveBeenCalled();+ });++ it('should navigate to new create alerts page with correct params if showNewCreateAlertsPage is true', () => {+ useUrlQuerySpy.mockReturnValue(({+ set: mockSetUrlQuery,+ toString: mockToString,+ get: mockGetUrlQuery.mockReturnValue('true'),+ } as Partial<URLSearchParams>) as URLSearchParams);++ render(<AlertTypeSelection />);+ fireEvent.click(screen.getByText('metric_based_alert'));+ expect(mockSetUrlQuery).toHaveBeenCalledTimes(3);+ expect(mockSetUrlQuery).toHaveBeenCalledWith(+ QueryParams.ruleType,+ AlertDetectionTypes.THRESHOLD_ALERT,+ );+ expect(mockSetUrlQuery).toHaveBeenCalledWith(+ QueryParams.alertType,+ AlertTypes.METRICS_BASED_ALERT,+ );+ expect(mockSetUrlQuery).toHaveBeenCalledWith(+ QueryParams.showNewCreateAlertsPage,+ 'true',+ );+ expect(mockSafeNavigate).toHaveBeenCalled();+ });+});diff --git a/frontend/src/pages/AlertTypeSelection/index.tsx b/frontend/src/pages/AlertTypeSelection/index.tsxnew file mode 100644index 0000000000..16ec4ffad3--- /dev/null+++ b/frontend/src/pages/AlertTypeSelection/index.tsx@@ -0,0 +1,3 @@+import AlertTypeSelectionPage from './AlertTypeSelection';++export default AlertTypeSelectionPage;diff --git a/frontend/src/utils/permission/index.ts b/frontend/src/utils/permission/index.tsindex e01837da6b..743e1d7465 100644--- a/frontend/src/utils/permission/index.ts+++ b/frontend/src/utils/permission/index.ts@@ -127,4 +127,5 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {METER: ['ADMIN', 'EDITOR', 'VIEWER'],METER_EXPLORER_VIEWS: ['ADMIN', 'EDITOR', 'VIEWER'],PUBLIC_DASHBOARD: ['ADMIN', 'EDITOR', 'VIEWER'],+ ALERT_TYPE_SELECTION: ['ADMIN', 'EDITOR'],};