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: add query section to create alerts (#8991)
Amlan Kumar Nandy0658c561b971
diff --git a/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/CreateAlertHeader.test.tsx b/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/CreateAlertHeader.test.tsxindex 978c359c29..adb4e8ed8b 100644--- a/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/CreateAlertHeader.test.tsx+++ b/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/CreateAlertHeader.test.tsx@@ -4,6 +4,27 @@ import { fireEvent, render, screen } from '@testing-library/react';import { CreateAlertProvider } from '../../context';import CreateAlertHeader from '../CreateAlertHeader';+jest.mock('uplot', () => {+ const paths = {+ spline: jest.fn(),+ bars: jest.fn(),+ };+ const uplotMock = jest.fn(() => ({+ paths,+ }));+ return {+ paths,+ default: uplotMock,+ };+});++jest.mock('react-router-dom', () => ({+ ...jest.requireActual('react-router-dom'),+ useLocation: (): { search: string } => ({+ search: '',+ }),+}));+const renderCreateAlertHeader = (): ReturnType<typeof render> =>render(<CreateAlertProvider>diff --git a/frontend/src/container/CreateAlertV2/CreateAlertV2.styles.scss b/frontend/src/container/CreateAlertV2/CreateAlertV2.styles.scssindex 916a70f958..23c38b075b 100644--- a/frontend/src/container/CreateAlertV2/CreateAlertV2.styles.scss+++ b/frontend/src/container/CreateAlertV2/CreateAlertV2.styles.scss@@ -1,3 +1,17 @@+$top-nav-background-1: #0f0f0f;+$top-nav-background-2: #101010;+.create-alert-v2-container {background-color: var(--bg-ink-500);}++.top-nav-container {+ background: repeating-linear-gradient(+ -45deg,+ $top-nav-background-1,+ $top-nav-background-1 10px,+ $top-nav-background-2 10px,+ $top-nav-background-2 20px+ );+ margin-bottom: 0;+}diff --git a/frontend/src/container/CreateAlertV2/CreateAlertV2.tsx b/frontend/src/container/CreateAlertV2/CreateAlertV2.tsxindex b896f8d10d..bdfededd13 100644--- a/frontend/src/container/CreateAlertV2/CreateAlertV2.tsx+++ b/frontend/src/container/CreateAlertV2/CreateAlertV2.tsx@@ -1,16 +1,32 @@import './CreateAlertV2.styles.scss';+import { initialQueriesMap } from 'constants/queryBuilder';+import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';+import { Query } from 'types/api/queryBuilder/queryBuilderData';+import { CreateAlertProvider } from './context';-import CreateAlertHeader from './CreateAlertHeader/CreateAlertHeader';+import CreateAlertHeader from './CreateAlertHeader';+import QuerySection from './QuerySection';++function CreateAlertV2({+ initialQuery = initialQueriesMap.metrics,+}: {+ initialQuery?: Query;+}): JSX.Element {+ useShareBuilderUrl({ defaultValue: initialQuery });-function CreateAlertV2(): JSX.Element {return (<div className="create-alert-v2-container"><CreateAlertProvider><CreateAlertHeader />+ <QuerySection /></CreateAlertProvider></div>);}+CreateAlertV2.defaultProps = {+ initialQuery: initialQueriesMap.metrics,+};+export default CreateAlertV2;diff --git a/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsx b/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsxnew file mode 100644index 0000000000..ae5876bc6a--- /dev/null+++ b/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsx@@ -0,0 +1,73 @@+import { PANEL_TYPES } from 'constants/queryBuilder';+import { useCreateAlertState } from 'container/CreateAlertV2/context';+import ChartPreviewComponent from 'container/FormAlertRules/ChartPreview';+import PlotTag from 'container/NewWidget/LeftContainer/WidgetGraph/PlotTag';+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';+import { useState } from 'react';+import { useSelector } from 'react-redux';+import { AppState } from 'store/reducers';+import { EQueryType } from 'types/common/dashboard';+import { GlobalReducer } from 'types/reducer/globalTime';++function ChartPreview(): JSX.Element {+ const { currentQuery, panelType, stagedQuery } = useQueryBuilder();+ const { selectedTime: globalSelectedInterval } = useSelector<+ AppState,+ GlobalReducer+ >((state) => state.globalTime);+ const [, setQueryStatus] = useState<string>('');+ const { alertDef } = useCreateAlertState();++ const yAxisUnit = currentQuery.unit || '';++ const renderQBChartPreview = (): JSX.Element => (+ <ChartPreviewComponent+ headline={+ <PlotTag+ queryType={currentQuery.queryType}+ panelType={panelType || PANEL_TYPES.TIME_SERIES}+ />+ }+ name=""+ query={stagedQuery}+ selectedInterval={globalSelectedInterval}+ alertDef={alertDef}+ yAxisUnit={yAxisUnit || ''}+ graphType={panelType || PANEL_TYPES.TIME_SERIES}+ setQueryStatus={setQueryStatus}+ showSideLegend+ />+ );++ const renderPromAndChQueryChartPreview = (): JSX.Element => (+ <ChartPreviewComponent+ headline={+ <PlotTag+ queryType={currentQuery.queryType}+ panelType={panelType || PANEL_TYPES.TIME_SERIES}+ />+ }+ name="Chart Preview"+ query={stagedQuery}+ alertDef={alertDef}+ selectedInterval={globalSelectedInterval}+ yAxisUnit={yAxisUnit || ''}+ graphType={panelType || PANEL_TYPES.TIME_SERIES}+ setQueryStatus={setQueryStatus}+ showSideLegend+ />+ );++ return (+ <div className="chart-preview-container">+ {currentQuery.queryType === EQueryType.QUERY_BUILDER &&+ renderQBChartPreview()}+ {currentQuery.queryType === EQueryType.PROM &&+ renderPromAndChQueryChartPreview()}+ {currentQuery.queryType === EQueryType.CLICKHOUSE &&+ renderPromAndChQueryChartPreview()}+ </div>+ );+}++export default ChartPreview;diff --git a/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/index.ts b/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/index.tsnew file mode 100644index 0000000000..8845923e05--- /dev/null+++ b/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/index.ts@@ -0,0 +1,3 @@+import ChartPreview from './ChartPreview';++export default ChartPreview;diff --git a/frontend/src/container/CreateAlertV2/QuerySection/QuerySection.tsx b/frontend/src/container/CreateAlertV2/QuerySection/QuerySection.tsxnew file mode 100644index 0000000000..644be2153d--- /dev/null+++ b/frontend/src/container/CreateAlertV2/QuerySection/QuerySection.tsx@@ -0,0 +1,82 @@+import './styles.scss';++import { Button } from 'antd';+import classNames from 'classnames';+import { PANEL_TYPES } from 'constants/queryBuilder';+import QuerySectionComponent from 'container/FormAlertRules/QuerySection';+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';+import { BarChart2, DraftingCompass, FileText, ScrollText } from 'lucide-react';+import { AlertTypes } from 'types/api/alerts/alertTypes';++import { useCreateAlertState } from '../context';+import Stepper from '../Stepper';+import ChartPreview from './ChartPreview';++function QuerySection(): JSX.Element {+ const { currentQuery, handleRunQuery } = useQueryBuilder();+ const { alertType, setAlertType, alertDef } = useCreateAlertState();++ const tabs = [+ {+ label: 'Metrics',+ icon: <BarChart2 size={14} data-testid="metrics-view" />,+ value: AlertTypes.METRICS_BASED_ALERT,+ },+ {+ label: 'Logs',+ icon: <ScrollText size={14} data-testid="logs-view" />,+ value: AlertTypes.LOGS_BASED_ALERT,+ },+ {+ label: 'Traces',+ icon: <DraftingCompass size={14} data-testid="traces-view" />,+ value: AlertTypes.TRACES_BASED_ALERT,+ },+ {+ label: 'Exceptions',+ icon: <FileText size={14} data-testid="exceptions-view" />,+ value: AlertTypes.EXCEPTIONS_BASED_ALERT,+ },+ ];++ return (+ <div className="query-section">+ <Stepper+ stepNumber={1}+ label="Define the query you want to set an alert on"+ />+ <ChartPreview />+ <div className="query-section-tabs">+ <div className="query-section-query-actions">+ {tabs.map((tab) => (+ <Button+ key={tab.value}+ className={classNames('list-view-tab', 'explorer-view-option', {+ 'active-tab': alertType === tab.value,+ })}+ onClick={(): void => {+ setAlertType(tab.value as AlertTypes);+ }}+ >+ {tab.icon}+ {tab.label}+ </Button>+ ))}+ </div>+ </div>+ <QuerySectionComponent+ queryCategory={currentQuery.queryType}+ setQueryCategory={(): void => {}}+ alertType={alertType}+ runQuery={handleRunQuery}+ alertDef={alertDef}+ panelType={PANEL_TYPES.TIME_SERIES}+ key={currentQuery.queryType}+ ruleId=""+ hideTitle+ />+ </div>+ );+}++export default QuerySection;diff --git a/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsx b/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsxnew file mode 100644index 0000000000..f2c560c754--- /dev/null+++ b/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsx@@ -0,0 +1,262 @@+/* eslint-disable @typescript-eslint/no-explicit-any */+/* eslint-disable react/destructuring-assignment */+import { render, screen } from '@testing-library/react';+import { PANEL_TYPES } from 'constants/queryBuilder';+import { QueryClient, QueryClientProvider } from 'react-query';+import { Provider } from 'react-redux';+import { MemoryRouter } from 'react-router-dom';+import store from 'store';+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';+const GRAPH_TYPE_TEST_ID = 'graph-type';+const CHART_PREVIEW_COMPONENT_TEST_ID = 'chart-preview-component';+const PLOT_QUERY_TYPE_TEST_ID = 'plot-query-type';+const PLOT_PANEL_TYPE_TEST_ID = 'plot-panel-type';++jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({+ useQueryBuilder: jest.fn(),+}));+jest.mock(+ 'container/FormAlertRules/ChartPreview',+ () =>+ function MockChartPreviewComponent(props: any): JSX.Element {+ return (+ <div data-testid={CHART_PREVIEW_COMPONENT_TEST_ID}>+ <div data-testid="headline">{props.headline}</div>+ <div data-testid="name">{props.name}</div>+ <div data-testid={QUERY_TYPE_TEST_ID}>{props.query?.queryType}</div>+ <div data-testid="selected-interval">+ {props.selectedInterval?.startTime}+ </div>+ <div data-testid="y-axis-unit">{props.yAxisUnit}</div>+ <div data-testid={GRAPH_TYPE_TEST_ID}>{props.graphType}</div>+ </div>+ );+ },+);+jest.mock(+ 'container/NewWidget/LeftContainer/WidgetGraph/PlotTag',+ () =>+ function MockPlotTag(props: any): JSX.Element {+ return (+ <div data-testid="plot-tag">+ <div data-testid={PLOT_QUERY_TYPE_TEST_ID}>{props.queryType}</div>+ <div data-testid={PLOT_PANEL_TYPE_TEST_ID}>{props.panelType}</div>+ </div>+ );+ },+);+jest.mock('uplot', () => {+ const paths = {+ spline: jest.fn(),+ bars: jest.fn(),+ };+ const uplotMock = jest.fn(() => ({+ paths,+ }));+ return {+ paths,+ default: uplotMock,+ };+});++// Mock react-redux+jest.mock('react-redux', () => ({+ ...jest.requireActual('react-redux'),+ useSelector: (): any => ({+ globalTime: {+ selectedTime: {+ startTime: 1713734400000,+ endTime: 1713738000000,+ },+ maxTime: 1713738000000,+ minTime: 1713734400000,+ },+ }),+}));++const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+});++const mockUseQueryBuilder = {+ currentQuery: {+ queryType: EQueryType.QUERY_BUILDER,+ unit: REQUESTS_PER_SEC,+ builder: {+ queryData: [+ {+ dataSource: 'metrics',+ },+ ],+ },+ },+ panelType: PANEL_TYPES.TIME_SERIES,+ stagedQuery: {+ queryType: EQueryType.QUERY_BUILDER,+ unit: REQUESTS_PER_SEC,+ },+};++const renderChartPreview = (): ReturnType<typeof render> =>+ render(+ <Provider store={store}>+ <QueryClientProvider client={queryClient}>+ <MemoryRouter>+ <CreateAlertProvider>+ <ChartPreview />+ </CreateAlertProvider>+ </MemoryRouter>+ </QueryClientProvider>+ </Provider>,+ );++describe('ChartPreview', () => {+ const { useQueryBuilder } = jest.requireMock(+ 'hooks/queryBuilder/useQueryBuilder',+ );++ beforeEach(() => {+ jest.clearAllMocks();+ useQueryBuilder.mockReturnValue(mockUseQueryBuilder);+ });++ it('renders the component with correct container class', () => {+ renderChartPreview();++ const container = screen+ .getByTestId(CHART_PREVIEW_COMPONENT_TEST_ID)+ .closest('.chart-preview-container');+ expect(container).toBeInTheDocument();+ });++ it('renders QueryBuilder chart preview when query type is QUERY_BUILDER', () => {+ renderChartPreview();++ expect(+ screen.getByTestId(CHART_PREVIEW_COMPONENT_TEST_ID),+ ).toBeInTheDocument();+ expect(screen.getByTestId('plot-tag')).toBeInTheDocument();+ expect(screen.getByTestId(PLOT_QUERY_TYPE_TEST_ID)).toHaveTextContent(+ EQueryType.QUERY_BUILDER,+ );+ expect(screen.getByTestId(PLOT_PANEL_TYPE_TEST_ID)).toHaveTextContent(+ PANEL_TYPES.TIME_SERIES,+ );+ });++ it('renders QueryBuilder chart preview with empty name when query type is QUERY_BUILDER', () => {+ renderChartPreview();++ expect(screen.getByTestId('name')).toHaveTextContent('');+ });++ it('renders QueryBuilder chart preview with correct props', () => {+ renderChartPreview();++ expect(screen.getByTestId(QUERY_TYPE_TEST_ID)).toHaveTextContent(+ EQueryType.QUERY_BUILDER,+ );+ expect(screen.getByTestId('y-axis-unit')).toHaveTextContent(REQUESTS_PER_SEC);+ expect(screen.getByTestId(GRAPH_TYPE_TEST_ID)).toHaveTextContent(+ PANEL_TYPES.TIME_SERIES,+ );+ expect(screen.getByTestId('name')).toHaveTextContent('');+ expect(screen.getByTestId('headline')).toBeInTheDocument();+ expect(screen.getByTestId('selected-interval')).toBeInTheDocument();+ });++ it('renders PromQL chart preview when query type is PROM', () => {+ useQueryBuilder.mockReturnValue({+ ...mockUseQueryBuilder,+ currentQuery: {+ ...mockUseQueryBuilder.currentQuery,+ queryType: EQueryType.PROM,+ },+ stagedQuery: {+ queryType: EQueryType.PROM,+ unit: REQUESTS_PER_SEC,+ },+ });++ renderChartPreview();++ expect(+ screen.getByTestId(CHART_PREVIEW_COMPONENT_TEST_ID),+ ).toBeInTheDocument();+ expect(screen.getByTestId('name')).toHaveTextContent(CHART_PREVIEW_NAME);+ expect(screen.getByTestId(QUERY_TYPE_TEST_ID)).toHaveTextContent(+ EQueryType.PROM,+ );+ });++ it('renders ClickHouse chart preview when query type is CLICKHOUSE', () => {+ useQueryBuilder.mockReturnValue({+ ...mockUseQueryBuilder,+ currentQuery: {+ ...mockUseQueryBuilder.currentQuery,+ queryType: EQueryType.CLICKHOUSE,+ },+ stagedQuery: {+ queryType: EQueryType.CLICKHOUSE,+ unit: REQUESTS_PER_SEC,+ },+ });++ renderChartPreview();++ expect(+ screen.getByTestId(CHART_PREVIEW_COMPONENT_TEST_ID),+ ).toBeInTheDocument();+ expect(screen.getByTestId('name')).toHaveTextContent(CHART_PREVIEW_NAME);+ expect(screen.getByTestId(QUERY_TYPE_TEST_ID)).toHaveTextContent(+ EQueryType.CLICKHOUSE,+ );+ });++ it('uses default panel type when panelType is not provided', () => {+ useQueryBuilder.mockReturnValue({+ ...mockUseQueryBuilder,+ panelType: undefined,+ });++ renderChartPreview();++ expect(screen.getByTestId(PLOT_PANEL_TYPE_TEST_ID)).toHaveTextContent(+ PANEL_TYPES.TIME_SERIES,+ );+ expect(screen.getByTestId(GRAPH_TYPE_TEST_ID)).toHaveTextContent(+ PANEL_TYPES.TIME_SERIES,+ );+ expect(screen.getByTestId(QUERY_TYPE_TEST_ID)).toHaveTextContent(+ EQueryType.QUERY_BUILDER,+ );+ });++ it('uses custom panel type when provided', () => {+ useQueryBuilder.mockReturnValue({+ ...mockUseQueryBuilder,+ panelType: PANEL_TYPES.BAR,+ });++ renderChartPreview();++ expect(screen.getByTestId(PLOT_PANEL_TYPE_TEST_ID)).toHaveTextContent(+ PANEL_TYPES.BAR,+ );+ expect(screen.getByTestId(GRAPH_TYPE_TEST_ID)).toHaveTextContent(+ PANEL_TYPES.BAR,+ );+ });+});diff --git a/frontend/src/container/CreateAlertV2/QuerySection/__tests__/QuerySection.test.tsx b/frontend/src/container/CreateAlertV2/QuerySection/__tests__/QuerySection.test.tsxnew file mode 100644index 0000000000..7f341c6956--- /dev/null+++ b/frontend/src/container/CreateAlertV2/QuerySection/__tests__/QuerySection.test.tsx@@ -0,0 +1,307 @@+/* eslint-disable @typescript-eslint/no-explicit-any */+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { QueryParams } from 'constants/query';+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 { CreateAlertProvider } from '../../context';+import QuerySection from '../QuerySection';++jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({+ useQueryBuilder: jest.fn(),+}));+jest.mock('uplot', () => {+ const paths = {+ spline: jest.fn(),+ bars: jest.fn(),+ };+ const uplotMock = jest.fn(() => ({+ paths,+ }));+ return {+ paths,+ default: uplotMock,+ };+});+jest.mock('react-redux', () => ({+ ...jest.requireActual('react-redux'),+ useSelector: (): any => ({+ globalTime: {+ selectedTime: {+ startTime: 1713734400000,+ endTime: 1713738000000,+ },+ maxTime: 1713738000000,+ minTime: 1713734400000,+ },+ }),+}));+jest.mock(+ 'container/FormAlertRules/QuerySection',+ () =>+ function MockQuerySectionComponent({+ queryCategory,+ alertType,+ panelType,+ }: any): JSX.Element {+ return (+ <div data-testid="query-section-component">+ <div data-testid="query-category">{queryCategory}</div>+ <div data-testid="alert-type">{alertType}</div>+ <div data-testid="panel-type">{panelType}</div>+ </div>+ );+ },+);+jest.mock(+ '../ChartPreview',+ () =>+ function MockChartPreview(): JSX.Element {+ return <div data-testid="chart-preview">Chart Preview</div>;+ },+);+jest.mock(+ '../../Stepper',+ () =>+ function MockStepper({ stepNumber, label }: any): JSX.Element {+ return (+ <div data-testid="stepper">+ <div data-testid="step-number">{stepNumber}</div>+ <div data-testid="step-label">{label}</div>+ </div>+ );+ },+);++const mockUseQueryBuilder = {+ currentQuery: {+ queryType: 'query_builder',+ unit: 'requests/sec',+ builder: {+ queryData: [+ {+ dataSource: 'metrics',+ },+ ],+ },+ },+ handleRunQuery: jest.fn(),+ redirectWithQueryBuilderData: jest.fn(),+};+const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+});+const renderQuerySection = (): ReturnType<typeof render> =>+ render(+ <Provider store={store}>+ <QueryClientProvider client={queryClient}>+ <MemoryRouter>+ <CreateAlertProvider>+ <QuerySection />+ </CreateAlertProvider>+ </MemoryRouter>+ </QueryClientProvider>+ </Provider>,+ );++const METRICS_TEXT = 'Metrics';+const QUERY_BUILDER_TEXT = 'query_builder';+const LOGS_TEXT = 'Logs';+const TRACES_TEXT = 'Traces';+const ACTIVE_TAB_CLASS = 'active-tab';++describe('QuerySection', () => {+ const { useQueryBuilder } = jest.requireMock(+ 'hooks/queryBuilder/useQueryBuilder',+ );++ beforeEach(() => {+ jest.clearAllMocks();+ useQueryBuilder.mockReturnValue(mockUseQueryBuilder);+ });++ it('renders the component with all required elements', () => {+ renderQuerySection();++ // Check if Stepper is rendered+ expect(screen.getByTestId('stepper')).toBeInTheDocument();+ expect(screen.getByTestId('step-number')).toHaveTextContent('1');+ expect(screen.getByTestId('step-label')).toHaveTextContent(+ 'Define the query you want to set an alert on',+ );++ // Check if ChartPreview is rendered+ expect(screen.getByTestId('chart-preview')).toBeInTheDocument();++ // Check if QuerySectionComponent is rendered+ expect(screen.getByTestId('query-section-component')).toBeInTheDocument();+ expect(screen.getByTestId('query-category')).toHaveTextContent(+ QUERY_BUILDER_TEXT,+ );+ expect(screen.getByTestId('alert-type')).toHaveTextContent(+ AlertTypes.METRICS_BASED_ALERT,+ );+ expect(screen.getByTestId('panel-type')).toHaveTextContent('graph');+ });++ it('renders all three alert type tabs', () => {+ renderQuerySection();++ // Check if all tabs are rendered+ expect(screen.getByText(METRICS_TEXT)).toBeInTheDocument();+ expect(screen.getByText('Logs')).toBeInTheDocument();+ expect(screen.getByText('Traces')).toBeInTheDocument();++ // Check if icons are rendered+ expect(screen.getByTestId('metrics-view')).toBeInTheDocument();+ expect(screen.getByTestId('logs-view')).toBeInTheDocument();+ expect(screen.getByTestId('traces-view')).toBeInTheDocument();+ });++ it('shows Metrics tab as active by default', () => {+ renderQuerySection();++ const metricsTab = screen.getByText(METRICS_TEXT).closest('button');+ expect(metricsTab).toHaveClass(ACTIVE_TAB_CLASS);+ });++ it('handles alert type change when clicking on different tabs', async () => {+ const user = userEvent.setup();+ renderQuerySection();++ // Click on Logs tab+ const logsTab = screen.getByText(LOGS_TEXT);+ await user.click(logsTab);++ // Verify that redirectWithQueryBuilderData was called with correct data+ expect(mockUseQueryBuilder.redirectWithQueryBuilderData).toHaveBeenCalledWith(+ expect.any(Object),+ {+ [QueryParams.alertType]: AlertTypes.LOGS_BASED_ALERT,+ },+ undefined,+ true,+ );++ // Click on Traces tab+ const tracesTab = screen.getByText(TRACES_TEXT);+ await user.click(tracesTab);++ // Verify that redirectWithQueryBuilderData was called with correct data+ expect(mockUseQueryBuilder.redirectWithQueryBuilderData).toHaveBeenCalledWith(+ expect.any(Object),+ {+ [QueryParams.alertType]: AlertTypes.TRACES_BASED_ALERT,+ },+ undefined,+ true,+ );+ });++ it('updates active tab when alert type changes', async () => {+ const user = userEvent.setup();+ renderQuerySection();++ // Initially Metrics should be active+ const metricsTab = screen.getByText(METRICS_TEXT).closest('button');+ expect(metricsTab).toHaveClass(ACTIVE_TAB_CLASS);++ // Click on Logs tab+ const logsTab = screen.getByText(LOGS_TEXT);+ await user.click(logsTab);++ // Logs should now be active+ const logsButton = logsTab.closest('button');+ expect(logsButton).toHaveClass(ACTIVE_TAB_CLASS);+ expect(metricsTab).not.toHaveClass(ACTIVE_TAB_CLASS);+ });++ it('passes correct props to QuerySectionComponent', () => {+ renderQuerySection();++ // Check if the component receives the correct props+ expect(screen.getByTestId('query-category')).toHaveTextContent(+ QUERY_BUILDER_TEXT,+ );+ expect(screen.getByTestId('alert-type')).toHaveTextContent(+ AlertTypes.METRICS_BASED_ALERT,+ );+ expect(screen.getByTestId('panel-type')).toHaveTextContent('graph');+ });++ it('has correct CSS classes for tab styling', () => {+ renderQuerySection();++ const tabs = screen.getAllByRole('button');++ tabs.forEach((tab) => {+ expect(tab).toHaveClass('list-view-tab');+ expect(tab).toHaveClass('explorer-view-option');+ });+ });++ it('renders with correct container structure', () => {+ renderQuerySection();++ const container = screen.getByText(METRICS_TEXT).closest('.query-section');+ expect(container).toBeInTheDocument();++ const tabsContainer = screen+ .getByText(METRICS_TEXT)+ .closest('.query-section-tabs');+ expect(tabsContainer).toBeInTheDocument();++ const actionsContainer = screen+ .getByText(METRICS_TEXT)+ .closest('.query-section-query-actions');+ expect(actionsContainer).toBeInTheDocument();+ });++ it('handles multiple rapid tab clicks correctly', async () => {+ const user = userEvent.setup();+ renderQuerySection();++ const logsTab = screen.getByText('Logs');+ const tracesTab = screen.getByText('Traces');++ // Rapidly click on different tabs+ await user.click(logsTab);+ await user.click(tracesTab);+ await user.click(logsTab);++ // Should have called redirectWithQueryBuilderData 3 times+ expect(+ mockUseQueryBuilder.redirectWithQueryBuilderData,+ ).toHaveBeenCalledTimes(3);+ });++ it('maintains tab state correctly after interactions', async () => {+ const user = userEvent.setup();+ renderQuerySection();++ // Click on Logs tab+ const logsTab = screen.getByText('Logs');+ await user.click(logsTab);++ // Verify Logs is active+ const logsButton = logsTab.closest('button');+ expect(logsButton).toHaveClass(ACTIVE_TAB_CLASS);++ // Click back to Metrics+ const metricsTab = screen.getByText(METRICS_TEXT);+ await user.click(metricsTab);++ // Verify Metrics is active again+ const metricsButton = metricsTab.closest('button');+ expect(metricsButton).toHaveClass(ACTIVE_TAB_CLASS);+ expect(logsButton).not.toHaveClass(ACTIVE_TAB_CLASS);+ });+});diff --git a/frontend/src/container/CreateAlertV2/QuerySection/index.ts b/frontend/src/container/CreateAlertV2/QuerySection/index.tsnew file mode 100644index 0000000000..b3ff502ac5--- /dev/null+++ b/frontend/src/container/CreateAlertV2/QuerySection/index.ts@@ -0,0 +1,3 @@+import QuerySection from './QuerySection';++export default QuerySection;diff --git a/frontend/src/container/CreateAlertV2/QuerySection/styles.scss b/frontend/src/container/CreateAlertV2/QuerySection/styles.scssnew file mode 100644index 0000000000..3faed92151--- /dev/null+++ b/frontend/src/container/CreateAlertV2/QuerySection/styles.scss@@ -0,0 +1,90 @@+.query-section {+ margin: 0 16px;+ .query-section-tabs {+ display: flex;+ align-items: center;+ margin-left: 12px;+ margin-top: 24px;++ .query-section-query-actions {+ 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;++ .prom-ql-icon {+ height: 14px;+ width: 14px;+ }++ .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);+ }+ }+ }++ .frequency-chart-view-controller {+ display: flex;+ align-items: center;+ padding-left: 8px;+ gap: 8px;+ }+ }++ .chart-preview-container {+ margin-right: 4px;+ .alert-chart-container {+ .ant-card {+ border: 1px solid var(--bg-slate-500);+ .ant-card-body {+ background-color: var(--bg-ink-500);+ }+ }+ }+ }++ .alert-query-section-container {+ margin: 0;+ background-color: var(--bg-ink-500);+ border: 1px solid var(--bg-slate-400);+ }+}diff --git a/frontend/src/container/CreateAlertV2/Stepper/styles.scss b/frontend/src/container/CreateAlertV2/Stepper/styles.scssindex db56be0695..ed0ee65a28 100644--- a/frontend/src/container/CreateAlertV2/Stepper/styles.scss+++ b/frontend/src/container/CreateAlertV2/Stepper/styles.scss@@ -3,7 +3,7 @@align-items: center;gap: 16px;margin-bottom: 16px;- padding: 16px;+ padding: 16px 0;border-radius: 8px;}diff --git a/frontend/src/container/CreateAlertV2/context/index.tsx b/frontend/src/container/CreateAlertV2/context/index.tsxindex 53839bbc07..4f1d4d50d7 100644--- a/frontend/src/container/CreateAlertV2/context/index.tsx+++ b/frontend/src/container/CreateAlertV2/context/index.tsx@@ -1,18 +1,25 @@+import { QueryParams } from 'constants/query';+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';+import { mapQueryDataFromApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataFromApi';import {createContext,+ useCallback,useContext,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 { ICreateAlertContextProps, ICreateAlertProviderProps } from './types';import {- AlertCreationStep,- ICreateAlertContextProps,- ICreateAlertProviderProps,-} from './types';-import { alertCreationReducer } from './utils';+ alertCreationReducer,+ buildInitialAlertDef,+ getInitialAlertTypeFromURL,+} from './utils';const CreateAlertContext = createContext<ICreateAlertContextProps | null>(null);@@ -36,18 +43,44 @@ export function CreateAlertProvider(alertCreationReducer,INITIAL_ALERT_STATE,);- const [step, setStep] = useState<AlertCreationStep>(- AlertCreationStep.ALERT_DEFINITION,++ const { currentQuery, redirectWithQueryBuilderData } = useQueryBuilder();+ const location = useLocation();+ const queryParams = new URLSearchParams(location.search);++ const [alertType, setAlertType] = useState<AlertTypes>(() =>+ getInitialAlertTypeFromURL(queryParams, currentQuery),+ );+ const [alertDef] = useState<AlertDef>(buildInitialAlertDef(alertType));++ const handleAlertTypeChange = useCallback(+ (value: AlertTypes): void => {+ const queryToRedirect = buildInitialAlertDef(value);+ const currentQueryToRedirect = mapQueryDataFromApi(+ queryToRedirect.condition.compositeQuery,+ );+ redirectWithQueryBuilderData(+ currentQueryToRedirect,+ {+ [QueryParams.alertType]: value,+ },+ undefined,+ true,+ );+ setAlertType(value);+ },+ [redirectWithQueryBuilderData],);const contextValue: ICreateAlertContextProps = useMemo(() => ({alertState,setAlertState,- step,- setStep,+ alertType,+ setAlertType: handleAlertTypeChange,+ alertDef,}),- [alertState, setAlertState, step, setStep],+ [alertState, alertType, handleAlertTypeChange, alertDef],);return (diff --git a/frontend/src/container/CreateAlertV2/context/types.ts b/frontend/src/container/CreateAlertV2/context/types.tsindex be0f8e53ca..ee90b03b88 100644--- a/frontend/src/container/CreateAlertV2/context/types.ts+++ b/frontend/src/container/CreateAlertV2/context/types.ts@@ -1,11 +1,13 @@import { Dispatch } from 'react';-import { Labels } from 'types/api/alerts/def';+import { AlertTypes } from 'types/api/alerts/alertTypes';+import { AlertDef, Labels } from 'types/api/alerts/def';export interface ICreateAlertContextProps {alertState: AlertState;setAlertState: Dispatch<CreateAlertAction>;- step: AlertCreationStep;- setStep: Dispatch<AlertCreationStep>;+ alertType: AlertTypes;+ setAlertType: Dispatch<AlertTypes>;+ alertDef: AlertDef;}export interface ICreateAlertProviderProps {diff --git a/frontend/src/container/CreateAlertV2/context/utils.tsx b/frontend/src/container/CreateAlertV2/context/utils.tsxindex d04a8d1b49..9c427a6e9a 100644--- a/frontend/src/container/CreateAlertV2/context/utils.tsx+++ b/frontend/src/container/CreateAlertV2/context/utils.tsx@@ -1,3 +1,16 @@+import { QueryParams } from 'constants/query';+import {+ alertDefaults,+ anamolyAlertDefaults,+ exceptionAlertDefaults,+ logAlertDefaults,+ traceAlertDefaults,+} from 'container/CreateAlertRule/defaults';+import { AlertTypes } from 'types/api/alerts/alertTypes';+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';export const alertCreationReducer = (@@ -24,3 +37,45 @@ export const alertCreationReducer = (return state;}};++export function getInitialAlertType(currentQuery: Query): AlertTypes {+ const dataSource =+ currentQuery.builder.queryData[0].dataSource || DataSource.METRICS;+ switch (dataSource) {+ case DataSource.METRICS:+ return AlertTypes.METRICS_BASED_ALERT;+ case DataSource.LOGS:+ return AlertTypes.LOGS_BASED_ALERT;+ case DataSource.TRACES:+ return AlertTypes.TRACES_BASED_ALERT;+ default:+ return AlertTypes.METRICS_BASED_ALERT;+ }+}++export function buildInitialAlertDef(alertType: AlertTypes): AlertDef {+ switch (alertType) {+ case AlertTypes.LOGS_BASED_ALERT:+ return logAlertDefaults;+ case AlertTypes.TRACES_BASED_ALERT:+ return traceAlertDefaults;+ case AlertTypes.EXCEPTIONS_BASED_ALERT:+ return exceptionAlertDefaults;+ case AlertTypes.ANOMALY_BASED_ALERT:+ return anamolyAlertDefaults;+ case AlertTypes.METRICS_BASED_ALERT:+ return alertDefaults;+ default:+ return alertDefaults;+ }+}++export function getInitialAlertTypeFromURL(+ urlSearchParams: URLSearchParams,+ currentQuery: Query,+): AlertTypes {+ const alertTypeFromURL = urlSearchParams.get(QueryParams.alertType);+ return alertTypeFromURL+ ? (alertTypeFromURL as AlertTypes)+ : getInitialAlertType(currentQuery);+}diff --git a/frontend/src/container/FormAlertRules/ChartPreview/index.tsx b/frontend/src/container/FormAlertRules/ChartPreview/index.tsxindex c6a4a7be6e..4390da8f9f 100644--- a/frontend/src/container/FormAlertRules/ChartPreview/index.tsx+++ b/frontend/src/container/FormAlertRules/ChartPreview/index.tsx@@ -65,6 +65,7 @@ export interface ChartPreviewProps {allowSelectedIntervalForStepGen?: boolean;yAxisUnit: string;setQueryStatus?: (status: string) => void;+ showSideLegend?: boolean;}// eslint-disable-next-line sonarjs/cognitive-complexity@@ -80,6 +81,7 @@ function ChartPreview({alertDef,yAxisUnit,setQueryStatus,+ showSideLegend = false,}: ChartPreviewProps): JSX.Element | null {const { t } = useTranslation('alerts');const dispatch = useDispatch();@@ -236,6 +238,18 @@ function ChartPreview({const { timezone } = useTimezone();+ const legendPosition = useMemo(() => {+ if (!showSideLegend) {+ return LegendPosition.BOTTOM;+ }+ const numberOfSeries =+ queryResponse?.data?.payload?.data?.result?.length || 0;+ if (numberOfSeries <= 1) {+ return LegendPosition.BOTTOM;+ }+ return LegendPosition.RIGHT;+ }, [queryResponse?.data?.payload?.data?.result?.length, showSideLegend]);+const options = useMemo(() =>getUPlotChartOptions({@@ -279,7 +293,7 @@ function ChartPreview({graphsVisibilityStates: graphVisibility,setGraphsVisibilityStates: setGraphVisibility,enhancedLegend: true,- legendPosition: LegendPosition.BOTTOM,+ legendPosition,}),[yAxisUnit,@@ -298,6 +312,7 @@ function ChartPreview({currentQuery,query,graphVisibility,+ legendPosition,],);@@ -370,6 +385,7 @@ ChartPreview.defaultProps = {allowSelectedIntervalForStepGen: false,alertDef: undefined,setQueryStatus: (): void => {},+ showSideLegend: false,};export default ChartPreview;diff --git a/frontend/src/container/FormAlertRules/QuerySection.tsx b/frontend/src/container/FormAlertRules/QuerySection.tsxindex 5009c0121a..1238a85015 100644--- a/frontend/src/container/FormAlertRules/QuerySection.tsx+++ b/frontend/src/container/FormAlertRules/QuerySection.tsx@@ -31,6 +31,7 @@ function QuerySection({alertDef,panelType,ruleId,+ hideTitle,}: QuerySectionProps): JSX.Element {// init namespace for translationsconst { t } = useTranslation('alerts');@@ -218,7 +219,9 @@ function QuerySection({return (<>- <StepHeading> {t('alert_form_step2', { step: step2Label })}</StepHeading>+ {!hideTitle && (+ <StepHeading> {t('alert_form_step2', { step: step2Label })}</StepHeading>+ )}<FormContainer className="alert-query-section-container"><div>{renderTabs(alertType)}</div>{renderQuerySection(currentTab)}@@ -235,6 +238,11 @@ interface QuerySectionProps {alertDef: AlertDef;panelType: PANEL_TYPES;ruleId: string;+ hideTitle?: boolean;}+QuerySection.defaultProps = {+ hideTitle: false,+};+export default QuerySection;diff --git a/frontend/src/pages/CreateAlert/index.tsx b/frontend/src/pages/CreateAlert/index.tsxindex 9172adfefb..b09a2503d2 100644--- a/frontend/src/pages/CreateAlert/index.tsx+++ b/frontend/src/pages/CreateAlert/index.tsx@@ -1,6 +1,8 @@import CreateAlertRule from 'container/CreateAlertRule';-import CreateAlertV2 from 'container/CreateAlertV2';import { showNewCreateAlertsPage } from 'container/CreateAlertV2/utils';+import { lazy } from 'react';++const CreateAlertV2 = lazy(() => import('container/CreateAlertV2'));function CreateAlertPage(): JSX.Element {const showNewCreateAlertsPageFlag = showNewCreateAlertsPage();