mirror of
https://github.com/SigNoz/signoz.git
synced 2026-10-16 23:20:51 +01:00
Compare commits
8 Commits
main
...
feat/notif
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
02ad3d0a05 | ||
|
|
9741734aa9 | ||
|
|
23a1dca192 | ||
|
|
e9284bac49 | ||
|
|
410622bf9f | ||
|
|
337fefa9bc | ||
|
|
782f17864e | ||
|
|
6bcb0c8ba3 |
@@ -104,7 +104,6 @@ func runGenerateAuthz(_ context.Context) error {
|
||||
coretypes.NewResourceRef(coretypes.ResourceTelemetryResourceMetrics).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceTelemetryResourceMeterMetrics).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceQuickFilter).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceSavedView).String(): true,
|
||||
}
|
||||
|
||||
allowedTypes := map[string]bool{}
|
||||
|
||||
@@ -25008,75 +25008,6 @@ paths:
|
||||
tags:
|
||||
- rules
|
||||
x-signoz-stability: alpha
|
||||
/api/v2/rules/{id}/clone:
|
||||
post:
|
||||
deprecated: false
|
||||
description: This endpoint creates a new alert rule from the stored definition
|
||||
of an existing one. The clone keeps every modeled field of the source, including
|
||||
its enabled/disabled state, and gets the source's name suffixed with " - Copy"
|
||||
(or a bumped " - Copy (n)" counter when the source is itself a copy). The
|
||||
clone is owned by the caller.
|
||||
operationId: CloneRuleByID
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"201":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
properties:
|
||||
data:
|
||||
$ref: '#/components/schemas/RuletypesRule'
|
||||
status:
|
||||
type: string
|
||||
required:
|
||||
- status
|
||||
- data
|
||||
type: object
|
||||
description: Created
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Bad Request
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Unauthorized
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Forbidden
|
||||
"404":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Not Found
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- EDITOR
|
||||
- tokenizer:
|
||||
- EDITOR
|
||||
summary: Clone alert rule
|
||||
tags:
|
||||
- rules
|
||||
x-signoz-stability: alpha
|
||||
/api/v2/rules/{id}/history/filter_keys:
|
||||
get:
|
||||
deprecated: false
|
||||
|
||||
@@ -423,7 +423,7 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
|
||||
func (r *AnomalyRule) String() string {
|
||||
|
||||
ar := ruletypes.PostableRule{
|
||||
AlertName: valuer.NewDisplayName(r.Name()),
|
||||
AlertName: r.Name(),
|
||||
RuleCondition: r.Condition(),
|
||||
EvalWindow: r.EvalWindow(),
|
||||
Labels: r.Labels().Map(),
|
||||
|
||||
@@ -46,7 +46,7 @@ func TestAnomalyRule_NoData_AlertOnAbsent(t *testing.T) {
|
||||
target := 500.0
|
||||
|
||||
postableRule := ruletypes.PostableRule{
|
||||
AlertName: valuer.NewDisplayName("Test anomaly no data"),
|
||||
AlertName: "Test anomaly no data",
|
||||
AlertType: ruletypes.AlertTypeMetric,
|
||||
RuleType: ruletypes.RuleTypeAnomaly,
|
||||
Evaluation: &ruletypes.EvaluationEnvelope{Kind: ruletypes.RollingEvaluation, Spec: ruletypes.RollingWindow{
|
||||
@@ -149,7 +149,7 @@ func TestAnomalyRule_NoData_AbsentFor(t *testing.T) {
|
||||
target := 500.0
|
||||
|
||||
postableRule := ruletypes.PostableRule{
|
||||
AlertName: valuer.NewDisplayName("Test anomaly no data with AbsentFor"),
|
||||
AlertName: "Test anomaly no data with AbsentFor",
|
||||
AlertType: ruletypes.AlertTypeMetric,
|
||||
RuleType: ruletypes.RuleTypeAnomaly,
|
||||
Evaluation: &ruletypes.EvaluationEnvelope{Kind: ruletypes.RollingEvaluation, Spec: ruletypes.RollingWindow{
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
baserules "github.com/SigNoz/signoz/pkg/query-service/rules"
|
||||
"github.com/SigNoz/signoz/pkg/types/ruletypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
)
|
||||
|
||||
func PrepareTaskFunc(opts baserules.PrepareTaskOptions) (baserules.Task, error) {
|
||||
@@ -119,7 +118,7 @@ func TestNotification(opts baserules.PrepareTestRuleOptions) (int, error) {
|
||||
}
|
||||
|
||||
parsedRule := opts.Rule
|
||||
var alertname = parsedRule.AlertName.StringValue()
|
||||
var alertname = parsedRule.AlertName
|
||||
if alertname == "" {
|
||||
// alertname is not mandatory for testing, so picking
|
||||
// a random string here
|
||||
@@ -127,7 +126,7 @@ func TestNotification(opts baserules.PrepareTestRuleOptions) (int, error) {
|
||||
}
|
||||
|
||||
// append name to indicate this is test alert
|
||||
parsedRule.AlertName = valuer.NewDisplayName(fmt.Sprintf("%s%s", alertname, ruletypes.TestAlertPostFix))
|
||||
parsedRule.AlertName = fmt.Sprintf("%s%s", alertname, ruletypes.TestAlertPostFix)
|
||||
|
||||
var rule baserules.Rule
|
||||
var err error
|
||||
|
||||
@@ -9,14 +9,12 @@ describe('ErrorResponseHandler', () => {
|
||||
.spyOn(console, 'error')
|
||||
.mockImplementation(() => undefined);
|
||||
|
||||
expect(ErrorResponseHandler(new CanceledError() as AxiosError)).toStrictEqual(
|
||||
{
|
||||
statusCode: 500,
|
||||
payload: null,
|
||||
error: 'Something went wrong',
|
||||
message: null,
|
||||
},
|
||||
);
|
||||
expect(ErrorResponseHandler(new CanceledError() as AxiosError)).toEqual({
|
||||
statusCode: 500,
|
||||
payload: null,
|
||||
error: 'Something went wrong',
|
||||
message: null,
|
||||
});
|
||||
expect(consoleError).not.toHaveBeenCalled();
|
||||
|
||||
consoleError.mockRestore();
|
||||
|
||||
@@ -18,8 +18,6 @@ import type {
|
||||
} from 'react-query';
|
||||
|
||||
import type {
|
||||
CloneRuleByID201,
|
||||
CloneRuleByIDPathParameters,
|
||||
CreateRule201,
|
||||
CreateRuleView201,
|
||||
DeleteRuleByIDPathParameters,
|
||||
@@ -965,85 +963,6 @@ export const useUpdateRuleByID = <
|
||||
> => {
|
||||
return useMutation(getUpdateRuleByIDMutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* This endpoint creates a new alert rule from the stored definition of an existing one. The clone keeps every modeled field of the source, including its enabled/disabled state, and gets the source's name suffixed with " - Copy" (or a bumped " - Copy (n)" counter when the source is itself a copy). The clone is owned by the caller.
|
||||
* @summary Clone alert rule
|
||||
*/
|
||||
export const cloneRuleByID = (
|
||||
{ id }: CloneRuleByIDPathParameters,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<CloneRuleByID201>({
|
||||
url: `/api/v2/rules/${id}/clone`,
|
||||
method: 'POST',
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getCloneRuleByIDMutationOptions = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof cloneRuleByID>>,
|
||||
TError,
|
||||
{ pathParams: CloneRuleByIDPathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof cloneRuleByID>>,
|
||||
TError,
|
||||
{ pathParams: CloneRuleByIDPathParameters },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ['cloneRuleByID'];
|
||||
const { mutation: mutationOptions } = options
|
||||
? options.mutation &&
|
||||
'mutationKey' in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey } };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof cloneRuleByID>>,
|
||||
{ pathParams: CloneRuleByIDPathParameters }
|
||||
> = (props) => {
|
||||
const { pathParams } = props ?? {};
|
||||
|
||||
return cloneRuleByID(pathParams);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type CloneRuleByIDMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof cloneRuleByID>>
|
||||
>;
|
||||
|
||||
export type CloneRuleByIDMutationError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary Clone alert rule
|
||||
*/
|
||||
export const useCloneRuleByID = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof cloneRuleByID>>,
|
||||
TError,
|
||||
{ pathParams: CloneRuleByIDPathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationResult<
|
||||
Awaited<ReturnType<typeof cloneRuleByID>>,
|
||||
TError,
|
||||
{ pathParams: CloneRuleByIDPathParameters },
|
||||
TContext
|
||||
> => {
|
||||
return useMutation(getCloneRuleByIDMutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* Returns distinct label keys from rule history entries for the selected range.
|
||||
* @summary Get rule history filter keys
|
||||
|
||||
@@ -14612,17 +14612,6 @@ export type PatchRuleByID200 = {
|
||||
export type UpdateRuleByIDPathParameters = {
|
||||
id: string;
|
||||
};
|
||||
export type CloneRuleByIDPathParameters = {
|
||||
id: string;
|
||||
};
|
||||
export type CloneRuleByID201 = {
|
||||
data: RuletypesRuleDTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type GetRuleHistoryFilterKeysPathParameters = {
|
||||
id: string;
|
||||
};
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { DrawerProps } from 'antd';
|
||||
import { ChangeViewFunctionType } from 'container/ExplorerOptions/types';
|
||||
import { AddToQueryHOCProps } from 'components/Logs/AddToQueryHOC';
|
||||
import { ActionItemProps } from 'container/LogDetailedView/LogDetailedView.types';
|
||||
import { IField } from 'types/api/logs/fields';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
|
||||
@@ -18,7 +20,9 @@ export type LogDetailProps = {
|
||||
handleOpenInExplorer?: MouseEventHandler;
|
||||
getContainer?: DrawerProps['getContainer'];
|
||||
onApplyLogFilter?: (expression: string) => void;
|
||||
} & Pick<DrawerProps, 'onClose'>;
|
||||
} & Pick<AddToQueryHOCProps, 'onAddToQuery'> &
|
||||
Partial<Pick<ActionItemProps, 'onClickActionItem'>> &
|
||||
Pick<DrawerProps, 'onClose'>;
|
||||
|
||||
export type LogDetailInnerProps = LogDetailProps & {
|
||||
log: NonNullable<LogDetailProps['log']>;
|
||||
|
||||
@@ -46,6 +46,8 @@ function renderDrawer(props: Partial<LogDetailProps> = {}): void {
|
||||
<LogDetail
|
||||
log={mockLog}
|
||||
selectedTab={VIEW_TYPES.OVERVIEW}
|
||||
onAddToQuery={jest.fn()}
|
||||
onClickActionItem={jest.fn()}
|
||||
onClose={jest.fn()}
|
||||
{...props}
|
||||
/>,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { useSavedViewEnabled } from 'hooks/useSavedViewEnabled';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import { QuickFiltersSource } from '../../types';
|
||||
import QuickFiltersLayout from '../QuickFiltersLayout';
|
||||
@@ -197,11 +197,6 @@ describe('QuickFiltersLayout', () => {
|
||||
expect(screen.queryByTestId('saved-views-panel')).not.toBeInTheDocument();
|
||||
expect(drawer()).not.toHaveClass('isOpen');
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('saved-views-open')).not.toHaveAttribute(
|
||||
'aria-busy',
|
||||
),
|
||||
);
|
||||
await user.click(screen.getByTestId('saved-views-open'));
|
||||
|
||||
expect(screen.getByTestId('saved-views-panel')).toBeInTheDocument();
|
||||
@@ -232,11 +227,6 @@ describe('QuickFiltersLayout', () => {
|
||||
'data-source',
|
||||
SavedviewtypesSourceDTO.traces,
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('saved-views-open')).not.toHaveAttribute(
|
||||
'aria-busy',
|
||||
),
|
||||
);
|
||||
await userEvent.setup().click(screen.getByTestId('saved-views-open'));
|
||||
expect(screen.getByTestId('saved-views-panel')).toHaveAttribute(
|
||||
'data-source',
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
import { useQuery } from 'react-query';
|
||||
import { Button, Tooltip } from 'antd';
|
||||
import getAllChannels from 'api/channels/getAll';
|
||||
import classNames from 'classnames';
|
||||
import { ChartLine } from '@signozhq/icons';
|
||||
import { SuccessResponseV2 } from 'types/api';
|
||||
import { useChannelOptions } from 'hooks/notificationChannels/useChannelOptions';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { Channels } from 'types/api/channels/getAll';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
import { useCreateAlertState } from '../context';
|
||||
import AdvancedOptions from '../EvaluationSettings/AdvancedOptions';
|
||||
@@ -21,14 +17,11 @@ function AlertCondition(): JSX.Element {
|
||||
const { alertType, setAlertType } = useCreateAlertState();
|
||||
|
||||
const {
|
||||
data,
|
||||
data: channels,
|
||||
isLoading: isLoadingChannels,
|
||||
isError: isErrorChannels,
|
||||
refetch: refreshChannels,
|
||||
} = useQuery<SuccessResponseV2<Channels[]>, APIError>(['getChannels'], {
|
||||
queryFn: () => getAllChannels(),
|
||||
});
|
||||
const channels = data?.data || [];
|
||||
} = useChannelOptions();
|
||||
|
||||
const showMultipleTabs =
|
||||
alertType === AlertTypes.ANOMALY_BASED_ALERT ||
|
||||
|
||||
@@ -2,12 +2,12 @@ import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { Channels } from 'types/api/channels/getAll';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
|
||||
import { CreateAlertProvider } from '../../context';
|
||||
import AlertThreshold from '../AlertThreshold';
|
||||
|
||||
const mockChannels: Channels[] = [];
|
||||
const mockChannels: ChannelOption[] = [];
|
||||
const mockRefreshChannels = jest.fn();
|
||||
const mockIsLoadingChannels = false;
|
||||
const mockIsErrorChannels = false;
|
||||
@@ -85,16 +85,17 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
}));
|
||||
|
||||
// Mock getAllChannels API
|
||||
jest.mock('api/channels/getAll', () => ({
|
||||
jest.mock('hooks/notificationChannels/useChannelOptions', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn(() =>
|
||||
Promise.resolve({
|
||||
data: [
|
||||
{ id: '1', name: 'Email Channel' },
|
||||
{ id: '2', name: 'Slack Channel' },
|
||||
] as Channels[],
|
||||
}),
|
||||
),
|
||||
useChannelOptions: jest.fn(() => ({
|
||||
data: [
|
||||
{ id: '1', name: 'Email Channel' },
|
||||
{ id: '2', name: 'Slack Channel' },
|
||||
] as ChannelOption[],
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
refetch: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
// Mock alert format categories
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { DefaultOptionType } from 'antd/es/select';
|
||||
import { createMockAlertContextState } from 'container/CreateAlertV2/EvaluationSettings/__tests__/testUtils';
|
||||
import { getAppContextMockState } from 'container/RoutingPolicies/__tests__/testUtils';
|
||||
import * as appHooks from 'providers/App/App';
|
||||
import { Channels } from 'types/api/channels/getAll';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
|
||||
import * as context from '../../context';
|
||||
import ThresholdItem from '../ThresholdItem';
|
||||
@@ -57,7 +57,7 @@ const mockThreshold = {
|
||||
color: '#ff0000',
|
||||
};
|
||||
|
||||
const mockChannels: Channels[] = [
|
||||
const mockChannels: ChannelOption[] = [
|
||||
{
|
||||
id: TEST_CONSTANTS.CHANNEL_1,
|
||||
name: TEST_CONSTANTS.EMAIL_CHANNEL_NAME,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { DefaultOptionType } from 'antd/es/select';
|
||||
import { Channels } from 'types/api/channels/getAll';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
|
||||
import {
|
||||
NotificationSettingsAction,
|
||||
@@ -21,7 +21,7 @@ export interface ThresholdItemProps {
|
||||
updateThreshold: UpdateThreshold;
|
||||
removeThreshold: (thresholdId: string) => void;
|
||||
showRemoveButton: boolean;
|
||||
channels: Channels[];
|
||||
channels: ChannelOption[];
|
||||
isLoadingChannels: boolean;
|
||||
units: DefaultOptionType[];
|
||||
isErrorChannels: boolean;
|
||||
@@ -29,7 +29,7 @@ export interface ThresholdItemProps {
|
||||
}
|
||||
|
||||
export interface AnomalyAndThresholdProps {
|
||||
channels: Channels[];
|
||||
channels: ChannelOption[];
|
||||
isLoadingChannels: boolean;
|
||||
isErrorChannels: boolean;
|
||||
refreshChannels: () => void;
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useQuery } from 'react-query';
|
||||
import { Plus } from '@signozhq/icons';
|
||||
import { Button, Flex, Form, Select, Tooltip } from 'antd';
|
||||
import { Switch } from '@signozhq/ui/switch';
|
||||
import getAll from 'api/channels/getAll';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { ALERTS_DATA_SOURCE_MAP } from 'constants/alerts';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { useChannelOptions } from 'hooks/notificationChannels/useChannelOptions';
|
||||
import useComponentPermission from 'hooks/useComponentPermission';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { SuccessResponseV2 } from 'types/api';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { AlertDef, Labels } from 'types/api/alerts/def';
|
||||
import { Channels } from 'types/api/channels/getAll';
|
||||
import APIError from 'types/api/error';
|
||||
import { requireErrorMessage } from 'utils/form/requireErrorMessage';
|
||||
import { openInNewTab } from 'utils/navigation';
|
||||
@@ -47,12 +44,13 @@ function BasicInfo({
|
||||
}: BasicInfoProps): JSX.Element {
|
||||
const { t } = useTranslation('alerts');
|
||||
|
||||
const { isLoading, data, error, isError, refetch } = useQuery<
|
||||
SuccessResponseV2<Channels[]>,
|
||||
APIError
|
||||
>(['getChannels'], {
|
||||
queryFn: () => getAll(),
|
||||
});
|
||||
const {
|
||||
isLoading,
|
||||
data: channels,
|
||||
error,
|
||||
isError,
|
||||
refetch,
|
||||
} = useChannelOptions();
|
||||
|
||||
const { user } = useAppContext();
|
||||
const [addNewChannelPermission] = useComponentPermission(
|
||||
@@ -81,7 +79,7 @@ function BasicInfo({
|
||||
});
|
||||
};
|
||||
|
||||
const noChannels = data?.data?.length === 0;
|
||||
const noChannels = channels.length === 0;
|
||||
const handleCreateNewChannels = useCallback(() => {
|
||||
logEvent('Alert: Create notification channel button clicked', {
|
||||
dataSource: ALERTS_DATA_SOURCE_MAP[alertDef?.alertType as AlertTypes],
|
||||
@@ -96,7 +94,7 @@ function BasicInfo({
|
||||
if (!isLoading && isNewRule && !hasLoggedEvent.current) {
|
||||
logEvent('Alert: New alert creation page visited', {
|
||||
dataSource: ALERTS_DATA_SOURCE_MAP[alertDef?.alertType as AlertTypes],
|
||||
numberOfChannels: data?.data?.length,
|
||||
numberOfChannels: channels.length,
|
||||
});
|
||||
hasLoggedEvent.current = true;
|
||||
}
|
||||
@@ -230,7 +228,7 @@ function BasicInfo({
|
||||
disabled={shouldBroadCastToAllChannels}
|
||||
currentValue={alertDef.preferredChannels}
|
||||
handleCreateNewChannels={handleCreateNewChannels}
|
||||
channels={data?.data || []}
|
||||
channels={channels}
|
||||
isLoading={isLoading}
|
||||
hasError={isError}
|
||||
error={error as APIError}
|
||||
|
||||
@@ -2,10 +2,10 @@ import { ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus } from '@signozhq/icons';
|
||||
import { Select, Spin } from 'antd';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
import useComponentPermission from 'hooks/useComponentPermission';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { Channels } from 'types/api/channels/getAll';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
import { StyledCreateChannelOption, StyledSelect } from './styles';
|
||||
@@ -16,7 +16,7 @@ export interface ChannelSelectProps {
|
||||
onSelectChannels: (s: string[]) => void;
|
||||
onDropdownOpen: () => void;
|
||||
isLoading: boolean;
|
||||
channels: Channels[];
|
||||
channels: ChannelOption[];
|
||||
hasError: boolean;
|
||||
error: APIError;
|
||||
handleCreateNewChannels: () => void;
|
||||
|
||||
@@ -25,8 +25,10 @@ import { InfraMonitoringEntity } from 'container/InfraMonitoringK8sV2/constants'
|
||||
import { LogsLoading } from 'container/LogsLoading/LogsLoading';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import RunQueryBtn from 'container/QueryBuilder/components/RunQueryBtn/RunQueryBtn';
|
||||
import { getOldLogsOperatorFromNew } from 'hooks/logs/useActiveLog';
|
||||
import useLogDetailHandlers from 'hooks/logs/useLogDetailHandlers';
|
||||
import useScrollToLog from 'hooks/logs/useScrollToLog';
|
||||
import { generateFilterQuery } from 'lib/logs/generateFilterQuery';
|
||||
import { saveRecentQueryByExpression } from 'lib/recentQueries/saveRecentQuery';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
@@ -80,6 +82,29 @@ function EntityLogsContent({
|
||||
const { activeLog, selectedTab, handleSetActiveLog, handleCloseLogDetail } =
|
||||
useLogDetailHandlers();
|
||||
|
||||
// TODO: Move away from using onAddToQuery after old drawer cleanup
|
||||
const onAddToQuery = useCallback(
|
||||
(fieldKey: string, fieldValue: string, operator: string): void => {
|
||||
handleCloseLogDetail();
|
||||
|
||||
const partExpression = generateFilterQuery({
|
||||
fieldKey,
|
||||
fieldValue,
|
||||
type: getOldLogsOperatorFromNew(operator),
|
||||
});
|
||||
|
||||
const currentUser = userExpression;
|
||||
const newUser = currentUser.trim()
|
||||
? `${currentUser} AND ${partExpression}`
|
||||
: partExpression;
|
||||
|
||||
querySearchOnRun(newUser);
|
||||
|
||||
logInfraDrawerFilterCustomizedEvent(category, 'logs', newUser, 'logs');
|
||||
},
|
||||
[userExpression, querySearchOnRun, handleCloseLogDetail, category],
|
||||
);
|
||||
|
||||
const onApplyLogFilter = useCallback(
|
||||
(expression: string): void => {
|
||||
handleCloseLogDetail();
|
||||
@@ -317,6 +342,8 @@ function EntityLogsContent({
|
||||
logs={logs}
|
||||
onNavigateLog={handleSetActiveLog}
|
||||
selectedTab={selectedTab}
|
||||
onAddToQuery={onAddToQuery}
|
||||
onClickActionItem={onAddToQuery}
|
||||
onApplyLogFilter={onApplyLogFilter}
|
||||
onScrollToLog={handleScrollToLog}
|
||||
handleOpenInExplorer={(e) => handleOpenInExplorer(e, activeLog)}
|
||||
|
||||
@@ -259,6 +259,8 @@ function LiveLogsList({
|
||||
selectedTab={selectedTab}
|
||||
log={activeLog}
|
||||
onClose={handleCloseLogDetail}
|
||||
onAddToQuery={onAddToQuery}
|
||||
onClickActionItem={onAddToQuery}
|
||||
handleChangeSelectedView={handleChangeSelectedView}
|
||||
logs={formattedLogs}
|
||||
onNavigateLog={handleSetActiveLog}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { MetricsType } from 'container/MetricsApplication/constant';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
|
||||
export type AnyObject = { [key: string]: any };
|
||||
|
||||
@@ -18,3 +19,15 @@ export interface DataType {
|
||||
field: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface ActionItemProps {
|
||||
fieldKey: string;
|
||||
fieldValue: string;
|
||||
onClickActionItem: (
|
||||
fieldKey: string,
|
||||
fieldValue: string,
|
||||
operator: string,
|
||||
dataType?: DataTypes,
|
||||
fieldType?: string,
|
||||
) => void;
|
||||
}
|
||||
|
||||
@@ -172,7 +172,7 @@ const normalizeDataType = (
|
||||
// key is fabricated locally (empty source list), so no click-time getAggregateKeys fetch.
|
||||
export const getFilterQueryData = (
|
||||
item: IBuilderQuery,
|
||||
target: Pick<LogFilterTarget, 'fieldKey' | 'dataType' | 'metricsType'>,
|
||||
target: LogFilterTarget,
|
||||
value: unknown,
|
||||
operator: string,
|
||||
): IBuilderQuery => {
|
||||
|
||||
@@ -381,6 +381,8 @@ function LogsExplorerList({
|
||||
selectedTab={selectedTab}
|
||||
log={activeLog}
|
||||
onClose={handleCloseLogDetail}
|
||||
onAddToQuery={onAddToQuery}
|
||||
onClickActionItem={onAddToQuery}
|
||||
handleChangeSelectedView={handleChangeSelectedView}
|
||||
logs={logs}
|
||||
onNavigateLog={handleSetActiveLog}
|
||||
|
||||
@@ -91,8 +91,13 @@ function LogsPanelComponent({
|
||||
() => logs.map((log) => FlatLogData(log) as RowData),
|
||||
[logs],
|
||||
);
|
||||
const { activeLog, selectedTab, handleSetActiveLog, handleCloseLogDetail } =
|
||||
useLogDetailHandlers();
|
||||
const {
|
||||
activeLog,
|
||||
onAddToQuery,
|
||||
selectedTab,
|
||||
handleSetActiveLog,
|
||||
handleCloseLogDetail,
|
||||
} = useLogDetailHandlers();
|
||||
|
||||
const handleRow = useCallback(
|
||||
(record: RowData): HTMLAttributes<RowData> => ({
|
||||
@@ -174,6 +179,8 @@ function LogsPanelComponent({
|
||||
selectedTab={selectedTab}
|
||||
log={activeLog}
|
||||
onClose={handleCloseLogDetail}
|
||||
onAddToQuery={onAddToQuery}
|
||||
onClickActionItem={onAddToQuery}
|
||||
isListViewPanel
|
||||
listViewPanelSelectedFields={widget?.selectedLogFields}
|
||||
logs={logs}
|
||||
|
||||
@@ -10,7 +10,8 @@ import { ILog } from 'types/api/logs/log';
|
||||
import './styles.scss';
|
||||
|
||||
function LogsList({ logs }: LogsListProps): JSX.Element {
|
||||
const { activeLog, onSetActiveLog, onClearActiveLog } = useActiveLog();
|
||||
const { activeLog, onSetActiveLog, onClearActiveLog, onAddToQuery } =
|
||||
useActiveLog();
|
||||
|
||||
const makeLogDetailsHandler = (log: ILog) => (): void => onSetActiveLog(log);
|
||||
|
||||
@@ -44,6 +45,8 @@ function LogsList({ logs }: LogsListProps): JSX.Element {
|
||||
selectedTab={VIEW_TYPES.OVERVIEW}
|
||||
log={activeLog}
|
||||
onClose={onClearActiveLog}
|
||||
onAddToQuery={onAddToQuery}
|
||||
onClickActionItem={onAddToQuery}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -329,7 +329,7 @@ describe('transformTransactionGroupsToResourcePermissions', () => {
|
||||
it('returns all resources from RESOURCE_ORDER even with empty transaction groups', () => {
|
||||
const result = transformTransactionGroupsToResourcePermissions([]);
|
||||
|
||||
expect(result).toHaveLength(12);
|
||||
expect(result).toHaveLength(11);
|
||||
expect(result.map((r) => r.resourceKind)).toStrictEqual([
|
||||
'factor-api-key',
|
||||
'dashboard',
|
||||
@@ -339,7 +339,6 @@ describe('transformTransactionGroupsToResourcePermissions', () => {
|
||||
'metrics',
|
||||
'quick-filter',
|
||||
'role',
|
||||
'saved-view',
|
||||
'serviceaccount',
|
||||
'subscription',
|
||||
'traces',
|
||||
@@ -423,7 +422,7 @@ describe('createEmptyRolePermissions', () => {
|
||||
it('creates permissions for all resources in RESOURCE_ORDER', () => {
|
||||
const result = createEmptyRolePermissions();
|
||||
|
||||
expect(result).toHaveLength(12);
|
||||
expect(result).toHaveLength(11);
|
||||
expect(result.map((r) => r.resourceKind)).toStrictEqual([
|
||||
'factor-api-key',
|
||||
'dashboard',
|
||||
@@ -433,7 +432,6 @@ describe('createEmptyRolePermissions', () => {
|
||||
'metrics',
|
||||
'quick-filter',
|
||||
'role',
|
||||
'saved-view',
|
||||
'serviceaccount',
|
||||
'subscription',
|
||||
'traces',
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
Logs,
|
||||
Receipt,
|
||||
Shield,
|
||||
TowerControl,
|
||||
} from '@signozhq/icons';
|
||||
|
||||
import permissionsType from 'lib/authz/hooks/useAuthZ/permissions.type';
|
||||
@@ -96,14 +95,6 @@ export const RESOURCE_PANELS: Record<AuthZResource, ResourcePanelConfig> = {
|
||||
'Type quick filter ID, separate multiple with comma or space',
|
||||
docsAnchor: 'quick-filter',
|
||||
},
|
||||
'saved-view': {
|
||||
label: 'Saved Views',
|
||||
description: 'Saved views in the logs, traces, metrics and meter explorers.',
|
||||
icon: TowerControl,
|
||||
selectorPlaceholder:
|
||||
'Type saved view ID, separate multiple with comma or space',
|
||||
docsAnchor: 'saved-view',
|
||||
},
|
||||
logs: {
|
||||
label: 'Logs',
|
||||
description: 'Log data collected across the workspace.',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ApiRoutingPolicy } from 'api/routingPolicies/getRoutingPolicies';
|
||||
import { IAppContext, IUser } from 'providers/App/types';
|
||||
import { Channels } from 'types/api/channels/getAll';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
|
||||
import { RoutingPolicy, UseRoutingPoliciesReturn } from '../types';
|
||||
|
||||
@@ -28,21 +28,13 @@ export const MOCK_ROUTING_POLICY_2: RoutingPolicy = {
|
||||
updatedBy: 'user2@signoz.io',
|
||||
};
|
||||
|
||||
export const MOCK_CHANNEL_1: Channels = {
|
||||
export const MOCK_CHANNEL_1: ChannelOption = {
|
||||
name: 'Channel 1',
|
||||
created_at: '2021-01-01',
|
||||
data: 'data 1',
|
||||
id: '1',
|
||||
type: 'type 1',
|
||||
updated_at: '2021-01-01',
|
||||
};
|
||||
export const MOCK_CHANNEL_2: Channels = {
|
||||
export const MOCK_CHANNEL_2: ChannelOption = {
|
||||
name: 'Channel 2',
|
||||
created_at: '2021-01-02',
|
||||
data: 'data 2',
|
||||
id: '2',
|
||||
type: 'type 2',
|
||||
updated_at: '2021-01-02',
|
||||
};
|
||||
|
||||
export function getUseRoutingPoliciesMockData(
|
||||
|
||||
@@ -77,12 +77,14 @@ jest.mock('hooks/routingPolicies/useDeleteRoutingPolicy', () => ({
|
||||
isLoading: false,
|
||||
}),
|
||||
}));
|
||||
jest.mock('api/channels/getAll', () => ({
|
||||
jest.mock('hooks/notificationChannels/useChannelOptions', () => ({
|
||||
__esModule: true,
|
||||
default: (): any =>
|
||||
Promise.resolve({
|
||||
data: [MOCK_CHANNEL_1, MOCK_CHANNEL_2],
|
||||
}),
|
||||
useChannelOptions: (): any => ({
|
||||
data: [MOCK_CHANNEL_1, MOCK_CHANNEL_2],
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
refetch: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
const ROUTING_POLICY_1_NAME = 'Routing Policy 1';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Channels } from 'types/api/channels/getAll';
|
||||
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
|
||||
|
||||
export interface RoutingPolicy {
|
||||
id: string;
|
||||
@@ -62,7 +62,7 @@ export interface RoutingPolicyDetailsProps {
|
||||
routingPolicy: RoutingPolicy | null;
|
||||
closeModal: () => void;
|
||||
mode: PolicyDetailsModalMode;
|
||||
channels: Channels[];
|
||||
channels: ChannelOption[];
|
||||
isErrorChannels: boolean;
|
||||
isLoadingChannels: boolean;
|
||||
handlePolicyDetailsModalAction: HandlePolicyDetailsModalAction;
|
||||
@@ -86,7 +86,7 @@ export interface UseRoutingPoliciesReturn {
|
||||
isErrorRoutingPolicies: boolean;
|
||||
refetchRoutingPolicies: () => void;
|
||||
// Channels
|
||||
channels: Channels[];
|
||||
channels: ChannelOption[];
|
||||
isLoadingChannels: boolean;
|
||||
isErrorChannels: boolean;
|
||||
refreshChannels: () => void;
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useQuery, useQueryClient } from 'react-query';
|
||||
import { useQueryClient } from 'react-query';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import getAllChannels from 'api/channels/getAll';
|
||||
import { GetRoutingPoliciesResponse } from 'api/routingPolicies/getRoutingPolicies';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
import { useCreateRoutingPolicy } from 'hooks/routingPolicies/useCreateRoutingPolicy';
|
||||
import { useDeleteRoutingPolicy } from 'hooks/routingPolicies/useDeleteRoutingPolicy';
|
||||
import { useChannelOptions } from 'hooks/notificationChannels/useChannelOptions';
|
||||
import { useGetRoutingPolicies } from 'hooks/routingPolicies/useGetRoutingPolicies';
|
||||
import { useUpdateRoutingPolicy } from 'hooks/routingPolicies/useUpdateRoutingPolicy';
|
||||
import useDebouncedFn from 'hooks/useDebouncedFunction';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { SuccessResponseV2 } from 'types/api';
|
||||
import { Channels } from 'types/api/channels/getAll';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
import {
|
||||
PolicyDetailsModalMode,
|
||||
@@ -83,14 +81,11 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
|
||||
|
||||
// Channels list
|
||||
const {
|
||||
data,
|
||||
data: channels,
|
||||
isLoading: isLoadingChannels,
|
||||
isError: isErrorChannels,
|
||||
refetch: refetchChannels,
|
||||
} = useQuery<SuccessResponseV2<Channels[]>, APIError>(['getChannels'], {
|
||||
queryFn: () => getAllChannels(),
|
||||
});
|
||||
const channels = data?.data || [];
|
||||
} = useChannelOptions();
|
||||
|
||||
const refreshChannels = (): void => {
|
||||
refetchChannels();
|
||||
|
||||
@@ -1,50 +1,41 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Check } from '@signozhq/icons';
|
||||
import AuthZDropdown from 'lib/authz/components/AuthZDropdown/AuthZDropdown';
|
||||
import type { AuthZDropdownItemType } from 'lib/authz/components/AuthZDropdown/types';
|
||||
import {
|
||||
buildSavedViewUpdatePermission,
|
||||
SavedViewCreatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
|
||||
import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
|
||||
|
||||
import SavedViewsIconButton from './SavedViewsIconButton';
|
||||
import { SaveChangesMenuProps } from './types';
|
||||
|
||||
function SaveChangesMenu({
|
||||
viewId,
|
||||
disabled,
|
||||
onSaveAsNew,
|
||||
onUpdate,
|
||||
}: SaveChangesMenuProps): JSX.Element {
|
||||
const items = useMemo<AuthZDropdownItemType[]>(
|
||||
const items = useMemo<DropdownItemType[]>(
|
||||
() => [
|
||||
{
|
||||
type: 'item',
|
||||
value: 'save-as-new',
|
||||
label: 'Save as new view',
|
||||
checks: [SavedViewCreatePermission],
|
||||
onClick: onSaveAsNew,
|
||||
},
|
||||
{
|
||||
type: 'item',
|
||||
value: 'update',
|
||||
label: 'Update selected view',
|
||||
checks: [buildSavedViewUpdatePermission(viewId)],
|
||||
onClick: onUpdate,
|
||||
},
|
||||
],
|
||||
[viewId, onSaveAsNew, onUpdate],
|
||||
[onSaveAsNew, onUpdate],
|
||||
);
|
||||
|
||||
return (
|
||||
<AuthZDropdown
|
||||
<Dropdown
|
||||
items={items}
|
||||
nativeButton
|
||||
align="end"
|
||||
side="bottom"
|
||||
disabled={disabled}
|
||||
disabledTooltip="Saving the view"
|
||||
testId="saved-views-save-changes"
|
||||
>
|
||||
<SavedViewsIconButton
|
||||
title="Save changes"
|
||||
@@ -52,7 +43,7 @@ function SaveChangesMenu({
|
||||
color="warning"
|
||||
testId="saved-views-save-changes"
|
||||
/>
|
||||
</AuthZDropdown>
|
||||
</Dropdown>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useState } from 'react';
|
||||
import { Plus } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
|
||||
import { SavedViewCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
|
||||
|
||||
import SaveViewModal from './SaveViewModal';
|
||||
import { SavedViewsEmptyStateProps } from './types';
|
||||
@@ -32,8 +31,7 @@ function SavedViewsEmptyState({
|
||||
<Typography.Text className={styles.stateText}>
|
||||
Save the current view to open it later.
|
||||
</Typography.Text>
|
||||
<AuthZButton
|
||||
checks={[SavedViewCreatePermission]}
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
@@ -42,7 +40,7 @@ function SavedViewsEmptyState({
|
||||
testId="saved-views-list-create"
|
||||
>
|
||||
Create view
|
||||
</AuthZButton>
|
||||
</Button>
|
||||
{isModalOpen && (
|
||||
<SaveViewModal
|
||||
mode="create"
|
||||
|
||||
@@ -78,7 +78,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
gap: var(--spacing-4);
|
||||
gap: var(--spacing-1);
|
||||
}
|
||||
|
||||
.collapseIcon {
|
||||
|
||||
@@ -5,17 +5,9 @@ import { Skeleton } from '@signozhq/ui/skeleton';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { useGetSavedViewParams } from 'hooks/saveViews/useGetSavedViewParams';
|
||||
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
|
||||
import {
|
||||
buildSavedViewReadPermission,
|
||||
SavedViewCreatePermission,
|
||||
SavedViewListPermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
|
||||
|
||||
import {
|
||||
MY_VIEW_NAME,
|
||||
SAVED_VIEW_FORBIDDEN_NAME,
|
||||
SAVED_VIEW_LOAD_FAILED_NAME,
|
||||
SAVED_VIEW_TOAST_POSITION,
|
||||
} from './constants';
|
||||
@@ -39,16 +31,8 @@ function SavedViewsHeader({
|
||||
onOpenViews?: () => void;
|
||||
onCollapse?: () => void;
|
||||
}): JSX.Element {
|
||||
const {
|
||||
view,
|
||||
isLoading,
|
||||
isError,
|
||||
isReadDenied,
|
||||
errorMessage,
|
||||
hasUnsavedChanges,
|
||||
} = useActiveSavedView(source);
|
||||
const { viewKey } = useGetSavedViewParams();
|
||||
const readPermission = buildSavedViewReadPermission(viewKey);
|
||||
const { view, isLoading, isError, hasUnsavedChanges } =
|
||||
useActiveSavedView(source);
|
||||
const { revertView, clearView, createView, updateView, isSaving } =
|
||||
useSavedViewActions(source);
|
||||
|
||||
@@ -65,27 +49,11 @@ function SavedViewsHeader({
|
||||
const openSaveAsNew = useCallback((): void => setModalMode('saveAsNew'), []);
|
||||
const closeModal = useCallback((): void => setModalMode(null), []);
|
||||
|
||||
let name = view?.spec.displayName ?? MY_VIEW_NAME;
|
||||
if (isReadDenied) {
|
||||
name = SAVED_VIEW_FORBIDDEN_NAME;
|
||||
} else if (isError) {
|
||||
name = SAVED_VIEW_LOAD_FAILED_NAME;
|
||||
}
|
||||
const name = isError
|
||||
? SAVED_VIEW_LOAD_FAILED_NAME
|
||||
: (view?.spec.displayName ?? MY_VIEW_NAME);
|
||||
const isDirty = !isError && !!view && hasUnsavedChanges;
|
||||
|
||||
const nameChip = (
|
||||
<span
|
||||
className={cx(styles.name, {
|
||||
[styles.isDirty]: isDirty,
|
||||
[styles.isError]: isError,
|
||||
})}
|
||||
data-testid="saved-views-name"
|
||||
>
|
||||
{isDirty && <span className={styles.dot} />}
|
||||
<span className={styles.nameText}>{name}</span>
|
||||
</span>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(styles.header, {
|
||||
@@ -100,7 +68,6 @@ function SavedViewsHeader({
|
||||
<SavedViewsIconButton
|
||||
title="All views"
|
||||
icon={<List size={14} />}
|
||||
checks={[SavedViewListPermission]}
|
||||
onClick={onOpenViews}
|
||||
testId="saved-views-open"
|
||||
/>
|
||||
@@ -112,10 +79,19 @@ function SavedViewsHeader({
|
||||
className={styles.skeleton}
|
||||
testId="saved-views-loading"
|
||||
/>
|
||||
) : isReadDenied ? (
|
||||
<AuthZTooltip checks={[readPermission]}>{nameChip}</AuthZTooltip>
|
||||
) : (
|
||||
<Tooltip title={errorMessage ?? name}>{nameChip}</Tooltip>
|
||||
<Tooltip title={name}>
|
||||
<span
|
||||
className={cx(styles.name, {
|
||||
[styles.isDirty]: isDirty,
|
||||
[styles.isError]: isError,
|
||||
})}
|
||||
data-testid="saved-views-name"
|
||||
>
|
||||
{isDirty && <span className={styles.dot} />}
|
||||
<span className={styles.nameText}>{name}</span>
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -126,7 +102,6 @@ function SavedViewsHeader({
|
||||
icon={<Plus size={14} />}
|
||||
disabled={isLoading}
|
||||
disabledTooltip="Loading views"
|
||||
checks={[SavedViewCreatePermission]}
|
||||
onClick={(): void => setModalMode('create')}
|
||||
testId="saved-views-create"
|
||||
/>
|
||||
@@ -142,7 +117,6 @@ function SavedViewsHeader({
|
||||
{view && isDirty && (
|
||||
<>
|
||||
<SaveChangesMenu
|
||||
viewId={view.id}
|
||||
disabled={isSaving}
|
||||
onSaveAsNew={openSaveAsNew}
|
||||
onUpdate={(): void => {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { forwardRef } from 'react';
|
||||
import { Button, type VariantColorType } from '@signozhq/ui/button';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
|
||||
|
||||
import { SavedViewsIconButtonProps } from './types';
|
||||
|
||||
@@ -26,33 +25,11 @@ const SavedViewsIconButton = forwardRef<
|
||||
color = 'secondary',
|
||||
disabled,
|
||||
disabledTooltip,
|
||||
checks,
|
||||
onClick,
|
||||
...triggerProps
|
||||
},
|
||||
ref,
|
||||
): JSX.Element {
|
||||
if (checks?.length) {
|
||||
return (
|
||||
<Tooltip title={title}>
|
||||
<AuthZButton
|
||||
checks={checks}
|
||||
{...VARIANT_COLORS[color]}
|
||||
size="sm"
|
||||
icon
|
||||
aria-label={title}
|
||||
disabled={disabled}
|
||||
// AuthZButton skips its checks while a block reason is set.
|
||||
disabledTooltip={disabled ? disabledTooltip : undefined}
|
||||
onClick={onClick}
|
||||
testId={testId}
|
||||
>
|
||||
{icon}
|
||||
</AuthZButton>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip title={title}>
|
||||
<Button
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
gap: var(--spacing-2);
|
||||
height: var(--spacing-16);
|
||||
padding-right: var(--spacing-4);
|
||||
border-radius: var(--radius-2);
|
||||
@@ -71,7 +71,7 @@
|
||||
|
||||
.row:hover .rowMenu,
|
||||
.row:focus-within .rowMenu,
|
||||
.rowMenu:has([data-popup-open]) {
|
||||
.rowMenu:has([data-state='open']) {
|
||||
width: auto;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
@@ -40,14 +40,8 @@ function SavedViewsList({
|
||||
const saveNewView = useSaveNewView(createView);
|
||||
const { createdByMe, createdByOthers, isLoading, isError, refetch } =
|
||||
useSavedViewsList(source, search);
|
||||
const {
|
||||
copyViewLink,
|
||||
copyViewId,
|
||||
renameView,
|
||||
deleteView,
|
||||
isRenaming,
|
||||
isDeleting,
|
||||
} = useSavedViewRowActions(source);
|
||||
const { copyViewLink, renameView, deleteView, isRenaming, isDeleting } =
|
||||
useSavedViewRowActions(source);
|
||||
const [pendingAction, setPendingAction] =
|
||||
useState<PendingSavedViewAction | null>(null);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
@@ -85,14 +79,10 @@ function SavedViewsList({
|
||||
copyViewLink(view);
|
||||
return;
|
||||
}
|
||||
if (key === 'copyId') {
|
||||
copyViewId(view);
|
||||
return;
|
||||
}
|
||||
closeHoverCard();
|
||||
setPendingAction({ key, view });
|
||||
},
|
||||
[copyViewLink, copyViewId, closeHoverCard],
|
||||
[copyViewLink, closeHoverCard],
|
||||
);
|
||||
|
||||
const closePendingAction = useCallback((): void => setPendingAction(null), []);
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import cx from 'classnames';
|
||||
import { Undo2 } from '@signozhq/icons';
|
||||
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
|
||||
import { buildSavedViewReadPermission } from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
|
||||
import SavedViewsRowButton from './SavedViewsRowButton';
|
||||
import SavedViewsRowMenu from './SavedViewsRowMenu';
|
||||
@@ -19,26 +17,17 @@ function SavedViewsListRow({
|
||||
hover,
|
||||
}: SavedViewsListRowProps): JSX.Element {
|
||||
const name = view.spec.displayName;
|
||||
const readPermission = buildSavedViewReadPermission(view.id);
|
||||
// Same cached check as the button; gates the hover card.
|
||||
const { isLoading, deniedPermissions } = useAuthZ([readPermission]);
|
||||
const canRead = !isLoading && deniedPermissions.length === 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(styles.row, { [styles.isActive]: isActive })}
|
||||
data-testid="saved-views-row"
|
||||
data-view-id={view.id}
|
||||
onMouseEnter={(event): void => {
|
||||
if (canRead) {
|
||||
hover.onRowEnter(view, event.currentTarget);
|
||||
}
|
||||
}}
|
||||
onMouseEnter={(event): void => hover.onRowEnter(view, event.currentTarget)}
|
||||
onMouseLeave={hover.onRowLeave}
|
||||
>
|
||||
<div className={styles.rowName}>
|
||||
<AuthZButton
|
||||
checks={[readPermission]}
|
||||
<Button
|
||||
size="md"
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
@@ -52,7 +41,7 @@ function SavedViewsListRow({
|
||||
testId="saved-views-row-name"
|
||||
>
|
||||
{name}
|
||||
</AuthZButton>
|
||||
</Button>
|
||||
</div>
|
||||
{isActive && (
|
||||
<SavedViewsRowButton
|
||||
@@ -65,7 +54,6 @@ function SavedViewsListRow({
|
||||
)}
|
||||
<span className={styles.rowMenu}>
|
||||
<SavedViewsRowMenu
|
||||
viewId={view.id}
|
||||
onAction={(key): void => onAction(view, key)}
|
||||
onOpen={hover.onMenuOpen}
|
||||
/>
|
||||
|
||||
@@ -4,9 +4,6 @@ import { Input } from '@signozhq/ui/input';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { AuthZGuardContent } from 'lib/authz/components/AuthZGuard/AuthZGuardContent';
|
||||
import { SavedViewListPermission } from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
|
||||
|
||||
import SavedViewsIconButton from './SavedViewsIconButton';
|
||||
import SavedViewsList from './SavedViewsList';
|
||||
|
||||
@@ -42,20 +39,16 @@ function SavedViewsPanel({
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<AuthZGuardContent checks={[SavedViewListPermission]}>
|
||||
<>
|
||||
<div className={styles.search}>
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(event): void => setSearch(event.target.value)}
|
||||
placeholder="Search..."
|
||||
aria-label="Search views"
|
||||
testId="saved-views-search"
|
||||
/>
|
||||
</div>
|
||||
<SavedViewsList source={source} search={search} />
|
||||
</>
|
||||
</AuthZGuardContent>
|
||||
<div className={styles.search}>
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(event): void => setSearch(event.target.value)}
|
||||
placeholder="Search..."
|
||||
aria-label="Search views"
|
||||
testId="saved-views-search"
|
||||
/>
|
||||
</div>
|
||||
<SavedViewsList source={source} search={search} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Ellipsis } from '@signozhq/icons';
|
||||
import AuthZDropdown from 'lib/authz/components/AuthZDropdown/AuthZDropdown';
|
||||
import type { AuthZDropdownItemType } from 'lib/authz/components/AuthZDropdown/types';
|
||||
import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
|
||||
|
||||
import { SAVED_VIEW_ROW_ACTIONS } from './constants';
|
||||
import SavedViewsRowButton from './SavedViewsRowButton';
|
||||
import { SavedViewsRowMenuProps } from './types';
|
||||
|
||||
function SavedViewsRowMenu({
|
||||
viewId,
|
||||
onAction,
|
||||
onOpen,
|
||||
}: SavedViewsRowMenuProps): JSX.Element {
|
||||
const items = useMemo<AuthZDropdownItemType[]>(
|
||||
const items = useMemo<DropdownItemType[]>(
|
||||
() =>
|
||||
SAVED_VIEW_ROW_ACTIONS.flatMap(
|
||||
({
|
||||
@@ -21,8 +19,7 @@ function SavedViewsRowMenu({
|
||||
icon: Icon,
|
||||
danger,
|
||||
hasDividerBefore,
|
||||
buildPermission,
|
||||
}): AuthZDropdownItemType[] => [
|
||||
}): DropdownItemType[] => [
|
||||
...(hasDividerBefore
|
||||
? [{ type: 'separator' as const, value: `separator-${key}` }]
|
||||
: []),
|
||||
@@ -32,16 +29,15 @@ function SavedViewsRowMenu({
|
||||
label,
|
||||
prefix: <Icon size={14} />,
|
||||
danger,
|
||||
checks: buildPermission ? [buildPermission(viewId)] : undefined,
|
||||
onClick: (): void => onAction(key),
|
||||
},
|
||||
],
|
||||
),
|
||||
[viewId, onAction],
|
||||
[onAction],
|
||||
);
|
||||
|
||||
return (
|
||||
<AuthZDropdown
|
||||
<Dropdown
|
||||
items={items}
|
||||
nativeButton
|
||||
side="right"
|
||||
@@ -51,7 +47,6 @@ function SavedViewsRowMenu({
|
||||
onOpen();
|
||||
}
|
||||
}}
|
||||
testId="saved-views-row-menu"
|
||||
>
|
||||
<SavedViewsRowButton
|
||||
icon={<Ellipsis size={14} />}
|
||||
@@ -59,7 +54,7 @@ function SavedViewsRowMenu({
|
||||
tooltip="More options"
|
||||
testId="saved-views-row-menu"
|
||||
/>
|
||||
</AuthZDropdown>
|
||||
</Dropdown>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
import {
|
||||
act,
|
||||
fireEvent,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from '@testing-library/react';
|
||||
import { act, fireEvent, screen, within } from '@testing-library/react';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import ROUTES from 'constants/routes';
|
||||
@@ -18,7 +12,6 @@ import {
|
||||
import SavedViewsPanel from '../SavedViewsPanel';
|
||||
import { mockSavedViewsApi } from './savedViewsApiMock';
|
||||
import {
|
||||
expectUsable,
|
||||
explorerUrl,
|
||||
makeView,
|
||||
queryWith,
|
||||
@@ -117,11 +110,6 @@ async function renderPanel(
|
||||
dataSource,
|
||||
);
|
||||
await screen.findByTestId('saved-views-list');
|
||||
await waitFor(() =>
|
||||
screen
|
||||
.getAllByTestId('saved-views-row-name')
|
||||
.forEach((name) => expectUsable(name)),
|
||||
);
|
||||
jest.useFakeTimers();
|
||||
}
|
||||
|
||||
@@ -152,10 +140,6 @@ describe('SavedViewHoverCard', () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// useAuthZ batches checks on a timer; left pending, it blocks later checks.
|
||||
act(() => {
|
||||
jest.runOnlyPendingTimers();
|
||||
});
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,265 +0,0 @@
|
||||
import { fireEvent, screen, waitFor, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import ROUTES from 'constants/routes';
|
||||
import {
|
||||
buildSavedViewDeletePermission,
|
||||
buildSavedViewReadPermission,
|
||||
buildSavedViewUpdatePermission,
|
||||
SavedViewCreatePermission,
|
||||
SavedViewListPermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
|
||||
import {
|
||||
AUTHZ_CHECK_URL,
|
||||
setupAuthzDeny,
|
||||
} from 'lib/authz/utils/authz-test-utils';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import SavedViewsHeader from '../SavedViewsHeader';
|
||||
import SavedViewsPanel from '../SavedViewsPanel';
|
||||
import { API, mockSavedViewsApi } from './savedViewsApiMock';
|
||||
import {
|
||||
explorerUrl,
|
||||
makeView,
|
||||
MENU_CHECK_TIMEOUT,
|
||||
queryWith,
|
||||
renderWithExplorerProviders,
|
||||
viewUrl,
|
||||
} from './savedViewsTestUtils';
|
||||
|
||||
const PATH = ROUTES.TRACES_EXPLORER;
|
||||
|
||||
const errors = makeView({ id: 'view-1', displayName: 'Errors' });
|
||||
const slow = makeView({ id: 'view-2', displayName: 'Slow spans' });
|
||||
|
||||
function renderPanel(url = explorerUrl(PATH, {})): void {
|
||||
renderWithExplorerProviders(
|
||||
<SavedViewsPanel
|
||||
source={SavedviewtypesSourceDTO.traces}
|
||||
onClose={jest.fn()}
|
||||
/>,
|
||||
url,
|
||||
);
|
||||
}
|
||||
|
||||
function renderHeader(
|
||||
url: string,
|
||||
): ReturnType<typeof renderWithExplorerProviders> {
|
||||
return renderWithExplorerProviders(
|
||||
<SavedViewsHeader
|
||||
source={SavedviewtypesSourceDTO.traces}
|
||||
onOpenViews={jest.fn()}
|
||||
/>,
|
||||
url,
|
||||
);
|
||||
}
|
||||
|
||||
const rowNamed = (name: string): HTMLElement =>
|
||||
screen
|
||||
.getAllByTestId('saved-views-row')
|
||||
.find((row) => row.textContent?.includes(name)) as HTMLElement;
|
||||
|
||||
async function openRowMenu(name: string): Promise<void> {
|
||||
await screen.findAllByTestId('saved-views-row');
|
||||
fireEvent.click(within(rowNamed(name)).getByTestId('saved-views-row-menu'));
|
||||
}
|
||||
|
||||
// Resolves once the row's check is back, so its state is final.
|
||||
async function settledRow(testId: string): Promise<HTMLElement> {
|
||||
await waitFor(
|
||||
() => expect(screen.getByTestId(testId)).not.toHaveAttribute('data-loading'),
|
||||
MENU_CHECK_TIMEOUT,
|
||||
);
|
||||
return screen.getByTestId(testId);
|
||||
}
|
||||
|
||||
describe('SavedViews - AuthZ', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('shows the denied callout instead of the list without list', async () => {
|
||||
mockSavedViewsApi([errors]);
|
||||
server.use(setupAuthzDeny(SavedViewListPermission));
|
||||
renderPanel();
|
||||
|
||||
await expect(
|
||||
screen.findByText(/not authorized/i),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('saved-views-list')).toBeNull();
|
||||
expect(screen.queryByTestId('saved-views-search')).toBeNull();
|
||||
});
|
||||
|
||||
it('disables only the views it cannot read', async () => {
|
||||
mockSavedViewsApi([errors, slow]);
|
||||
server.use(setupAuthzDeny(buildSavedViewReadPermission(errors.id)));
|
||||
renderPanel();
|
||||
|
||||
await screen.findAllByTestId('saved-views-row');
|
||||
const nameOf = (view: string): HTMLElement =>
|
||||
within(rowNamed(view)).getByTestId('saved-views-row-name');
|
||||
await waitFor(() =>
|
||||
expect(nameOf('Errors')).toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(nameOf('Slow spans')).not.toHaveAttribute('aria-busy'),
|
||||
);
|
||||
expect(nameOf('Slow spans')).not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
it('keeps the row menu on a view it cannot read', async () => {
|
||||
mockSavedViewsApi([errors]);
|
||||
server.use(setupAuthzDeny(buildSavedViewReadPermission(errors.id)));
|
||||
renderPanel();
|
||||
|
||||
await openRowMenu('Errors');
|
||||
|
||||
await expect(
|
||||
settledRow('saved-views-row-menu-item-delete'),
|
||||
).resolves.not.toHaveAttribute('data-disabled');
|
||||
await expect(
|
||||
settledRow('saved-views-row-menu-item-editDetails'),
|
||||
).resolves.not.toHaveAttribute('data-disabled');
|
||||
await expect(
|
||||
settledRow('saved-views-row-menu-item-copyLink'),
|
||||
).resolves.not.toHaveAttribute('data-disabled');
|
||||
});
|
||||
|
||||
it('disables creating without create', async () => {
|
||||
mockSavedViewsApi([]);
|
||||
server.use(setupAuthzDeny(SavedViewCreatePermission));
|
||||
renderPanel();
|
||||
renderHeader(explorerUrl(PATH, {}));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('saved-views-list-create')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('saved-views-create')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps create disabled while the check is pending', async () => {
|
||||
mockSavedViewsApi([]);
|
||||
server.use(
|
||||
rest.post(AUTHZ_CHECK_URL, (_req, res, ctx) => res(ctx.delay('infinite'))),
|
||||
);
|
||||
renderHeader(explorerUrl(PATH, {}));
|
||||
|
||||
const create = screen.getByTestId('saved-views-create');
|
||||
expect(create).toHaveAttribute('aria-busy', 'true');
|
||||
await userEvent.click(create);
|
||||
expect(screen.queryByTestId('save-view-name')).toBeNull();
|
||||
});
|
||||
|
||||
it('disables edit details without update and delete without delete', async () => {
|
||||
mockSavedViewsApi([errors]);
|
||||
server.use(
|
||||
setupAuthzDeny(
|
||||
buildSavedViewUpdatePermission(errors.id),
|
||||
buildSavedViewDeletePermission(errors.id),
|
||||
),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await openRowMenu('Errors');
|
||||
|
||||
await expect(
|
||||
settledRow('saved-views-row-menu-item-editDetails'),
|
||||
).resolves.toHaveAttribute('data-disabled');
|
||||
await expect(
|
||||
settledRow('saved-views-row-menu-item-delete'),
|
||||
).resolves.toHaveAttribute('data-disabled');
|
||||
await expect(
|
||||
settledRow('saved-views-row-menu-item-copyLink'),
|
||||
).resolves.not.toHaveAttribute('data-disabled');
|
||||
});
|
||||
|
||||
it('disables updating the open view without update, keeping save as new', async () => {
|
||||
mockSavedViewsApi([errors]);
|
||||
server.use(setupAuthzDeny(buildSavedViewUpdatePermission(errors.id)));
|
||||
const { history } = renderHeader(viewUrl(PATH, errors));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('saved-views-name')).toHaveTextContent('Errors'),
|
||||
);
|
||||
|
||||
history.push(
|
||||
explorerUrl(PATH, {
|
||||
query: queryWith(DataSource.TRACES, 'has_error = false'),
|
||||
panelType: PANEL_TYPES.LIST,
|
||||
viewKey: errors.id,
|
||||
}),
|
||||
);
|
||||
await userEvent.click(await screen.findByTestId('saved-views-save-changes'));
|
||||
|
||||
await expect(
|
||||
settledRow('saved-views-save-changes-item-update'),
|
||||
).resolves.toHaveAttribute('data-disabled');
|
||||
await expect(
|
||||
settledRow('saved-views-save-changes-item-save-as-new'),
|
||||
).resolves.not.toHaveAttribute('data-disabled');
|
||||
});
|
||||
|
||||
it('says no access when the check denies read, even if the server returns the view', async () => {
|
||||
mockSavedViewsApi([errors]);
|
||||
server.use(setupAuthzDeny(buildSavedViewReadPermission(errors.id)));
|
||||
renderHeader(viewUrl(PATH, errors));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('saved-views-name')).toHaveTextContent(
|
||||
'No view access',
|
||||
),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('saved-views-name')).toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
),
|
||||
);
|
||||
await userEvent.setup().hover(screen.getByTestId('saved-views-name'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.queryAllByText(/is not authorized to perform read:saved-view:view-1/)
|
||||
.length,
|
||||
).toBeGreaterThan(0),
|
||||
);
|
||||
});
|
||||
|
||||
it('treats a 403 the check allowed as a failed load, showing the server message', async () => {
|
||||
const message = 'saved-view:read is missing, ask an admin for it';
|
||||
mockSavedViewsApi([errors]);
|
||||
server.use(
|
||||
rest.get(`${API}/:id`, (_req, res, ctx) =>
|
||||
res(
|
||||
ctx.status(403),
|
||||
ctx.json({ status: 'error', error: { code: 'forbidden', message } }),
|
||||
),
|
||||
),
|
||||
);
|
||||
renderHeader(viewUrl(PATH, errors));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('saved-views-name')).toHaveTextContent(
|
||||
'View failed to load',
|
||||
),
|
||||
);
|
||||
await userEvent.setup().hover(screen.getByTestId('saved-views-name'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.queryAllByText(message).length).toBeGreaterThan(0),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -9,9 +9,7 @@ import { usePreferenceContext } from 'providers/preferences/context/PreferenceCo
|
||||
import SavedViewsHeader from '../SavedViewsHeader';
|
||||
import { mockSavedViewsApi } from './savedViewsApiMock';
|
||||
import {
|
||||
expectRowUsable,
|
||||
makeView,
|
||||
MENU_CHECK_TIMEOUT,
|
||||
renderWithExplorerProviders,
|
||||
viewUrl,
|
||||
} from './savedViewsTestUtils';
|
||||
@@ -117,11 +115,9 @@ describe('SavedViewsHeader columns', () => {
|
||||
await userEvent.click(screen.getByTestId('add-column'));
|
||||
await waitFor(() => expect(isDirty()).toBe(true));
|
||||
await userEvent.click(screen.getByTestId('saved-views-save-changes'));
|
||||
const update = await screen.findByTestId(
|
||||
'saved-views-save-changes-item-update',
|
||||
await userEvent.click(
|
||||
await screen.findByRole('menuitem', { name: 'Update selected view' }),
|
||||
);
|
||||
await waitFor(() => expectRowUsable(update), MENU_CHECK_TIMEOUT);
|
||||
await userEvent.click(update);
|
||||
await waitFor(() => expect(isDirty()).toBe(false));
|
||||
|
||||
await userEvent.click(screen.getByTestId('add-column'));
|
||||
|
||||
@@ -9,11 +9,8 @@ import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import SavedViewsHeader from '../SavedViewsHeader';
|
||||
import {
|
||||
expectRowUsable,
|
||||
expectUsable,
|
||||
explorerUrl,
|
||||
makeView,
|
||||
MENU_CHECK_TIMEOUT,
|
||||
queryWith,
|
||||
renderWithExplorerProviders,
|
||||
urlParam,
|
||||
@@ -70,21 +67,9 @@ async function openDirtyView(
|
||||
return rendered;
|
||||
}
|
||||
|
||||
const SAVE_MENU_ITEM_TEST_IDS: Record<string, string> = {
|
||||
'Save as new view': 'saved-views-save-changes-item-save-as-new',
|
||||
'Update selected view': 'saved-views-save-changes-item-update',
|
||||
};
|
||||
|
||||
async function chooseFromSaveMenu(item: string): Promise<void> {
|
||||
await userEvent.click(screen.getByTestId('saved-views-save-changes'));
|
||||
const menuItem = await screen.findByTestId(SAVE_MENU_ITEM_TEST_IDS[item]);
|
||||
await waitFor(() => expectRowUsable(menuItem), MENU_CHECK_TIMEOUT);
|
||||
await userEvent.click(menuItem);
|
||||
}
|
||||
|
||||
async function clickCreate(): Promise<void> {
|
||||
await waitFor(() => expectUsable(screen.getByTestId('saved-views-create')));
|
||||
await userEvent.click(screen.getByTestId('saved-views-create'));
|
||||
await userEvent.click(await screen.findByRole('menuitem', { name: item }));
|
||||
}
|
||||
|
||||
async function submitName(name: string): Promise<void> {
|
||||
@@ -102,7 +87,7 @@ describe('SavedViewsHeader saving', () => {
|
||||
const requests = mockSavedViewsApi([], { createdId: 'view-new' });
|
||||
const { history } = renderHeader(explorerUrl(PATH, {}));
|
||||
|
||||
await clickCreate();
|
||||
await userEvent.click(screen.getByTestId('saved-views-create'));
|
||||
|
||||
expect(within(modal()).getByText('Create new view')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('save-view-submit')).toHaveAttribute(
|
||||
@@ -145,7 +130,7 @@ describe('SavedViewsHeader saving', () => {
|
||||
const requests = mockSavedViewsApi([], { createStatus: 500 });
|
||||
const { history } = renderHeader(explorerUrl(PATH, {}));
|
||||
|
||||
await clickCreate();
|
||||
await userEvent.click(screen.getByTestId('saved-views-create'));
|
||||
await submitName('Slow checkout');
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalled());
|
||||
@@ -160,7 +145,7 @@ describe('SavedViewsHeader saving', () => {
|
||||
const requests = mockSavedViewsApi([]);
|
||||
renderHeader(explorerUrl(PATH, {}));
|
||||
|
||||
await clickCreate();
|
||||
await userEvent.click(screen.getByTestId('saved-views-create'));
|
||||
await userEvent.type(screen.getByTestId('save-view-name'), 'Draft');
|
||||
await userEvent.click(screen.getByTestId('save-view-cancel'));
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ import ROUTES from 'constants/routes';
|
||||
import SavedViewsPanel from '../SavedViewsPanel';
|
||||
import { mockSavedViewsApi } from './savedViewsApiMock';
|
||||
import {
|
||||
expectUsable,
|
||||
explorerUrl,
|
||||
makeView,
|
||||
renderWithExplorerProviders,
|
||||
@@ -85,9 +84,9 @@ describe('SavedViewsPanel list', () => {
|
||||
const { history } = renderPanel();
|
||||
|
||||
await screen.findByTestId('saved-views-list');
|
||||
const name = within(row('Slow spans')).getByTestId('saved-views-row-name');
|
||||
await waitFor(() => expectUsable(name));
|
||||
await userEvent.click(name);
|
||||
await userEvent.click(
|
||||
within(row('Slow spans')).getByTestId('saved-views-row-name'),
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(urlParam(history, QueryParams.viewKey)).toBe(
|
||||
@@ -162,9 +161,7 @@ describe('SavedViewsPanel list', () => {
|
||||
const requests = mockSavedViewsApi([], { createdId: 'view-new' });
|
||||
const { history } = renderPanel();
|
||||
|
||||
const create = await screen.findByTestId('saved-views-list-create');
|
||||
await waitFor(() => expectUsable(create));
|
||||
await userEvent.click(create);
|
||||
await userEvent.click(await screen.findByTestId('saved-views-list-create'));
|
||||
await userEvent.type(screen.getByTestId('save-view-name'), 'First view');
|
||||
await userEvent.click(screen.getByTestId('save-view-submit'));
|
||||
|
||||
|
||||
@@ -9,10 +9,8 @@ import SavedViewsHeader from '../SavedViewsHeader';
|
||||
import SavedViewsPanel from '../SavedViewsPanel';
|
||||
import { mockSavedViewsApi } from './savedViewsApiMock';
|
||||
import {
|
||||
expectRowUsable,
|
||||
explorerUrl,
|
||||
makeView,
|
||||
MENU_CHECK_TIMEOUT,
|
||||
renderWithExplorerProviders,
|
||||
urlParam,
|
||||
viewUrl,
|
||||
@@ -60,22 +58,13 @@ const row = (name: string): HTMLElement =>
|
||||
.getAllByTestId('saved-views-row')
|
||||
.find((element) => element.textContent?.includes(name)) as HTMLElement;
|
||||
|
||||
const ROW_MENU_ITEM_TEST_IDS: Record<string, string> = {
|
||||
'Copy link': 'saved-views-row-menu-item-copyLink',
|
||||
'Copy ID': 'saved-views-row-menu-item-copyId',
|
||||
'Edit details': 'saved-views-row-menu-item-editDetails',
|
||||
Delete: 'saved-views-row-menu-item-delete',
|
||||
};
|
||||
|
||||
async function chooseFromRowMenu(
|
||||
viewName: string,
|
||||
item: string,
|
||||
): Promise<void> {
|
||||
await screen.findByTestId('saved-views-list');
|
||||
fireEvent.click(within(row(viewName)).getByTestId('saved-views-row-menu'));
|
||||
const menuItem = await screen.findByTestId(ROW_MENU_ITEM_TEST_IDS[item]);
|
||||
await waitFor(() => expectRowUsable(menuItem), MENU_CHECK_TIMEOUT);
|
||||
fireEvent.click(menuItem);
|
||||
fireEvent.click(await screen.findByRole('menuitem', { name: item }));
|
||||
}
|
||||
|
||||
const chip = (): HTMLElement => screen.getByTestId('saved-views-name');
|
||||
@@ -87,38 +76,21 @@ describe('SavedViewsPanel row menu', () => {
|
||||
jest.mocked(toast.success).mockClear();
|
||||
});
|
||||
|
||||
it('offers copy link, copy id, edit details and delete', async () => {
|
||||
it('offers copy link, edit details and delete', async () => {
|
||||
mockSavedViewsApi([errors]);
|
||||
renderPanelWithHeader();
|
||||
await screen.findByTestId('saved-views-list');
|
||||
|
||||
fireEvent.click(within(row('Errors')).getByTestId('saved-views-row-menu'));
|
||||
|
||||
await screen.findByTestId(ROW_MENU_ITEM_TEST_IDS['Copy link']);
|
||||
const items = Object.values(ROW_MENU_ITEM_TEST_IDS).map(
|
||||
(testId) => screen.getByTestId(testId).textContent,
|
||||
);
|
||||
expect(items).toStrictEqual([
|
||||
const items = await screen.findAllByRole('menuitem');
|
||||
expect(items.map((item) => item.textContent)).toStrictEqual([
|
||||
'Copy link',
|
||||
'Copy ID',
|
||||
'Edit details',
|
||||
'Delete',
|
||||
]);
|
||||
});
|
||||
|
||||
it('copies the view id', async () => {
|
||||
mockSavedViewsApi([errors, slow]);
|
||||
renderPanelWithHeader();
|
||||
|
||||
await chooseFromRowMenu('Slow spans', 'Copy ID');
|
||||
|
||||
expect(mockCopy).toHaveBeenCalledWith(slow.id);
|
||||
expect(toast.success).toHaveBeenCalledWith(
|
||||
'View ID copied',
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it('copies a link that opens the view with its query and tab', async () => {
|
||||
mockSavedViewsApi([errors, slow]);
|
||||
renderPanelWithHeader();
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { SavedviewtypesSavedViewDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
|
||||
@@ -14,7 +13,6 @@ export interface Requests {
|
||||
}
|
||||
|
||||
// Mutates `views` on create, update and delete, so a refetch sees the change.
|
||||
// Grants every permission; a later server.use overrides it.
|
||||
export function mockSavedViewsApi(
|
||||
views: SavedviewtypesSavedViewDTO[],
|
||||
{
|
||||
@@ -32,7 +30,6 @@ export function mockSavedViewsApi(
|
||||
const requests: Requests = { created: [], updated: [], deleted: [] };
|
||||
let failedLists = 0;
|
||||
server.use(
|
||||
setupAuthzAdmin(),
|
||||
rest.get(API, (req, res, ctx) => {
|
||||
if (failedLists < listFailures) {
|
||||
failedLists += 1;
|
||||
|
||||
@@ -251,20 +251,3 @@ export function renderWithExplorerProviders(
|
||||
export function urlParam(history: MemoryHistory, key: string): string | null {
|
||||
return new URLSearchParams(history.location.search).get(key);
|
||||
}
|
||||
|
||||
// The ui Button marks a pending check with aria-busy and a block with
|
||||
// aria-disabled, never the disabled attribute.
|
||||
export function expectUsable(element: HTMLElement): void {
|
||||
expect(element).not.toHaveAttribute('aria-busy');
|
||||
expect(element).not.toHaveAttribute('aria-disabled', 'true');
|
||||
}
|
||||
|
||||
// A menu checks its rows on first open; on a loaded CI runner that outlasts
|
||||
// waitFor's 1s default.
|
||||
export const MENU_CHECK_TIMEOUT = { timeout: 5000 };
|
||||
|
||||
// A menu row waiting on its check is data-loading, not yet data-disabled.
|
||||
export function expectRowUsable(row: HTMLElement): void {
|
||||
expect(row).not.toHaveAttribute('data-loading');
|
||||
expect(row).not.toHaveAttribute('data-disabled');
|
||||
}
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import { Copy, Link, PenLine, Trash2 } from '@signozhq/icons';
|
||||
import { Link, PenLine, Trash2 } from '@signozhq/icons';
|
||||
import {
|
||||
SavedviewtypesSchemaVersionDTO,
|
||||
SavedviewtypesSourceDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import {
|
||||
buildSavedViewDeletePermission,
|
||||
buildSavedViewUpdatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { SavedViewRowActionConfig, SaveViewModalMode } from './types';
|
||||
@@ -34,8 +30,6 @@ export const MY_VIEW_NAME = 'My view';
|
||||
|
||||
export const SAVED_VIEW_LOAD_FAILED_NAME = 'View failed to load';
|
||||
|
||||
export const SAVED_VIEW_FORBIDDEN_NAME = 'No view access';
|
||||
|
||||
export const SAVED_VIEWS_LIST_LOADING_ROWS = 4;
|
||||
|
||||
export const SAVED_VIEW_HOVER_CARD_OPEN_DELAY_MS = 1000;
|
||||
@@ -53,20 +47,13 @@ export const SAVE_VIEW_MODAL_TITLE: Record<SaveViewModalMode, string> = {
|
||||
|
||||
export const SAVED_VIEW_ROW_ACTIONS: SavedViewRowActionConfig[] = [
|
||||
{ key: 'copyLink', label: 'Copy link', icon: Link },
|
||||
{ key: 'copyId', label: 'Copy ID', icon: Copy },
|
||||
{
|
||||
key: 'editDetails',
|
||||
label: 'Edit details',
|
||||
icon: PenLine,
|
||||
buildPermission: buildSavedViewUpdatePermission,
|
||||
},
|
||||
{ key: 'editDetails', label: 'Edit details', icon: PenLine },
|
||||
{
|
||||
key: 'delete',
|
||||
label: 'Delete',
|
||||
icon: Trash2,
|
||||
danger: true,
|
||||
hasDividerBefore: true,
|
||||
buildPermission: buildSavedViewDeletePermission,
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -6,10 +6,7 @@ import useOptionsMenu from 'container/OptionsMenu/useOptionsMenu';
|
||||
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useGetSavedViewParams } from 'hooks/saveViews/useGetSavedViewParams';
|
||||
import { buildSavedViewReadPermission } from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { toAPIError } from 'utils/errorUtils';
|
||||
|
||||
import { SAVED_VIEW_OPTIONS_DATA_SOURCE } from '../constants';
|
||||
import { UseActiveSavedViewResult } from '../types';
|
||||
@@ -26,19 +23,11 @@ export function useActiveSavedView(
|
||||
dataSource: optionsDataSource ?? DataSource.LOGS,
|
||||
});
|
||||
|
||||
const { isLoading: isCheckingRead, deniedPermissions } = useAuthZ(
|
||||
[buildSavedViewReadPermission(viewKey)],
|
||||
{ enabled: !!viewKey },
|
||||
);
|
||||
const isReadDenied = !!viewKey && deniedPermissions.length > 0;
|
||||
|
||||
const canFetch = !!viewKey && !isCheckingRead && !isReadDenied;
|
||||
|
||||
const { data, isLoading, isError, error } = useGetSavedView(
|
||||
const { data, isLoading, isError } = useGetSavedView(
|
||||
{ id: viewKey },
|
||||
{ query: { enabled: canFetch } },
|
||||
{ query: { enabled: !!viewKey } },
|
||||
);
|
||||
const view = canFetch ? data?.data : undefined;
|
||||
const view = viewKey ? data?.data : undefined;
|
||||
|
||||
// The query builder stages the url query a render later. Until the ids
|
||||
// match, keep the last answer for this view; another view starts clean.
|
||||
@@ -79,17 +68,10 @@ export function useActiveSavedView(
|
||||
lastResult.current = { viewId: view?.id, hasUnsavedChanges };
|
||||
}, [view?.id, hasUnsavedChanges]);
|
||||
|
||||
const errorMessage =
|
||||
viewKey && isError && error
|
||||
? toAPIError(error, '').getErrorMessage() || undefined
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
view,
|
||||
isLoading: !!viewKey && (isCheckingRead || isLoading),
|
||||
isError: !!viewKey && (isError || isReadDenied),
|
||||
isReadDenied,
|
||||
errorMessage,
|
||||
isLoading: !!viewKey && isLoading,
|
||||
isError: !!viewKey && isError,
|
||||
hasUnsavedChanges,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -59,14 +59,6 @@ export function useSavedViewRowActions(
|
||||
[pathname, copyToClipboard],
|
||||
);
|
||||
|
||||
const copyViewId = useCallback(
|
||||
(view: SavedviewtypesSavedViewDTO): void => {
|
||||
copyToClipboard(view.id);
|
||||
toast.success('View ID copied', { position: SAVED_VIEW_TOAST_POSITION });
|
||||
},
|
||||
[copyToClipboard],
|
||||
);
|
||||
|
||||
const renameView = useCallback(
|
||||
async (
|
||||
view: SavedviewtypesSavedViewDTO,
|
||||
@@ -109,12 +101,5 @@ export function useSavedViewRowActions(
|
||||
[deleteSavedView, source, queryClient],
|
||||
);
|
||||
|
||||
return {
|
||||
copyViewLink,
|
||||
copyViewId,
|
||||
renameView,
|
||||
deleteView,
|
||||
isRenaming,
|
||||
isDeleting,
|
||||
};
|
||||
return { copyViewLink, renameView, deleteView, isRenaming, isDeleting };
|
||||
}
|
||||
|
||||
@@ -1,329 +0,0 @@
|
||||
/**
|
||||
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import { rest, type RequestHandler } from 'msw';
|
||||
import { TooltipProvider } from '@signozhq/ui/tooltip';
|
||||
import remove from 'api/browser/localstorage/remove';
|
||||
import {
|
||||
type AuthtypesTransactionDTO,
|
||||
type SavedviewtypesSavedViewDTO,
|
||||
SavedviewtypesSourceDTO,
|
||||
type SavedviewtypesUpdatableSavedViewDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { SIDEBAR_TOOLTIP_DELAY_MS } from 'components/QuickFilters/QuickFiltersLayout/constants';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import {
|
||||
AUTHZ_CHECK_URL,
|
||||
authzMockResponse,
|
||||
} from 'lib/authz/utils/authz-test-utils';
|
||||
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
import { accessFor } from '@/storybook/access/access';
|
||||
import {
|
||||
choiceControl,
|
||||
countControl,
|
||||
toggleControl,
|
||||
} from '@/storybook/controls/controls';
|
||||
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { MockControlValues, StoryMocks } from '@/storybook/controls/types';
|
||||
import { withCanvas } from '@/storybook/decorators/withCanvas';
|
||||
import { authzMocks, type AuthzArgs } from '@/storybook/globals/authzMocks';
|
||||
import { respondWith } from '@/storybook/runtime/responseState';
|
||||
|
||||
import {
|
||||
createdSavedView,
|
||||
OPEN_VIEW_ERRORS,
|
||||
OPEN_VIEWS,
|
||||
type OpenView,
|
||||
SAVED_VIEW_SOURCES,
|
||||
SAVED_VIEWS_MAX,
|
||||
savedViewById,
|
||||
savedViewResponse,
|
||||
savedViewRoute,
|
||||
savedViewsListResponse,
|
||||
type SavedViewSource,
|
||||
unreadableViewId,
|
||||
} from './__story_mockdata__/savedViews';
|
||||
|
||||
import SavedViewsHeader from '../SavedViewsHeader';
|
||||
import SavedViewsPanel from '../SavedViewsPanel';
|
||||
import type { SavedViewRowActionKey } from '../types';
|
||||
|
||||
const API = 'http://localhost/api/v2/saved_views';
|
||||
|
||||
const LIST = 'Saved Views · list';
|
||||
const VIEW = 'Saved Views · open view';
|
||||
|
||||
const controls = {
|
||||
source: choiceControl<SavedViewSource>('Source', {
|
||||
group: VIEW,
|
||||
description: 'Which explorer the views belong to.',
|
||||
options: SAVED_VIEW_SOURCES,
|
||||
value: SavedviewtypesSourceDTO.traces,
|
||||
}),
|
||||
openView: choiceControl<OpenView>('Open view', {
|
||||
group: VIEW,
|
||||
description:
|
||||
'The `viewKey` the explorer url carries. `unsaved-changes` stages a query that differs from the view, which swaps in the ✓ save menu; `forbidden`, `failed` and `not-found` are the 403, 500 and 404 the view fetch answers with; each shows View failed to load.',
|
||||
options: OPEN_VIEWS,
|
||||
value: 'none',
|
||||
}),
|
||||
unreadableView: toggleControl('Unreadable view', {
|
||||
group: VIEW,
|
||||
description:
|
||||
'Denies `read` on the first view created by others alone, on top of the Access controls: its row greys out, and with Open view on `created-by-others` the header shows No view access.',
|
||||
value: false,
|
||||
}),
|
||||
createdByMe: countControl('Created by me', {
|
||||
group: LIST,
|
||||
value: 3,
|
||||
max: SAVED_VIEWS_MAX,
|
||||
}),
|
||||
createdByOthers: countControl('Created by others', {
|
||||
group: LIST,
|
||||
description: 'Both at 0 is the empty state, with its Create view button.',
|
||||
value: 4,
|
||||
max: SAVED_VIEWS_MAX,
|
||||
}),
|
||||
};
|
||||
|
||||
type SavedViewsValues = MockControlValues<typeof controls>;
|
||||
|
||||
type WrittenView = Pick<SavedviewtypesSavedViewDTO, 'spec' | 'source'>;
|
||||
|
||||
const viewDenied = (
|
||||
transaction: AuthtypesTransactionDTO,
|
||||
deniedId: string,
|
||||
): boolean =>
|
||||
transaction.relation === 'read' &&
|
||||
transaction.object.resource.kind === 'saved-view' &&
|
||||
transaction.object.selector === deniedId;
|
||||
|
||||
const definition = defineStoryMocks({
|
||||
controls,
|
||||
handlers: (
|
||||
values: SavedViewsValues & AuthzArgs,
|
||||
response,
|
||||
): RequestHandler[] => {
|
||||
const { source, openView, createdByMe, createdByOthers } = values;
|
||||
|
||||
// What the panel writes stays in this handler set until a control changes.
|
||||
const created: SavedviewtypesSavedViewDTO[] = [];
|
||||
const updated = new Map<string, WrittenView>();
|
||||
const deleted = new Set<string>();
|
||||
|
||||
const current = (
|
||||
view: SavedviewtypesSavedViewDTO,
|
||||
): SavedviewtypesSavedViewDTO => ({ ...view, ...updated.get(view.id) });
|
||||
|
||||
const findView = (id: string): SavedviewtypesSavedViewDTO | undefined => {
|
||||
const view = created.find((item) => item.id === id) ?? savedViewById(id);
|
||||
|
||||
return view && !deleted.has(id) ? current(view) : undefined;
|
||||
};
|
||||
|
||||
const openError = OPEN_VIEW_ERRORS[openView];
|
||||
|
||||
return [
|
||||
rest.post(API, async (req, res, ctx) => {
|
||||
const body = (await req.json()) as SavedviewtypesUpdatableSavedViewDTO;
|
||||
const id = `storybook-${source}-created-${created.length + 1}`;
|
||||
|
||||
created.push(createdSavedView(source, id, body.spec));
|
||||
|
||||
return res(ctx.status(201), ctx.json({ status: 'success', data: { id } }));
|
||||
}),
|
||||
|
||||
rest.get(
|
||||
API,
|
||||
response.json(() => {
|
||||
const list = savedViewsListResponse(source, createdByMe, createdByOthers);
|
||||
|
||||
return {
|
||||
...list,
|
||||
data: [...(list.data ?? []), ...created]
|
||||
.filter((view) => !deleted.has(view.id))
|
||||
.map(current),
|
||||
};
|
||||
}),
|
||||
),
|
||||
|
||||
rest.get(`${API}/:id`, (req, res, ctx) => {
|
||||
if (openError) {
|
||||
return res(ctx.status(openError.status), ctx.json(openError.body));
|
||||
}
|
||||
|
||||
const view = findView(String(req.params.id));
|
||||
|
||||
if (!view) {
|
||||
return res(ctx.status(404), ctx.json(OPEN_VIEW_ERRORS['not-found']?.body));
|
||||
}
|
||||
|
||||
return response.json(() => savedViewResponse(view))(req, res, ctx);
|
||||
}),
|
||||
|
||||
rest.put(`${API}/:id`, async (req, res, ctx) => {
|
||||
const body = (await req.json()) as SavedviewtypesUpdatableSavedViewDTO;
|
||||
|
||||
updated.set(String(req.params.id), {
|
||||
spec: body.spec,
|
||||
source: body.source,
|
||||
});
|
||||
|
||||
return res(ctx.status(204));
|
||||
}),
|
||||
|
||||
rest.delete(`${API}/:id`, (req, res, ctx) => {
|
||||
deleted.add(String(req.params.id));
|
||||
|
||||
return res(ctx.status(204));
|
||||
}),
|
||||
|
||||
...(values.unreadableView
|
||||
? [
|
||||
rest.post(
|
||||
AUTHZ_CHECK_URL,
|
||||
respondWith(values.authzState, async (req) => {
|
||||
const payload = (await req.json()) as AuthtypesTransactionDTO[];
|
||||
const granted = accessFor(
|
||||
values.access,
|
||||
values.permissions,
|
||||
values.revoked,
|
||||
);
|
||||
const deniedId = unreadableViewId(source);
|
||||
|
||||
return authzMockResponse(
|
||||
payload,
|
||||
payload.map(
|
||||
(transaction) =>
|
||||
!viewDenied(transaction, deniedId) && granted.allows(transaction),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
]
|
||||
: []),
|
||||
];
|
||||
},
|
||||
config: ({ source, openView }) => ({
|
||||
route: savedViewRoute(source, openView),
|
||||
}),
|
||||
effect: () => {
|
||||
remove(LOCALSTORAGE.LAST_USED_SAVED_VIEWS);
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* The per-view read denial answers `authz/check` in place of the global access
|
||||
* mocks, so it reads their controls as well as its own to answer every other
|
||||
* check the way they would.
|
||||
*/
|
||||
export const savedViewsMocks: StoryMocks<typeof controls> = {
|
||||
...definition,
|
||||
read: (args) => ({ ...authzMocks.read(args), ...definition.read(args) }),
|
||||
};
|
||||
|
||||
/** The sidebar slot of an explorer without quick filters. */
|
||||
export const sidebarCanvas = withCanvas({
|
||||
width: 280,
|
||||
height: 640,
|
||||
padding: 0,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
borderRight: '1px solid var(--l1-border)',
|
||||
});
|
||||
|
||||
/**
|
||||
* The header above the pinned list. `onOpenViews` adds All views, which the
|
||||
* header only shows in an explorer whose quick filters hide the list.
|
||||
*/
|
||||
export function SavedViewsSidebar({
|
||||
source,
|
||||
onOpenViews,
|
||||
}: {
|
||||
source: SavedViewSource;
|
||||
onOpenViews?: () => void;
|
||||
}): JSX.Element {
|
||||
return (
|
||||
<TooltipProvider delay={SIDEBAR_TOOLTIP_DELAY_MS}>
|
||||
<SavedViewsHeader source={source} onOpenViews={onOpenViews} />
|
||||
<SavedViewsPanel source={source} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
/** The panel fetches the list and checks every row's permissions before it settles. */
|
||||
export const UNTIL_LOADED = { timeout: 15_000 };
|
||||
|
||||
/**
|
||||
* Re-queried on every attempt: a button whose check settles is a new node, so a
|
||||
* reference taken while it was pending never changes.
|
||||
*/
|
||||
type FindElement = () => HTMLElement;
|
||||
|
||||
export const byTestId =
|
||||
(testId: string): FindElement =>
|
||||
(): HTMLElement =>
|
||||
screen.getByTestId(testId);
|
||||
|
||||
/** A check still in flight: `aria-busy` on a button, `data-loading` on a menu row. */
|
||||
const isPending = (element: HTMLElement): boolean =>
|
||||
element.getAttribute('aria-busy') === 'true' ||
|
||||
element.hasAttribute('data-loading');
|
||||
|
||||
const isDisabled = (element: HTMLElement): boolean =>
|
||||
element.hasAttribute('disabled') || element.hasAttribute('data-disabled');
|
||||
|
||||
export const expectDisabled = (
|
||||
find: FindElement,
|
||||
disabled = true,
|
||||
): Promise<void> =>
|
||||
waitFor(async () => {
|
||||
const element = find();
|
||||
|
||||
await expect(isPending(element)).toBe(false);
|
||||
await expect(isDisabled(element)).toBe(disabled);
|
||||
}, UNTIL_LOADED);
|
||||
|
||||
export const expectPending = (find: FindElement): Promise<void> =>
|
||||
waitFor(() => expect(isPending(find())).toBe(true), UNTIL_LOADED);
|
||||
|
||||
export const findRows = (canvasElement: HTMLElement): Promise<HTMLElement[]> =>
|
||||
within(canvasElement).findAllByTestId(
|
||||
'saved-views-row',
|
||||
undefined,
|
||||
UNTIL_LOADED,
|
||||
);
|
||||
|
||||
export const rowName =
|
||||
(row: HTMLElement): FindElement =>
|
||||
(): HTMLElement =>
|
||||
within(row).getByTestId('saved-views-row-name');
|
||||
|
||||
export const openRowMenu = async (row: HTMLElement): Promise<void> => {
|
||||
await userEvent.click(within(row).getByTestId('saved-views-row-menu'));
|
||||
await screen.findByRole('menu', undefined, UNTIL_LOADED);
|
||||
};
|
||||
|
||||
export const rowMenuItem = (key: SavedViewRowActionKey): FindElement =>
|
||||
byTestId(`saved-views-row-menu-item-${key}`);
|
||||
|
||||
export const openSaveChangesMenu = async (
|
||||
canvasElement: HTMLElement,
|
||||
): Promise<void> => {
|
||||
const trigger = await waitFor(async () => {
|
||||
const button = within(canvasElement).getByTestId('saved-views-save-changes');
|
||||
|
||||
await expect(button).not.toHaveAttribute('aria-busy');
|
||||
|
||||
return button;
|
||||
}, UNTIL_LOADED);
|
||||
|
||||
await userEvent.click(trigger);
|
||||
await screen.findByRole('menu', undefined, UNTIL_LOADED);
|
||||
};
|
||||
|
||||
export const saveChangesItem = (key: 'save-as-new' | 'update'): FindElement =>
|
||||
byTestId(`saved-views-save-changes-item-${key}`);
|
||||
@@ -1,80 +0,0 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
|
||||
import SavedViewsPanel from '../SavedViewsPanel';
|
||||
import {
|
||||
findRows,
|
||||
openRowMenu,
|
||||
openSaveChangesMenu,
|
||||
SavedViewsSidebar,
|
||||
savedViewsMocks,
|
||||
sidebarCanvas,
|
||||
} from './SavedViews.stories.mocks';
|
||||
|
||||
type SavedViewsArgs = PageStoryArgs<typeof savedViewsMocks>;
|
||||
|
||||
const componentStory = storyMocks(savedViewsMocks);
|
||||
|
||||
/**
|
||||
* The saved views sidebar of an explorer without quick filters: the header with
|
||||
* the open view and its actions, above the list of views created by the user
|
||||
* and by others. Every action is gated on the `saved-view` authz permissions
|
||||
* (list, create, and read, update and delete per view).
|
||||
*
|
||||
* Route: the explorer of the Source control, with the Open view control's
|
||||
* `viewKey`.
|
||||
*/
|
||||
const meta = {
|
||||
title: 'Components/Saved Views/Overview',
|
||||
tags: ['authz', 'play'],
|
||||
component: SavedViewsPanel,
|
||||
decorators: [sidebarCanvas],
|
||||
render: ({ source }): JSX.Element => <SavedViewsSidebar source={source} />,
|
||||
...componentStory,
|
||||
parameters: { ...componentStory.parameters },
|
||||
} satisfies Meta<SavedViewsArgs>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<SavedViewsArgs>;
|
||||
|
||||
/** Traces views created by the user and by others, with no view open. */
|
||||
export const Default: Story = {};
|
||||
|
||||
/** A workspace with no views yet: the empty state offers Create view. */
|
||||
export const Empty: Story = {
|
||||
args: { createdByMe: 0, createdByOthers: 0 },
|
||||
};
|
||||
|
||||
/**
|
||||
* A view open with a query that differs from what it saved: the name carries
|
||||
* the unsaved dot, and ✓ and discard replace Clear view.
|
||||
*/
|
||||
export const UnsavedChanges: Story = {
|
||||
args: { openView: 'unsaved-changes' },
|
||||
};
|
||||
|
||||
/**
|
||||
* The first row's menu. Edit details and Delete follow `update` and `delete` on
|
||||
* that view, so revoking either disables its item.
|
||||
*/
|
||||
export const RowMenu: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
const [row] = await findRows(canvasElement);
|
||||
|
||||
await openRowMenu(row);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The ✓ menu on a view with unsaved changes. Save as new view follows `create`
|
||||
* and Update selected view follows `update` on the open view.
|
||||
*/
|
||||
export const SaveChangesMenu: Story = {
|
||||
args: { openView: 'unsaved-changes' },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await openSaveChangesMenu(canvasElement);
|
||||
},
|
||||
};
|
||||
@@ -1,309 +0,0 @@
|
||||
/**
|
||||
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import type {
|
||||
GetSavedView200,
|
||||
ListSavedViews200,
|
||||
RenderErrorResponseDTO,
|
||||
SavedviewtypesSavedViewDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
SavedviewtypesSchemaVersionDTO,
|
||||
SavedviewtypesSourceDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import {
|
||||
initialQueriesMap,
|
||||
initialQueryMeterWithType,
|
||||
PANEL_TYPES,
|
||||
} from 'constants/queryBuilder';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { getSavedViewQuery } from 'container/SavedViews/utils/getSavedViewQuery';
|
||||
import { toSavedViewSpec } from 'container/SavedViews/utils/toSavedViewSpec';
|
||||
import { createAppContextMock } from 'tests/fixtures/appContextMock';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
|
||||
export const SAVED_VIEW_SOURCES = [
|
||||
SavedviewtypesSourceDTO.traces,
|
||||
SavedviewtypesSourceDTO.logs,
|
||||
SavedviewtypesSourceDTO.metrics,
|
||||
SavedviewtypesSourceDTO.meter,
|
||||
] as const;
|
||||
|
||||
export type SavedViewSource = (typeof SAVED_VIEW_SOURCES)[number];
|
||||
|
||||
export const OPEN_VIEWS = [
|
||||
'none',
|
||||
'created-by-me',
|
||||
'created-by-others',
|
||||
'unsaved-changes',
|
||||
'forbidden',
|
||||
'failed',
|
||||
'not-found',
|
||||
] as const;
|
||||
|
||||
export type OpenView = (typeof OPEN_VIEWS)[number];
|
||||
|
||||
export const SAVED_VIEWS_MAX = 8;
|
||||
|
||||
/** The user the story app context signs in as, so "Created by me" follows it. */
|
||||
const STORY_USER_EMAIL = createAppContextMock(USER_ROLES.ADMIN).user.email;
|
||||
|
||||
const OTHER_AUTHORS = ['priya@signoz.io', 'marco@signoz.io', 'lena@signoz.io'];
|
||||
|
||||
const MY_VIEW_NAMES = [
|
||||
'Checkout errors',
|
||||
'Slow payment calls',
|
||||
'Cart service, production',
|
||||
'Auth retries',
|
||||
'Inventory sync',
|
||||
'Search p99 regressions',
|
||||
'Webhook failures',
|
||||
'Cold starts after deploy',
|
||||
];
|
||||
|
||||
const OTHER_VIEW_NAMES = [
|
||||
'On-call triage',
|
||||
'Frontend 5xx',
|
||||
'Shipping latency by region',
|
||||
'Kafka consumer lag',
|
||||
'Staging smoke tests',
|
||||
'Recommendation timeouts',
|
||||
'Ad service sampling',
|
||||
'Email queue backlog',
|
||||
];
|
||||
|
||||
const EXPRESSIONS = [
|
||||
"service.name = 'checkout' AND has_error = true",
|
||||
"service.name = 'payments'",
|
||||
"service.name = 'cart' AND deployment.environment = 'production'",
|
||||
"service.name = 'auth'",
|
||||
"service.name IN ('inventory', 'catalog')",
|
||||
"service.name = 'search'",
|
||||
"service.name = 'webhooks' AND has_error = true",
|
||||
"deployment.environment = 'production'",
|
||||
];
|
||||
|
||||
const BASE_QUERY: Record<SavedViewSource, Query> = {
|
||||
traces: initialQueriesMap.traces,
|
||||
logs: initialQueriesMap.logs,
|
||||
metrics: initialQueriesMap.metrics,
|
||||
meter: initialQueryMeterWithType,
|
||||
};
|
||||
|
||||
const EXPLORER_ROUTE: Record<SavedViewSource, string> = {
|
||||
traces: ROUTES.TRACES_EXPLORER,
|
||||
logs: ROUTES.LOGS_EXPLORER,
|
||||
metrics: ROUTES.METRICS_EXPLORER_EXPLORER,
|
||||
meter: ROUTES.METER_EXPLORER,
|
||||
};
|
||||
|
||||
const queryWith = (source: SavedViewSource, expression: string): Query => {
|
||||
const base = BASE_QUERY[source];
|
||||
|
||||
return {
|
||||
...base,
|
||||
builder: {
|
||||
...base.builder,
|
||||
queryData: [
|
||||
{
|
||||
...base.builder.queryData[0],
|
||||
filter: { expression },
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
} as Query;
|
||||
};
|
||||
|
||||
type Author = 'mine' | 'others';
|
||||
|
||||
const viewId = (
|
||||
source: SavedViewSource,
|
||||
author: Author,
|
||||
index: number,
|
||||
): string => `storybook-${source}-${author}-${index + 1}`;
|
||||
|
||||
/** The view other people made that the per-view read denial applies to. */
|
||||
export const unreadableViewId = (source: SavedViewSource): string =>
|
||||
viewId(source, 'others', 0);
|
||||
|
||||
const savedView = (
|
||||
source: SavedViewSource,
|
||||
author: Author,
|
||||
index: number,
|
||||
): SavedviewtypesSavedViewDTO => {
|
||||
const displayName = (author === 'mine' ? MY_VIEW_NAMES : OTHER_VIEW_NAMES)[
|
||||
index
|
||||
];
|
||||
const createdBy =
|
||||
author === 'mine'
|
||||
? STORY_USER_EMAIL
|
||||
: OTHER_AUTHORS[index % OTHER_AUTHORS.length];
|
||||
const id = viewId(source, author, index);
|
||||
|
||||
return {
|
||||
id,
|
||||
name: id,
|
||||
source,
|
||||
schemaVersion: SavedviewtypesSchemaVersionDTO.v2,
|
||||
createdAt: '2026-09-02T08:30:00Z',
|
||||
createdBy,
|
||||
updatedAt: `2026-10-${String(14 - (index % 10)).padStart(2, '0')}T11:42:00Z`,
|
||||
updatedBy: createdBy,
|
||||
spec: toSavedViewSpec({
|
||||
query: queryWith(
|
||||
source,
|
||||
EXPRESSIONS[(index + (author === 'mine' ? 0 : 3)) % EXPRESSIONS.length],
|
||||
),
|
||||
panelType: PANEL_TYPES.LIST,
|
||||
displayName,
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const savedViews = (
|
||||
source: SavedViewSource,
|
||||
author: Author,
|
||||
count: number,
|
||||
): SavedviewtypesSavedViewDTO[] =>
|
||||
Array.from({ length: Math.min(count, SAVED_VIEWS_MAX) }, (_, index) =>
|
||||
savedView(source, author, index),
|
||||
);
|
||||
|
||||
export const savedViewsListResponse = (
|
||||
source: SavedViewSource,
|
||||
createdByMe: number,
|
||||
createdByOthers: number,
|
||||
): ListSavedViews200 => ({
|
||||
status: 'success',
|
||||
data: [
|
||||
...savedViews(source, 'mine', createdByMe),
|
||||
...savedViews(source, 'others', createdByOthers),
|
||||
],
|
||||
});
|
||||
|
||||
/** Every view the workspace has, whatever the list control trims it to. */
|
||||
export const savedViewById = (
|
||||
id: string,
|
||||
): SavedviewtypesSavedViewDTO | undefined =>
|
||||
SAVED_VIEW_SOURCES.flatMap((source) => [
|
||||
...savedViews(source, 'mine', SAVED_VIEWS_MAX),
|
||||
...savedViews(source, 'others', SAVED_VIEWS_MAX),
|
||||
]).find((view) => view.id === id);
|
||||
|
||||
/** A view the panel itself created, owned by the story user. */
|
||||
export const createdSavedView = (
|
||||
source: SavedViewSource,
|
||||
id: string,
|
||||
spec: SavedviewtypesSavedViewDTO['spec'],
|
||||
): SavedviewtypesSavedViewDTO => ({
|
||||
...savedView(source, 'mine', 0),
|
||||
id,
|
||||
name: id,
|
||||
createdAt: '2026-10-16T09:00:00Z',
|
||||
updatedAt: '2026-10-16T09:00:00Z',
|
||||
spec,
|
||||
});
|
||||
|
||||
export const savedViewResponse = (
|
||||
view: SavedviewtypesSavedViewDTO,
|
||||
): GetSavedView200 => ({ status: 'success', data: view });
|
||||
|
||||
export const OPEN_VIEW_ERRORS: Partial<
|
||||
Record<OpenView, { status: number; body: RenderErrorResponseDTO }>
|
||||
> = {
|
||||
forbidden: {
|
||||
status: 403,
|
||||
body: {
|
||||
status: 'error',
|
||||
error: {
|
||||
code: 'forbidden',
|
||||
message: 'You do not have access to this saved view',
|
||||
errors: [],
|
||||
suggestions: [],
|
||||
type: 'forbidden',
|
||||
},
|
||||
},
|
||||
},
|
||||
failed: {
|
||||
status: 500,
|
||||
body: {
|
||||
status: 'error',
|
||||
error: {
|
||||
code: 'internal',
|
||||
message: 'Failed to load the saved view',
|
||||
errors: [],
|
||||
suggestions: [],
|
||||
type: 'internal',
|
||||
},
|
||||
},
|
||||
},
|
||||
'not-found': {
|
||||
status: 404,
|
||||
body: {
|
||||
status: 'error',
|
||||
error: {
|
||||
code: 'not_found',
|
||||
message: 'Saved view not found',
|
||||
errors: [],
|
||||
suggestions: [],
|
||||
type: 'not_found',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const openViewId = (source: SavedViewSource, open: OpenView): string | null => {
|
||||
if (open === 'none') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (open === 'created-by-others' || open === 'forbidden') {
|
||||
return viewId(source, 'others', 0);
|
||||
}
|
||||
|
||||
if (open === 'not-found') {
|
||||
return `storybook-${source}-deleted`;
|
||||
}
|
||||
|
||||
return viewId(source, 'mine', 0);
|
||||
};
|
||||
|
||||
/**
|
||||
* The explorer url with a view open, its params written the way
|
||||
* `redirectWithQueryBuilderData` writes them. `panelTypes` is left out: the
|
||||
* query builder seeds its panel type from the raw, JSON-quoted param, which no
|
||||
* saved panel type equals, and without it the header compares against `list`.
|
||||
*/
|
||||
export const savedViewRoute = (
|
||||
source: SavedViewSource,
|
||||
open: OpenView,
|
||||
): string => {
|
||||
const params = new URLSearchParams({ relativeTime: '15m' });
|
||||
const id = openViewId(source, open);
|
||||
|
||||
if (id) {
|
||||
const view = savedViewById(id);
|
||||
const query = view
|
||||
? getSavedViewQuery(view)
|
||||
: queryWith(source, EXPRESSIONS[0]);
|
||||
const staged =
|
||||
open === 'unsaved-changes'
|
||||
? queryWith(source, `${EXPRESSIONS[0]} AND duration_nano > 500000000`)
|
||||
: query;
|
||||
|
||||
params.set(
|
||||
QueryParams.compositeQuery,
|
||||
encodeURIComponent(
|
||||
JSON.stringify({ ...staged, id: `storybook-staged-${open}` }),
|
||||
),
|
||||
);
|
||||
params.set(QueryParams.viewKey, JSON.stringify(id));
|
||||
}
|
||||
|
||||
return `${EXPLORER_ROUTE[source]}?${params.toString()}`;
|
||||
};
|
||||
@@ -1,220 +0,0 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, waitFor, within } from 'storybook/test';
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
|
||||
import { unreadableViewId } from '../__story_mockdata__/savedViews';
|
||||
import {
|
||||
byTestId,
|
||||
expectDisabled,
|
||||
expectPending,
|
||||
findRows,
|
||||
openRowMenu,
|
||||
openSaveChangesMenu,
|
||||
rowMenuItem,
|
||||
rowName,
|
||||
saveChangesItem,
|
||||
SavedViewsSidebar,
|
||||
savedViewsMocks,
|
||||
sidebarCanvas,
|
||||
UNTIL_LOADED,
|
||||
} from '../SavedViews.stories.mocks';
|
||||
|
||||
import SavedViewsPanel from '../../SavedViewsPanel';
|
||||
|
||||
type SavedViewsArgs = PageStoryArgs<typeof savedViewsMocks>;
|
||||
|
||||
const componentStory = storyMocks(savedViewsMocks);
|
||||
|
||||
/**
|
||||
* The saved views sidebar with one permission missing at a time. Every story
|
||||
* here is an admin denied exactly what its name says. `list` and `create` are
|
||||
* workspace-wide; `read`, `update` and `delete` are checked per view, so a row
|
||||
* menu only checks its view once it is opened.
|
||||
*
|
||||
* Route: the explorer of the Source control, with the Open view control's
|
||||
* `viewKey`.
|
||||
*/
|
||||
const meta = {
|
||||
title: 'Components/Saved Views/Authz',
|
||||
tags: ['authz', 'play'],
|
||||
component: SavedViewsPanel,
|
||||
decorators: [sidebarCanvas],
|
||||
render: ({ source }): JSX.Element => <SavedViewsSidebar source={source} />,
|
||||
...componentStory,
|
||||
parameters: { ...componentStory.parameters },
|
||||
} satisfies Meta<SavedViewsArgs>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<SavedViewsArgs>;
|
||||
|
||||
const LIST = 'list:saved-view';
|
||||
const CREATE = 'create:saved-view';
|
||||
const UPDATE = 'update:saved-view';
|
||||
const DELETE = 'delete:saved-view';
|
||||
|
||||
/**
|
||||
* The panel shows the permission callout in place of the list, and All views,
|
||||
* in an explorer whose quick filters hide the list, is disabled.
|
||||
*/
|
||||
export const NoList: Story = {
|
||||
args: { revoked: [LIST] },
|
||||
render: ({ source }): JSX.Element => (
|
||||
<SavedViewsSidebar source={source} onOpenViews={(): void => {}} />
|
||||
),
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
|
||||
await expectDisabled(byTestId('saved-views-open'));
|
||||
await waitFor(
|
||||
() =>
|
||||
expect(canvas.getByTestId('saved-views-panel')).toHaveTextContent(
|
||||
/is not authorized to perform list/,
|
||||
),
|
||||
UNTIL_LOADED,
|
||||
);
|
||||
await expect(canvas.queryByTestId('saved-views-search')).toBeNull();
|
||||
},
|
||||
};
|
||||
|
||||
/** An empty workspace with both ways to create a view disabled: + and Create view. */
|
||||
export const NoCreate: Story = {
|
||||
args: { revoked: [CREATE], createdByMe: 0, createdByOthers: 0 },
|
||||
play: async () => {
|
||||
await expectDisabled(byTestId('saved-views-create'));
|
||||
await expectDisabled(byTestId('saved-views-list-create'));
|
||||
},
|
||||
};
|
||||
|
||||
/** The ✓ menu on unsaved changes: Save as new view disabled, Update selected view open. */
|
||||
export const NoCreateSaveMenu: Story = {
|
||||
args: { revoked: [CREATE], openView: 'unsaved-changes' },
|
||||
play: async ({ canvasElement }) => {
|
||||
await openSaveChangesMenu(canvasElement);
|
||||
await expectDisabled(saveChangesItem('save-as-new'));
|
||||
await expectDisabled(saveChangesItem('update'), false);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* `read` denied on one view made by someone else: its name is disabled and its
|
||||
* hover card never opens, while every other view still opens.
|
||||
*/
|
||||
export const NoRead: Story = {
|
||||
args: { unreadableView: true },
|
||||
play: async ({ canvasElement, args }) => {
|
||||
const rows = await findRows(canvasElement);
|
||||
const deniedId = unreadableViewId(args.source);
|
||||
|
||||
await Promise.all(
|
||||
rows.map((row) =>
|
||||
expectDisabled(rowName(row), row.getAttribute('data-view-id') === deniedId),
|
||||
),
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
/** The unreadable view open from its link: the header names it No view access. */
|
||||
export const NoReadOpenView: Story = {
|
||||
args: { unreadableView: true, openView: 'created-by-others' },
|
||||
play: async ({ canvasElement }) => {
|
||||
await expect(
|
||||
await within(canvasElement).findByText(
|
||||
'No view access',
|
||||
undefined,
|
||||
UNTIL_LOADED,
|
||||
),
|
||||
).toBeVisible();
|
||||
},
|
||||
};
|
||||
|
||||
/** A row's menu: Edit details disabled; Copy link, Copy ID and Delete open. */
|
||||
export const NoUpdate: Story = {
|
||||
args: { revoked: [UPDATE] },
|
||||
play: async ({ canvasElement }) => {
|
||||
const [row] = await findRows(canvasElement);
|
||||
|
||||
await openRowMenu(row);
|
||||
await expectDisabled(rowMenuItem('editDetails'));
|
||||
await expectDisabled(rowMenuItem('copyLink'), false);
|
||||
await expectDisabled(rowMenuItem('copyId'), false);
|
||||
await expectDisabled(rowMenuItem('delete'), false);
|
||||
},
|
||||
};
|
||||
|
||||
/** The ✓ menu on unsaved changes: Update selected view disabled, Save as new view open. */
|
||||
export const NoUpdateSaveMenu: Story = {
|
||||
args: { revoked: [UPDATE], openView: 'unsaved-changes' },
|
||||
play: async ({ canvasElement }) => {
|
||||
await openSaveChangesMenu(canvasElement);
|
||||
await expectDisabled(saveChangesItem('update'));
|
||||
await expectDisabled(saveChangesItem('save-as-new'), false);
|
||||
},
|
||||
};
|
||||
|
||||
/** A row's menu: Delete disabled, Edit details still open. */
|
||||
export const NoDelete: Story = {
|
||||
args: { revoked: [DELETE] },
|
||||
play: async ({ canvasElement }) => {
|
||||
const [row] = await findRows(canvasElement);
|
||||
|
||||
await openRowMenu(row);
|
||||
await expectDisabled(rowMenuItem('delete'));
|
||||
await expectDisabled(rowMenuItem('editDetails'), false);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Everything but listing and reading: + is disabled, and a row's menu has only
|
||||
* Copy link and Copy ID left.
|
||||
*/
|
||||
export const ReadOnly: Story = {
|
||||
args: { revoked: [CREATE, UPDATE, DELETE] },
|
||||
play: async ({ canvasElement }) => {
|
||||
await expectDisabled(byTestId('saved-views-create'));
|
||||
|
||||
const [row] = await findRows(canvasElement);
|
||||
|
||||
await expectDisabled(rowName(row), false);
|
||||
await openRowMenu(row);
|
||||
await expectDisabled(rowMenuItem('editDetails'));
|
||||
await expectDisabled(rowMenuItem('delete'));
|
||||
await expectDisabled(rowMenuItem('copyLink'), false);
|
||||
await expectDisabled(rowMenuItem('copyId'), false);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The permission check never answering: + spins, and the list stays blank
|
||||
* behind its `list` check.
|
||||
*/
|
||||
export const CheckLoading: Story = {
|
||||
args: { authzState: 'loading' },
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
|
||||
await expectPending(byTestId('saved-views-create'));
|
||||
await expect(canvas.queryByTestId('saved-views-search')).toBeNull();
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The permission check failing rather than denying: the sidebar fails open,
|
||||
* so the list renders and every action stays enabled for the API to refuse.
|
||||
*/
|
||||
export const CheckFailed: Story = {
|
||||
args: { authzState: 'error' },
|
||||
parameters: { allowConsoleErrors: true },
|
||||
play: async ({ canvasElement }) => {
|
||||
await expectDisabled(byTestId('saved-views-create'), false);
|
||||
|
||||
const [row] = await findRows(canvasElement);
|
||||
|
||||
await expectDisabled(rowName(row), false);
|
||||
await openRowMenu(row);
|
||||
await expectDisabled(rowMenuItem('editDetails'), false);
|
||||
await expectDisabled(rowMenuItem('delete'), false);
|
||||
},
|
||||
};
|
||||
@@ -1,6 +1,5 @@
|
||||
import { ReactElement, ReactNode } from 'react';
|
||||
import type { Link } from '@signozhq/icons';
|
||||
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
|
||||
import {
|
||||
SavedviewtypesSavedViewDTO,
|
||||
SavedviewtypesSourceDTO,
|
||||
@@ -42,8 +41,6 @@ export interface UseActiveSavedViewResult {
|
||||
view: SavedviewtypesSavedViewDTO | undefined;
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
isReadDenied: boolean;
|
||||
errorMessage: string | undefined;
|
||||
hasUnsavedChanges: boolean;
|
||||
}
|
||||
|
||||
@@ -73,7 +70,6 @@ export interface SaveViewModalProps {
|
||||
}
|
||||
|
||||
export interface SaveChangesMenuProps {
|
||||
viewId: string;
|
||||
disabled: boolean;
|
||||
onSaveAsNew: () => void;
|
||||
onUpdate: () => void;
|
||||
@@ -86,7 +82,6 @@ export interface SavedViewsIconButtonProps {
|
||||
color?: 'secondary' | 'warning';
|
||||
disabled?: boolean;
|
||||
disabledTooltip?: ReactNode;
|
||||
checks?: BrandedPermission[];
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
@@ -121,11 +116,7 @@ export interface SavedViewsListRowProps {
|
||||
hover: SavedViewsListRowHoverProps;
|
||||
}
|
||||
|
||||
export type SavedViewRowActionKey =
|
||||
| 'copyLink'
|
||||
| 'copyId'
|
||||
| 'editDetails'
|
||||
| 'delete';
|
||||
export type SavedViewRowActionKey = 'copyLink' | 'editDetails' | 'delete';
|
||||
|
||||
export interface SavedViewRowActionConfig {
|
||||
key: SavedViewRowActionKey;
|
||||
@@ -133,11 +124,10 @@ export interface SavedViewRowActionConfig {
|
||||
icon: typeof Link;
|
||||
danger?: boolean;
|
||||
hasDividerBefore?: boolean;
|
||||
buildPermission?: (id: string) => BrandedPermission;
|
||||
}
|
||||
|
||||
export interface PendingSavedViewAction {
|
||||
key: Exclude<SavedViewRowActionKey, 'copyLink' | 'copyId'>;
|
||||
key: Exclude<SavedViewRowActionKey, 'copyLink'>;
|
||||
view: SavedviewtypesSavedViewDTO;
|
||||
}
|
||||
|
||||
@@ -150,7 +140,6 @@ export interface SavedViewsRowButtonProps {
|
||||
}
|
||||
|
||||
export interface SavedViewsRowMenuProps {
|
||||
viewId: string;
|
||||
onAction: (key: SavedViewRowActionKey) => void;
|
||||
onOpen: () => void;
|
||||
}
|
||||
@@ -163,7 +152,6 @@ export interface DeleteSavedViewDialogProps {
|
||||
|
||||
export interface UseSavedViewRowActionsResult {
|
||||
copyViewLink: (view: SavedviewtypesSavedViewDTO) => void;
|
||||
copyViewId: (view: SavedviewtypesSavedViewDTO) => void;
|
||||
renameView: (
|
||||
view: SavedviewtypesSavedViewDTO,
|
||||
displayName: string,
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import { useActiveLog } from '../useActiveLog';
|
||||
|
||||
const mockRedirect = jest.fn();
|
||||
|
||||
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
useQueryBuilder: (): unknown => ({
|
||||
currentQuery: initialQueriesMap.logs,
|
||||
redirectWithQueryBuilderData: mockRedirect,
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('hooks/useUrlQuery', () => ({
|
||||
__esModule: true,
|
||||
default: (): URLSearchParams => new URLSearchParams(),
|
||||
}));
|
||||
|
||||
describe('useActiveLog', () => {
|
||||
beforeEach(() => {
|
||||
mockRedirect.mockClear();
|
||||
});
|
||||
|
||||
it('adds the chip field as a filter with its data type and redirects', () => {
|
||||
const { result } = renderHook(() => useActiveLog());
|
||||
|
||||
result.current.onAddToQuery(
|
||||
'service.name',
|
||||
'frontend',
|
||||
'=',
|
||||
DataTypes.String,
|
||||
);
|
||||
|
||||
expect(mockRedirect).toHaveBeenCalledTimes(1);
|
||||
const query = mockRedirect.mock.calls[0][0] as Query;
|
||||
const item = query.builder.queryData[0].filters?.items.at(-1);
|
||||
expect(item?.key).toMatchObject({
|
||||
key: 'service.name',
|
||||
dataType: DataTypes.String,
|
||||
type: '',
|
||||
});
|
||||
expect(item?.op).toBe('=');
|
||||
expect(item?.value).toBe('frontend');
|
||||
});
|
||||
|
||||
it('keeps the existing filter items ahead of the new one', () => {
|
||||
const { result } = renderHook(() => useActiveLog());
|
||||
|
||||
result.current.onAddToQuery('k8s.pod.name', 'pod-1', '=');
|
||||
|
||||
const query = mockRedirect.mock.calls[0][0] as Query;
|
||||
const items = query.builder.queryData[0].filters?.items ?? [];
|
||||
expect(items).toHaveLength(
|
||||
(initialQueriesMap.logs.builder.queryData[0].filters?.items.length ?? 0) + 1,
|
||||
);
|
||||
expect(items.at(-1)?.key?.key).toBe('k8s.pod.name');
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ jest.mock('hooks/useIsTextSelected');
|
||||
const mockOnSetActiveLog = jest.fn();
|
||||
const mockOnClearActiveLog = jest.fn();
|
||||
const mockOnAddToQuery = jest.fn();
|
||||
const mockOnGroupByAttribute = jest.fn();
|
||||
const mockIsTextSelected = jest.fn();
|
||||
|
||||
const mockLog: ILog = {
|
||||
@@ -43,6 +44,7 @@ beforeEach(() => {
|
||||
onSetActiveLog: mockOnSetActiveLog,
|
||||
onClearActiveLog: mockOnClearActiveLog,
|
||||
onAddToQuery: mockOnAddToQuery,
|
||||
onGroupByAttribute: mockOnGroupByAttribute,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -78,6 +80,7 @@ it('should toggle off when clicking the same active log', () => {
|
||||
onSetActiveLog: mockOnSetActiveLog,
|
||||
onClearActiveLog: mockOnClearActiveLog,
|
||||
onAddToQuery: mockOnAddToQuery,
|
||||
onGroupByAttribute: mockOnGroupByAttribute,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useLogDetailHandlers());
|
||||
|
||||
@@ -25,4 +25,5 @@ export type UseActiveLog = {
|
||||
operator: string,
|
||||
dataType?: DataTypes,
|
||||
) => void;
|
||||
onGroupByAttribute: (fieldKey: string, dataType?: DataTypes) => Promise<void>;
|
||||
};
|
||||
|
||||
@@ -1,16 +1,40 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useQueryClient } from 'react-query';
|
||||
import { getAggregateKeys } from 'api/queryBuilder/getAttributeKeys';
|
||||
import { SOMETHING_WENT_WRONG } from 'constants/api';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { getFilterQueryData } from 'container/LogDetailedView/logAttributeActions.utils';
|
||||
import { OPERATORS, QueryBuilderKeys } from 'constants/queryBuilder';
|
||||
import { MetricsType } from 'container/MetricsApplication/constant';
|
||||
import { getOperatorValue } from 'container/QueryBuilder/filters/QueryBuilderSearchV2/utils';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { chooseAutocompleteFromCustomValue } from 'lib/newQueryBuilder/chooseAutocompleteFromCustomValue';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
import { UseActiveLog } from './types';
|
||||
|
||||
export function getOldLogsOperatorFromNew(operator: string): string {
|
||||
switch (operator) {
|
||||
case OPERATORS['=']:
|
||||
return OPERATORS.IN;
|
||||
case OPERATORS['!=']:
|
||||
return OPERATORS.NIN;
|
||||
default:
|
||||
return operator;
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
export const useActiveLog = (): UseActiveLog => {
|
||||
const queryClient = useQueryClient();
|
||||
const { currentQuery, redirectWithQueryBuilderData } = useQueryBuilder();
|
||||
const { notifications } = useNotifications();
|
||||
|
||||
const [activeLog, setActiveLog] = useState<ILog | null>(null);
|
||||
|
||||
@@ -34,32 +58,121 @@ export const useActiveLog = (): UseActiveLog => {
|
||||
|
||||
const onClearActiveLog = useCallback((): void => setActiveLog(null), []);
|
||||
|
||||
const onAddToQuery = useCallback(
|
||||
(
|
||||
const onAddToQueryExplorer = useCallback(
|
||||
async (
|
||||
fieldKey: string,
|
||||
fieldValue: string,
|
||||
operator: string,
|
||||
dataType?: DataTypes,
|
||||
): void => {
|
||||
const nextQuery: Query = {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: currentQuery.builder.queryData.map((item) =>
|
||||
getFilterQueryData(item, { fieldKey, dataType }, fieldValue, operator),
|
||||
),
|
||||
},
|
||||
};
|
||||
fieldType?: MetricsType | undefined,
|
||||
): Promise<void> => {
|
||||
try {
|
||||
const keysAutocompleteResponse = await queryClient.fetchQuery(
|
||||
[QueryBuilderKeys.GET_AGGREGATE_KEYS, fieldKey],
|
||||
async () =>
|
||||
getAggregateKeys({
|
||||
searchText: fieldKey,
|
||||
aggregateOperator:
|
||||
currentQuery.builder.queryData[0].aggregateOperator || '',
|
||||
dataSource: currentQuery.builder.queryData[0].dataSource,
|
||||
aggregateAttribute:
|
||||
currentQuery.builder.queryData[0].aggregateAttribute?.key || '',
|
||||
}),
|
||||
);
|
||||
|
||||
redirectWithQueryBuilderData(nextQuery);
|
||||
const keysAutocomplete: BaseAutocompleteData[] =
|
||||
keysAutocompleteResponse.payload?.attributeKeys || [];
|
||||
|
||||
const existAutocompleteKey = chooseAutocompleteFromCustomValue(
|
||||
keysAutocomplete,
|
||||
fieldKey,
|
||||
dataType,
|
||||
fieldType,
|
||||
);
|
||||
|
||||
const currentOperator = getOperatorValue(operator);
|
||||
|
||||
const nextQuery: Query = {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: currentQuery.builder.queryData.map((item) => ({
|
||||
...item,
|
||||
filters: {
|
||||
...item.filters,
|
||||
items: [
|
||||
...(item.filters?.items || []),
|
||||
{
|
||||
id: uuid(),
|
||||
key: existAutocompleteKey,
|
||||
op: currentOperator,
|
||||
value: fieldValue,
|
||||
},
|
||||
],
|
||||
op: item.filters?.op || 'AND',
|
||||
},
|
||||
})),
|
||||
},
|
||||
};
|
||||
|
||||
redirectWithQueryBuilderData(nextQuery);
|
||||
} catch {
|
||||
notifications.error({ message: SOMETHING_WENT_WRONG });
|
||||
}
|
||||
},
|
||||
[currentQuery, redirectWithQueryBuilderData],
|
||||
[currentQuery, notifications, queryClient, redirectWithQueryBuilderData],
|
||||
);
|
||||
|
||||
const onGroupByAttribute = useCallback(
|
||||
async (fieldKey: string, dataType?: DataTypes): Promise<void> => {
|
||||
try {
|
||||
const keysAutocompleteResponse = await queryClient.fetchQuery(
|
||||
[QueryBuilderKeys.GET_AGGREGATE_KEYS, fieldKey],
|
||||
// eslint-disable-next-line sonarjs/no-identical-functions
|
||||
async () =>
|
||||
getAggregateKeys({
|
||||
searchText: fieldKey,
|
||||
aggregateOperator:
|
||||
currentQuery.builder.queryData[0].aggregateOperator || '',
|
||||
dataSource: currentQuery.builder.queryData[0].dataSource,
|
||||
aggregateAttribute:
|
||||
currentQuery.builder.queryData[0].aggregateAttribute?.key || '',
|
||||
}),
|
||||
);
|
||||
|
||||
const keysAutocomplete: BaseAutocompleteData[] =
|
||||
keysAutocompleteResponse.payload?.attributeKeys || [];
|
||||
|
||||
const existAutocompleteKey = chooseAutocompleteFromCustomValue(
|
||||
keysAutocomplete,
|
||||
fieldKey,
|
||||
dataType,
|
||||
);
|
||||
|
||||
const nextQuery: Query = {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: currentQuery.builder.queryData.map((item) => ({
|
||||
...item,
|
||||
groupBy: [...item.groupBy, existAutocompleteKey],
|
||||
})),
|
||||
},
|
||||
};
|
||||
|
||||
redirectWithQueryBuilderData(nextQuery);
|
||||
} catch {
|
||||
notifications.error({ message: SOMETHING_WENT_WRONG });
|
||||
}
|
||||
},
|
||||
[currentQuery, notifications, queryClient, redirectWithQueryBuilderData],
|
||||
);
|
||||
|
||||
return {
|
||||
activeLog,
|
||||
onSetActiveLog,
|
||||
onClearActiveLog,
|
||||
onAddToQuery,
|
||||
onAddToQuery: onAddToQueryExplorer,
|
||||
onGroupByAttribute,
|
||||
};
|
||||
};
|
||||
|
||||
68
frontend/src/hooks/notificationChannels/useChannelOptions.ts
Normal file
68
frontend/src/hooks/notificationChannels/useChannelOptions.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { useQuery, UseQueryResult } from 'react-query';
|
||||
import { listNotificationChannels } from 'api/generated/services/channels';
|
||||
import {
|
||||
AlertmanagertypesChannelListOrderDTO,
|
||||
AlertmanagertypesChannelListSortDTO,
|
||||
AlertmanagertypesListedNotificationChannelDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { range } from 'lodash-es';
|
||||
|
||||
const PAGE_SIZE = 100;
|
||||
|
||||
export const CHANNEL_OPTIONS_QUERY_KEY = ['notificationChannelOptions'];
|
||||
|
||||
export interface ChannelOption {
|
||||
id: string;
|
||||
/** The display name, which is what rules and routing policies reference. */
|
||||
name: string;
|
||||
}
|
||||
|
||||
export type UseChannelOptionsResult = Omit<
|
||||
UseQueryResult<ChannelOption[], Error>,
|
||||
'data'
|
||||
> & {
|
||||
data: ChannelOption[];
|
||||
};
|
||||
|
||||
function fetchPage(
|
||||
offset: number,
|
||||
): ReturnType<typeof listNotificationChannels> {
|
||||
return listNotificationChannels({
|
||||
limit: PAGE_SIZE,
|
||||
offset,
|
||||
sort: AlertmanagertypesChannelListSortDTO.name,
|
||||
order: AlertmanagertypesChannelListOrderDTO.asc,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Every channel, for the pickers that let a rule or a policy name one. The list
|
||||
* API is paginated and silently clamps a larger limit, so the first page reports
|
||||
* the total and any remainder is fetched alongside rather than truncating. One
|
||||
* request covers an org with a page's worth of channels or fewer.
|
||||
*/
|
||||
async function fetchAllChannels(): Promise<ChannelOption[]> {
|
||||
const first = await fetchPage(0);
|
||||
const rest = await Promise.all(
|
||||
range(PAGE_SIZE, first.data.total, PAGE_SIZE).map(fetchPage),
|
||||
);
|
||||
|
||||
const channels: AlertmanagertypesListedNotificationChannelDTO[] = [
|
||||
...first.data.channels,
|
||||
...rest.flatMap((page) => page.data.channels),
|
||||
];
|
||||
|
||||
return channels.map((channel) => ({
|
||||
id: channel.id,
|
||||
name: channel.displayName,
|
||||
}));
|
||||
}
|
||||
|
||||
export function useChannelOptions(): UseChannelOptionsResult {
|
||||
const query = useQuery<ChannelOption[], Error>(
|
||||
CHANNEL_OPTIONS_QUERY_KEY,
|
||||
fetchAllChannels,
|
||||
);
|
||||
|
||||
return { ...query, data: query.data ?? [] };
|
||||
}
|
||||
@@ -23,11 +23,6 @@ export default {
|
||||
type: 'metaresource',
|
||||
allowedVerbs: ['list', 'read', 'update'],
|
||||
},
|
||||
{
|
||||
kind: 'saved-view',
|
||||
type: 'metaresource',
|
||||
allowedVerbs: ['create', 'delete', 'list', 'read', 'update'],
|
||||
},
|
||||
{
|
||||
kind: 'subscription',
|
||||
type: 'metaresource',
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import type { BrandedPermission } from '../types';
|
||||
import { buildPermission } from '../utils';
|
||||
|
||||
export const SavedViewListPermission = buildPermission('list', 'saved-view:*');
|
||||
export const SavedViewCreatePermission = buildPermission(
|
||||
'create',
|
||||
'saved-view:*',
|
||||
);
|
||||
|
||||
export const buildSavedViewReadPermission = (id: string): BrandedPermission =>
|
||||
buildPermission('read', `saved-view:${id}`);
|
||||
export const buildSavedViewUpdatePermission = (id: string): BrandedPermission =>
|
||||
buildPermission('update', `saved-view:${id}`);
|
||||
export const buildSavedViewDeletePermission = (id: string): BrandedPermission =>
|
||||
buildPermission('delete', `saved-view:${id}`);
|
||||
24
frontend/src/lib/logs/generateFilterQuery.ts
Normal file
24
frontend/src/lib/logs/generateFilterQuery.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { QueryOperatorsMultiVal } from 'lib/logql/tokens';
|
||||
|
||||
type Keys = keyof typeof QueryOperatorsMultiVal;
|
||||
type Values = (typeof QueryOperatorsMultiVal)[Keys];
|
||||
|
||||
interface GenerateFilterQueryParams {
|
||||
fieldKey: string;
|
||||
fieldValue: string;
|
||||
type: Values;
|
||||
}
|
||||
export const generateFilterQuery = ({
|
||||
fieldKey,
|
||||
fieldValue,
|
||||
type,
|
||||
}: GenerateFilterQueryParams): string => {
|
||||
let generatedQueryString = `${fieldKey} ${type} `;
|
||||
if (typeof fieldValue === 'number') {
|
||||
generatedQueryString += `(${fieldValue})`;
|
||||
} else {
|
||||
generatedQueryString += `('${fieldValue}')`;
|
||||
}
|
||||
|
||||
return generatedQueryString;
|
||||
};
|
||||
@@ -51,3 +51,38 @@ export const opsGeniePriorityDefaultValue =
|
||||
|
||||
export const pagerDutySeverityTextDefaultValue =
|
||||
'{{ (index .Alerts 0).Labels.severity }}';
|
||||
|
||||
export const notificationChannelsV2 = [
|
||||
{
|
||||
id: '3',
|
||||
name: 'dummy-channel',
|
||||
displayName: 'Dummy-Channel',
|
||||
kind: 'slack',
|
||||
createdAt: '2023-08-09T04:45:19.239344617Z',
|
||||
updatedAt: '2024-06-27T11:37:14.841184399Z',
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
name: 'oncall-pagerduty',
|
||||
displayName: 'Oncall PagerDuty',
|
||||
kind: 'pagerduty',
|
||||
createdAt: '2024-02-03T04:45:19.239344617Z',
|
||||
updatedAt: '2024-06-28T11:37:14.841184399Z',
|
||||
},
|
||||
];
|
||||
|
||||
export const notificationChannelV2 = {
|
||||
id: '3',
|
||||
name: 'dummy-channel',
|
||||
displayName: 'Dummy-Channel',
|
||||
createdAt: '2023-08-09T04:45:19.239344617Z',
|
||||
updatedAt: '2024-06-27T11:37:14.841184399Z',
|
||||
config: {
|
||||
kind: 'slack',
|
||||
spec: {
|
||||
apiUrl: 'https://hooks.slack.com/services/dummy',
|
||||
channel: '#dummy_channel',
|
||||
sendResolved: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -2,7 +2,11 @@ import { rest } from 'msw';
|
||||
|
||||
import commonEnTranslation from '../../public/locales/en/common.json';
|
||||
import enTranslation from '../../public/locales/en/translation.json';
|
||||
import { allAlertChannels } from './__mockdata__/alerts';
|
||||
import {
|
||||
allAlertChannels,
|
||||
notificationChannelsV2,
|
||||
notificationChannelV2,
|
||||
} from './__mockdata__/alerts';
|
||||
import { alertRulesFixture } from './__mockdata__/alert_rules';
|
||||
import { triggeredAlertsFixture } from './__mockdata__/triggered_alerts';
|
||||
import { billingSuccessResponse } from './__mockdata__/billing';
|
||||
@@ -205,6 +209,32 @@ export const handlers = [
|
||||
rest.get('http://localhost/api/v1/channels', (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ data: allAlertChannels, status: 'success' })),
|
||||
),
|
||||
rest.get('http://localhost/api/v2/notification_channels', (req, res, ctx) => {
|
||||
const query = req.url.searchParams.get('query')?.toLowerCase() ?? '';
|
||||
const kind = req.url.searchParams.get('kind');
|
||||
const channels = notificationChannelsV2.filter(
|
||||
(channel) =>
|
||||
(!query || channel.displayName.toLowerCase().includes(query)) &&
|
||||
(!kind || channel.kind === kind),
|
||||
);
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
data: { channels, total: channels.length },
|
||||
status: 'success',
|
||||
}),
|
||||
);
|
||||
}),
|
||||
rest.get('http://localhost/api/v2/notification_channels/:id', (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({ data: notificationChannelV2, status: 'success' }),
|
||||
),
|
||||
),
|
||||
rest.delete(
|
||||
'http://localhost/api/v2/notification_channels/:id',
|
||||
(_, res, ctx) => res(ctx.status(204)),
|
||||
),
|
||||
rest.get('http://localhost/api/v1/alerts', (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
import {
|
||||
alertRuleByIdResponse,
|
||||
ALERT_SCHEMAS,
|
||||
channelsResponse,
|
||||
notificationChannelsResponse,
|
||||
CHANNEL_MAX,
|
||||
FIRST_RULE_NAME,
|
||||
type AlertSchema,
|
||||
@@ -148,8 +148,8 @@ export const alertHistoryMocks = defineStoryMocks({
|
||||
),
|
||||
|
||||
rest.get(
|
||||
'http://localhost/api/v1/channels',
|
||||
response.json(() => channelsResponse(CHANNEL_MAX)),
|
||||
'http://localhost/api/v2/notification_channels',
|
||||
response.json(() => notificationChannelsResponse(CHANNEL_MAX)),
|
||||
),
|
||||
],
|
||||
config: () => ({
|
||||
|
||||
@@ -12,7 +12,7 @@ import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import {
|
||||
alertRuleByIdResponse,
|
||||
ALERT_SCHEMAS,
|
||||
channelsResponse,
|
||||
notificationChannelsResponse,
|
||||
CHANNEL_MAX,
|
||||
RULE_STATE_CHOICES,
|
||||
SEVERITY_CHOICES,
|
||||
@@ -116,8 +116,8 @@ export const alertOverviewMocks = defineStoryMocks({
|
||||
),
|
||||
|
||||
rest.get(
|
||||
'http://localhost/api/v1/channels',
|
||||
response.json(() => channelsResponse(values.channels)),
|
||||
'http://localhost/api/v2/notification_channels',
|
||||
response.json(() => notificationChannelsResponse(values.channels)),
|
||||
),
|
||||
|
||||
rest.post(
|
||||
|
||||
@@ -10,7 +10,7 @@ import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
|
||||
import {
|
||||
CHANNEL_MAX,
|
||||
channelsResponse,
|
||||
notificationChannelsResponse,
|
||||
} from '../../stories/__story_mockdata__/alerts';
|
||||
import { AlertListTabs } from '../../types';
|
||||
|
||||
@@ -27,8 +27,8 @@ export const channelsMocks = defineStoryMocks({
|
||||
},
|
||||
handlers: (values, response) => [
|
||||
rest.get(
|
||||
'http://localhost/api/v1/channels',
|
||||
response.json(() => channelsResponse(values.channels)),
|
||||
'http://localhost/api/v2/notification_channels',
|
||||
response.json(() => notificationChannelsResponse(values.channels)),
|
||||
),
|
||||
],
|
||||
config: () => ({ route: `/alerts?tab=${AlertListTabs.CHANNELS}` }),
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
.container {
|
||||
--control-height: 2rem;
|
||||
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: calc(100vh - 62px);
|
||||
min-height: 400px;
|
||||
|
||||
--combobox-trigger-height: var(--control-height);
|
||||
--select-trigger-height: var(--control-height);
|
||||
--input-height: var(--control-height);
|
||||
--input-wrapper-height: var(--control-height);
|
||||
--button-height: var(--control-height);
|
||||
}
|
||||
|
||||
/* Title, count and filters sit on the page surface, with matching space above
|
||||
and below before the table starts. */
|
||||
.headerBand {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-6);
|
||||
flex-shrink: 0;
|
||||
padding: var(--spacing-6) var(--spacing-8);
|
||||
}
|
||||
|
||||
/* Title and count on the left, the create action at the far end, the way the
|
||||
dashboards list opens. */
|
||||
.commandHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.headingBlock {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
color: var(--l1-foreground);
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 28px;
|
||||
letter-spacing: -0.09px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.countPill {
|
||||
padding: 2px 9px;
|
||||
border-radius: 999px;
|
||||
background: var(--l2-background);
|
||||
border: 1px solid var(--l2-border);
|
||||
color: var(--l2-foreground);
|
||||
font-size: var(--font-size-xs);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.grow {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* Search and the type filter, the band's second row. */
|
||||
.filtersRow {
|
||||
position: relative;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* Spans the row, the way the dashboards filter bar does. The input's own
|
||||
wrapper is `width: 100%`, so the basis has to be 0 or `auto` resolves to the
|
||||
full row and wraps the type filter onto the next line. */
|
||||
.searchInput {
|
||||
flex: 1 1 0;
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
.kindSelect {
|
||||
/* the trigger sizes itself to 100%, so the flex item has to be bounded */
|
||||
flex: 0 0 180px;
|
||||
width: 180px;
|
||||
max-width: 180px;
|
||||
}
|
||||
|
||||
/* The options panel is rendered inline (withPortal={false}) so it can be told to
|
||||
match the trigger; Radix publishes that width at the popper layer. */
|
||||
.filtersRow :global([data-slot='select-content']) {
|
||||
width: var(--radix-select-trigger-width);
|
||||
min-width: var(--radix-select-trigger-width);
|
||||
}
|
||||
|
||||
.commandHeader > button {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.searchIcon {
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.actionsHeader {
|
||||
display: block;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
/* Left on the table's own defaults, the way Infrastructure Monitoring uses it:
|
||||
transparent cells over the page background rather than a raised slab. */
|
||||
.tableContainer {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
--tanstack-table-row-hover-bg: var(--l2-background-hover);
|
||||
--tanstack-table-row-active-bg: var(--l2-background-active);
|
||||
--tanstack-table-row-height: 42px;
|
||||
|
||||
--tanstack-cell-padding-top-override: 5px;
|
||||
--tanstack-cell-padding-bottom-override: 5px;
|
||||
--tanstack-cell-padding-left-override: 16px;
|
||||
--tanstack-cell-padding-right-override: 16px;
|
||||
|
||||
--tanstack-table-row-odd-bg: color-mix(
|
||||
in srgb,
|
||||
var(--l1-foreground) 2%,
|
||||
transparent
|
||||
);
|
||||
--tanstack-table-row-even-bg: color-mix(
|
||||
in srgb,
|
||||
var(--l1-foreground) 1%,
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
.paginationContainer {
|
||||
padding-right: var(--spacing-12);
|
||||
height: 62px;
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Plus, Search } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import { SelectSimple } from '@signozhq/ui/select';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import ErrorEmptyState from 'components/Alerts/ErrorEmptyState';
|
||||
import NoResultsEmptyState from 'components/Alerts/NoResultsEmptyState';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
import { useCalculatedPageSize } from 'components/TanStackTableView/useCalculatedPageSize';
|
||||
import { useTableParams } from 'components/TanStackTableView/useTableParams';
|
||||
import TextToolTip from 'components/TextToolTip';
|
||||
import { useUrlSearchState } from 'hooks/useUrlSearchState';
|
||||
import { parseAsString, useQueryState } from 'nuqs';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
|
||||
import ChannelActionsMenu from './components/ChannelActionsMenu/ChannelActionsMenu';
|
||||
import ChannelJsonDialog from './components/ChannelJsonDialog/ChannelJsonDialog';
|
||||
import {
|
||||
KIND_FILTER_ALL,
|
||||
KIND_FILTER_OPTIONS,
|
||||
KIND_KEY,
|
||||
SEARCH_KEY,
|
||||
} from './constants';
|
||||
import { useChannelDelete } from './hooks/useChannelDelete';
|
||||
import { useChannelFormView } from './hooks/useChannelFormView';
|
||||
import { useChannelsData } from './hooks/useChannelsData';
|
||||
import styles from './NotificationChannels.module.scss';
|
||||
import { getChannelColumns } from './table.config';
|
||||
import type { Channel } from './types';
|
||||
|
||||
const QUERY_PARAMS_CONFIG = {
|
||||
orderBy: 'orderBy',
|
||||
page: 'page',
|
||||
limit: 'limit',
|
||||
} as const;
|
||||
|
||||
const DEFAULT_PAGE = 1;
|
||||
const DEFAULT_LIMIT = 10;
|
||||
|
||||
function NotificationChannels(): JSX.Element {
|
||||
const { formatTimezoneAdjustedTimestamp } = useTimezone();
|
||||
const formView = useChannelFormView();
|
||||
|
||||
const { containerRef, calculatedPageSize } = useCalculatedPageSize({
|
||||
rowHeight: 46,
|
||||
});
|
||||
|
||||
const { orderBy, page, limit, setLimit, setPage } = useTableParams(
|
||||
QUERY_PARAMS_CONFIG,
|
||||
{
|
||||
page: DEFAULT_PAGE,
|
||||
limit: DEFAULT_LIMIT,
|
||||
storageKey: 'notification-channels',
|
||||
calculatedPageSize,
|
||||
cleanupOnUnmount: true,
|
||||
},
|
||||
);
|
||||
|
||||
const resetPageOnSearch = useCallback((): void => {
|
||||
setPage(1);
|
||||
}, [setPage]);
|
||||
|
||||
const { searchText, debouncedSearch, handleSearchChange, clearSearch } =
|
||||
useUrlSearchState(SEARCH_KEY, { onDebouncedChange: resetPageOnSearch });
|
||||
|
||||
const [kind, setKind] = useQueryState(
|
||||
KIND_KEY,
|
||||
parseAsString.withDefault(KIND_FILTER_ALL),
|
||||
);
|
||||
|
||||
const handleKindChange = useCallback(
|
||||
(value: string | string[]): void => {
|
||||
const next = value as string;
|
||||
void setKind(next === KIND_FILTER_ALL ? null : next);
|
||||
setPage(1);
|
||||
},
|
||||
[setKind, setPage],
|
||||
);
|
||||
|
||||
const { channels, total, isFetching, isError, refetch } = useChannelsData({
|
||||
search: debouncedSearch,
|
||||
kind,
|
||||
orderBy,
|
||||
page,
|
||||
limit,
|
||||
});
|
||||
|
||||
const deletion = useChannelDelete();
|
||||
const [jsonChannel, setJsonChannel] = useState<Channel | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
void logEvent('Alert Channel: Channel list page visited', {});
|
||||
}, []);
|
||||
|
||||
const handleEdit = useCallback(
|
||||
(channel: Channel, options?: { newTab?: boolean }): void => {
|
||||
formView.openEdit(channel.id, options);
|
||||
},
|
||||
[formView],
|
||||
);
|
||||
|
||||
const handleRowClick = useCallback(
|
||||
(channel: Channel): void => formView.openEdit(channel.id),
|
||||
[formView],
|
||||
);
|
||||
|
||||
const handleRowClickNewTab = useCallback(
|
||||
(channel: Channel): void => formView.openEdit(channel.id, { newTab: true }),
|
||||
[formView],
|
||||
);
|
||||
|
||||
const columns = useMemo(
|
||||
() => getChannelColumns(formatTimezoneAdjustedTimestamp),
|
||||
[formatTimezoneAdjustedTimestamp],
|
||||
);
|
||||
|
||||
const columnsWithActions = useMemo(
|
||||
() => [
|
||||
...columns,
|
||||
{
|
||||
id: 'actions',
|
||||
header: (): JSX.Element => (
|
||||
<span className={styles.actionsHeader}>Actions</span>
|
||||
),
|
||||
accessorKey: 'id',
|
||||
width: { fixed: '96px', ignoreLastColumnFill: true },
|
||||
enableSort: false,
|
||||
enableResize: false,
|
||||
enableRemove: false,
|
||||
enableMove: false,
|
||||
pin: 'right' as const,
|
||||
cell: ({ row }: { row: Channel }): JSX.Element => (
|
||||
<ChannelActionsMenu
|
||||
channel={row}
|
||||
onOpen={handleEdit}
|
||||
onDelete={deletion.request}
|
||||
onViewJson={setJsonChannel}
|
||||
/>
|
||||
),
|
||||
},
|
||||
],
|
||||
[columns, handleEdit, deletion.request],
|
||||
);
|
||||
|
||||
const hasActiveFilters = searchText.length > 0 || kind !== KIND_FILTER_ALL;
|
||||
const isEmpty = !isFetching && channels.length === 0;
|
||||
|
||||
const handleClearFilters = useCallback((): void => {
|
||||
clearSearch();
|
||||
void setKind(null);
|
||||
}, [clearSearch, setKind]);
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<header className={styles.headerBand}>
|
||||
<div className={styles.commandHeader}>
|
||||
<div className={styles.headingBlock}>
|
||||
<Typography.Title className={styles.title}>
|
||||
All notification channels
|
||||
</Typography.Title>
|
||||
<span className={styles.countPill}>{total}</span>
|
||||
</div>
|
||||
<div className={styles.grow} />
|
||||
<TextToolTip
|
||||
text="More details on how to configure notification channels"
|
||||
url="https://signoz.io/docs/setup-alerts-notification/"
|
||||
urlText="Learn More"
|
||||
/>
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
size="sm"
|
||||
prefix={<Plus size={14} />}
|
||||
onClick={formView.openCreate}
|
||||
testId="channels-create"
|
||||
>
|
||||
New channel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className={styles.filtersRow}>
|
||||
<Input
|
||||
containerClassName={styles.searchInput}
|
||||
placeholder="Search by channel name"
|
||||
value={searchText}
|
||||
onChange={handleSearchChange}
|
||||
suffix={<Search size={14} className={styles.searchIcon} />}
|
||||
testId="channels-search"
|
||||
/>
|
||||
<SelectSimple
|
||||
className={styles.kindSelect}
|
||||
items={KIND_FILTER_OPTIONS}
|
||||
value={kind}
|
||||
onChange={handleKindChange}
|
||||
withPortal={false}
|
||||
testId="channels-kind-filter"
|
||||
/>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div ref={containerRef} className={styles.tableContainer}>
|
||||
{isError ? (
|
||||
<ErrorEmptyState
|
||||
title="Failed to load notification channels"
|
||||
onRefresh={refetch}
|
||||
/>
|
||||
) : isEmpty && hasActiveFilters ? (
|
||||
<NoResultsEmptyState
|
||||
title="No matching channels"
|
||||
subtitle="No notification channels match your search. Try adjusting your search criteria."
|
||||
onClear={handleClearFilters}
|
||||
clearButtonText="Clear Search"
|
||||
/>
|
||||
) : (
|
||||
<TanStackTable<Channel>
|
||||
data={channels}
|
||||
columns={columnsWithActions}
|
||||
isLoading={isFetching}
|
||||
getRowKey={(row): string => row.id}
|
||||
getItemKey={(row): string => row.id}
|
||||
columnStorageKey="notification-channels-columns"
|
||||
enableQueryParams={QUERY_PARAMS_CONFIG}
|
||||
onRowClick={handleRowClick}
|
||||
onRowClickNewTab={handleRowClickNewTab}
|
||||
pagination={{
|
||||
total,
|
||||
calculatedPageSize,
|
||||
onLimitChange: setLimit,
|
||||
showTotalCount: true,
|
||||
}}
|
||||
paginationClassname={styles.paginationContainer}
|
||||
enableAlternatingRowColors
|
||||
plainTextCellLineClamp={1}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{jsonChannel && (
|
||||
<ChannelJsonDialog
|
||||
channelId={jsonChannel.id}
|
||||
channelName={jsonChannel.displayName}
|
||||
onClose={(): void => setJsonChannel(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{deletion.contextHolder}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default NotificationChannels;
|
||||
@@ -0,0 +1,100 @@
|
||||
import { server } from 'mocks-server/server';
|
||||
import { screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { renderChannels } from './renderChannels';
|
||||
|
||||
const FIND = { timeout: 5000 };
|
||||
const TEST_TIMEOUT = 20000;
|
||||
|
||||
describe('Notification channels list', () => {
|
||||
beforeEach(() => {
|
||||
// search, filter and page live in the url, so one test's filter would
|
||||
// otherwise still be applied in the next
|
||||
window.history.replaceState({}, '', '/');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it(
|
||||
'heads the page with the channel count',
|
||||
async () => {
|
||||
renderChannels();
|
||||
|
||||
await expect(
|
||||
screen.findByText('All notification channels', {}, FIND),
|
||||
).resolves.toBeInTheDocument();
|
||||
// the count comes from the API's total, not the loaded page
|
||||
await expect(screen.findByText('2', {}, FIND)).resolves.toBeInTheDocument();
|
||||
},
|
||||
TEST_TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
'lists every channel with its type',
|
||||
async () => {
|
||||
renderChannels();
|
||||
|
||||
await expect(
|
||||
screen.findByText('Dummy-Channel', {}, FIND),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText('Oncall PagerDuty')).toBeInTheDocument();
|
||||
// the type reads as plain text, no colour coding
|
||||
expect(screen.getByText('Slack')).toBeInTheDocument();
|
||||
expect(screen.getByText('PagerDuty')).toBeInTheDocument();
|
||||
},
|
||||
TEST_TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
'filters server-side as the user types',
|
||||
async () => {
|
||||
renderChannels();
|
||||
|
||||
await screen.findByText('Dummy-Channel', {}, FIND);
|
||||
|
||||
await userEvent.type(screen.getByTestId('channels-search'), 'oncall');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Dummy-Channel')).not.toBeInTheDocument();
|
||||
}, FIND);
|
||||
await expect(
|
||||
screen.findByText('Oncall PagerDuty', {}, FIND),
|
||||
).resolves.toBeInTheDocument();
|
||||
},
|
||||
TEST_TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
'asks for confirmation before deleting, from the row menu',
|
||||
async () => {
|
||||
renderChannels();
|
||||
|
||||
await screen.findByText('Dummy-Channel', {}, FIND);
|
||||
// the table paints a loading layer over the rows until the fetch settles
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
await user.click(screen.getByTestId('channel-actions-3'));
|
||||
// Radix renders the menu into a portal once the trigger is activated
|
||||
await screen.findByRole('menu', {}, FIND);
|
||||
// the menu lives inside the row's clickable cell, so opening it must not
|
||||
// also fire the row click and route to the edit screen
|
||||
expect(window.location.pathname).not.toContain('/channels/edit/');
|
||||
|
||||
await user.click(
|
||||
await screen.findByRole('menuitem', { name: 'Delete' }, FIND),
|
||||
);
|
||||
|
||||
// the shared destructive confirmation, the one dashboards also use
|
||||
await expect(
|
||||
screen.findByText(
|
||||
/Are you sure you want to delete the Dummy-Channel channel\?/,
|
||||
{},
|
||||
FIND,
|
||||
),
|
||||
).resolves.toBeInTheDocument();
|
||||
},
|
||||
TEST_TIMEOUT,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { AlertmanagertypesGettableNotificationChannelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import {
|
||||
channelToJson,
|
||||
hasSecrets,
|
||||
SECRET_PLACEHOLDER,
|
||||
} from '../utils/channelJson';
|
||||
|
||||
const slackChannel = {
|
||||
id: '1',
|
||||
name: 'prod-alerts',
|
||||
displayName: 'prod alerts',
|
||||
createdAt: '2026-09-01T00:00:00Z',
|
||||
updatedAt: '2026-09-01T00:00:00Z',
|
||||
config: {
|
||||
kind: 'slack',
|
||||
spec: {
|
||||
apiUrl: 'https://hooks.slack.com/services/T/B/SECRET',
|
||||
channel: '#alerts',
|
||||
sendResolved: true,
|
||||
},
|
||||
},
|
||||
} as AlertmanagertypesGettableNotificationChannelDTO;
|
||||
|
||||
describe('channelToJson', () => {
|
||||
it('hides the credential the API returns in the clear', () => {
|
||||
const json = JSON.parse(channelToJson(slackChannel, false));
|
||||
|
||||
expect(json.config.spec.apiUrl).toBe(SECRET_PLACEHOLDER);
|
||||
expect(json.config.spec.channel).toBe('#alerts');
|
||||
expect(channelToJson(slackChannel, false)).not.toContain('SECRET');
|
||||
});
|
||||
|
||||
it('reveals it only when asked', () => {
|
||||
const json = JSON.parse(channelToJson(slackChannel, true));
|
||||
|
||||
expect(json.config.spec.apiUrl).toBe(
|
||||
'https://hooks.slack.com/services/T/B/SECRET',
|
||||
);
|
||||
});
|
||||
|
||||
it('leaves the timestamps and id out, so the JSON can be reused', () => {
|
||||
const json = JSON.parse(channelToJson(slackChannel, true));
|
||||
|
||||
expect(json).not.toHaveProperty('id');
|
||||
expect(json).not.toHaveProperty('createdAt');
|
||||
expect(json.name).toBe('prod-alerts');
|
||||
});
|
||||
|
||||
it('knows which kinds carry a credential', () => {
|
||||
expect(hasSecrets('slack')).toBe(true);
|
||||
expect(hasSecrets('email')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { VirtuosoMockContext } from 'react-virtuoso';
|
||||
import { render } from 'tests/test-utils';
|
||||
|
||||
import NotificationChannels from '../NotificationChannels';
|
||||
|
||||
/** The list is virtualized, so jsdom needs a viewport for rows to mount. */
|
||||
export function renderChannels(): ReturnType<typeof render> {
|
||||
return render(
|
||||
<VirtuosoMockContext.Provider value={{ viewportHeight: 800, itemHeight: 46 }}>
|
||||
<NotificationChannels />
|
||||
</VirtuosoMockContext.Provider>,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.actions button {
|
||||
opacity: 0.7;
|
||||
transition: opacity 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { useMemo } from 'react';
|
||||
import {
|
||||
Braces,
|
||||
Ellipsis,
|
||||
PenLine,
|
||||
SquareArrowOutUpRight,
|
||||
Trash2,
|
||||
} from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
|
||||
|
||||
import type { Channel } from '../../types';
|
||||
import styles from './ChannelActionsMenu.module.scss';
|
||||
|
||||
interface ChannelActionsMenuProps {
|
||||
channel: Channel;
|
||||
onOpen: (channel: Channel, options?: { newTab?: boolean }) => void;
|
||||
onDelete: (channel: Channel) => void;
|
||||
onViewJson: (channel: Channel) => void;
|
||||
}
|
||||
|
||||
function ChannelActionsMenu({
|
||||
channel,
|
||||
onOpen,
|
||||
onDelete,
|
||||
onViewJson,
|
||||
}: ChannelActionsMenuProps): JSX.Element {
|
||||
const menuItems = useMemo<DropdownItemType[]>(
|
||||
() => [
|
||||
{
|
||||
type: 'item',
|
||||
value: 'open',
|
||||
label: 'Edit',
|
||||
prefix: <PenLine size={14} />,
|
||||
onClick: (): void => onOpen(channel),
|
||||
},
|
||||
{
|
||||
type: 'item',
|
||||
value: 'open-new-tab',
|
||||
label: 'Open in New Tab',
|
||||
prefix: <SquareArrowOutUpRight size={14} />,
|
||||
onClick: (): void => onOpen(channel, { newTab: true }),
|
||||
},
|
||||
{
|
||||
type: 'item',
|
||||
value: 'view-json',
|
||||
label: 'View JSON',
|
||||
prefix: <Braces size={14} />,
|
||||
onClick: (): void => onViewJson(channel),
|
||||
},
|
||||
{ type: 'separator', value: 'before-delete' },
|
||||
{
|
||||
type: 'item',
|
||||
value: 'delete',
|
||||
label: 'Delete',
|
||||
prefix: <Trash2 size={14} />,
|
||||
danger: true,
|
||||
onClick: (): void => onDelete(channel),
|
||||
},
|
||||
],
|
||||
[channel, onOpen, onDelete, onViewJson],
|
||||
);
|
||||
|
||||
return (
|
||||
// the row itself opens the channel, so the actions keep their clicks
|
||||
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
|
||||
<div
|
||||
className={styles.actions}
|
||||
onClick={(event): void => event.stopPropagation()}
|
||||
>
|
||||
<Dropdown items={menuItems} nativeButton align="end" side="bottom">
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
icon
|
||||
testId={`channel-actions-${channel.id}`}
|
||||
aria-label={`Actions for ${channel.displayName}`}
|
||||
>
|
||||
<Ellipsis size={16} />
|
||||
</Button>
|
||||
</Dropdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ChannelActionsMenu;
|
||||
@@ -0,0 +1,26 @@
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-3);
|
||||
height: 100%;
|
||||
min-height: 420px;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-2);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.spacer {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.editor {
|
||||
flex: 1 1 auto;
|
||||
min-height: 360px;
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCopyToClipboard } from 'react-use';
|
||||
import MEditor from '@monaco-editor/react';
|
||||
import { DrawerWrapper } from '@signozhq/ui/drawer';
|
||||
import { useGetNotificationChannel } from 'api/generated/services/channels';
|
||||
import ErrorEmptyState from 'components/Alerts/ErrorEmptyState';
|
||||
import Spinner from 'components/Spinner';
|
||||
import { READONLY_EDITOR_OPTIONS } from 'container/RolesSettings/monaco.config';
|
||||
import {
|
||||
defineJsonEditorTheme,
|
||||
JSON_EDITOR_THEME,
|
||||
} from 'lib/monaco/jsonEditorTheme';
|
||||
|
||||
import { channelToJson, hasSecrets } from '../../utils/channelJson';
|
||||
import styles from './ChannelJsonDialog.module.scss';
|
||||
import ChannelJsonToolbar from './ChannelJsonToolbar';
|
||||
|
||||
interface ChannelJsonDialogProps {
|
||||
channelId: string;
|
||||
channelName: string;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
function ChannelJsonDialog({
|
||||
channelId,
|
||||
channelName,
|
||||
onClose,
|
||||
}: ChannelJsonDialogProps): JSX.Element {
|
||||
const [copyState, copyToClipboard] = useCopyToClipboard();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [showSecrets, setShowSecrets] = useState(false);
|
||||
|
||||
const { data, isLoading, refetch } = useGetNotificationChannel({
|
||||
id: channelId,
|
||||
});
|
||||
const channel = data?.data;
|
||||
|
||||
const json = useMemo(
|
||||
() => (channel ? channelToJson(channel, showSecrets) : ''),
|
||||
[channel, showSecrets],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (copyState.value) {
|
||||
setCopied(true);
|
||||
const timer = setTimeout(() => setCopied(false), 1500);
|
||||
return (): void => clearTimeout(timer);
|
||||
}
|
||||
return undefined;
|
||||
}, [copyState]);
|
||||
|
||||
const handleCopy = useCallback(
|
||||
(): void => copyToClipboard(json),
|
||||
[copyToClipboard, json],
|
||||
);
|
||||
|
||||
const handleRefetch = useCallback((): void => {
|
||||
void refetch();
|
||||
}, [refetch]);
|
||||
|
||||
const handleToggleSecrets = useCallback(
|
||||
(): void => setShowSecrets((value) => !value),
|
||||
[],
|
||||
);
|
||||
|
||||
const kindHasSecrets = channel ? hasSecrets(channel.config.kind) : false;
|
||||
|
||||
return (
|
||||
<DrawerWrapper
|
||||
open
|
||||
onOpenChange={(isOpen): void => {
|
||||
if (!isOpen) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
title={channelName}
|
||||
subTitle="Channel JSON"
|
||||
width="wide"
|
||||
testId="channel-json-dialog"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Spinner tip="Loading channel..." />
|
||||
) : !channel ? (
|
||||
<ErrorEmptyState title="Failed to load channel" onRefresh={handleRefetch} />
|
||||
) : (
|
||||
<div className={styles.body}>
|
||||
<ChannelJsonToolbar
|
||||
kindHasSecrets={kindHasSecrets}
|
||||
showSecrets={showSecrets}
|
||||
onToggleSecrets={handleToggleSecrets}
|
||||
copied={copied}
|
||||
onCopy={handleCopy}
|
||||
/>
|
||||
|
||||
<div className={styles.editor}>
|
||||
<MEditor
|
||||
value={json}
|
||||
language="json"
|
||||
options={READONLY_EDITOR_OPTIONS}
|
||||
height="100%"
|
||||
theme="vs-dark"
|
||||
// the same theme the dashboard JSON drawer uses: it reads the
|
||||
// page's own tokens, so it follows light and dark
|
||||
onMount={(editor, monaco): void => {
|
||||
defineJsonEditorTheme(monaco, editor.getContainerDomNode());
|
||||
monaco.editor.setTheme(JSON_EDITOR_THEME);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DrawerWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
export default ChannelJsonDialog;
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Check, Copy, Eye, EyeOff } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import styles from './ChannelJsonDialog.module.scss';
|
||||
|
||||
interface ChannelJsonToolbarProps {
|
||||
kindHasSecrets: boolean;
|
||||
showSecrets: boolean;
|
||||
onToggleSecrets: () => void;
|
||||
copied: boolean;
|
||||
onCopy: () => void;
|
||||
}
|
||||
|
||||
function ChannelJsonToolbar({
|
||||
kindHasSecrets,
|
||||
showSecrets,
|
||||
onToggleSecrets,
|
||||
copied,
|
||||
onCopy,
|
||||
}: ChannelJsonToolbarProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.toolbar}>
|
||||
{kindHasSecrets && (
|
||||
<Typography.Text color="muted" size="sm">
|
||||
{showSecrets ? 'Credentials are visible.' : 'Credentials are hidden.'}
|
||||
</Typography.Text>
|
||||
)}
|
||||
<span className={styles.spacer} />
|
||||
{kindHasSecrets && (
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
prefix={showSecrets ? <EyeOff size={14} /> : <Eye size={14} />}
|
||||
onClick={onToggleSecrets}
|
||||
testId="channel-json-toggle-secrets"
|
||||
>
|
||||
{showSecrets ? 'Hide credentials' : 'Show credentials'}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
prefix={
|
||||
copied ? (
|
||||
<Check size={14} color={Color.BG_FOREST_400} />
|
||||
) : (
|
||||
<Copy size={14} />
|
||||
)
|
||||
}
|
||||
onClick={onCopy}
|
||||
testId="channel-json-copy"
|
||||
>
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ChannelJsonToolbar;
|
||||
@@ -0,0 +1,34 @@
|
||||
import { AlertmanagertypesChannelKindDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
export const SEARCH_KEY = 'search';
|
||||
export const KIND_KEY = 'kind';
|
||||
export const PAGE_KEY = 'page';
|
||||
|
||||
export const PAGE_SIZE = 20;
|
||||
export const SEARCH_DEBOUNCE_MS = 300;
|
||||
|
||||
export const CHANNEL_KIND_LABEL: Record<
|
||||
AlertmanagertypesChannelKindDTO,
|
||||
string
|
||||
> = {
|
||||
[AlertmanagertypesChannelKindDTO.slack]: 'Slack',
|
||||
[AlertmanagertypesChannelKindDTO.email]: 'Email',
|
||||
[AlertmanagertypesChannelKindDTO.webhook]: 'Webhook',
|
||||
[AlertmanagertypesChannelKindDTO.pagerduty]: 'PagerDuty',
|
||||
[AlertmanagertypesChannelKindDTO.opsgenie]: 'Opsgenie',
|
||||
[AlertmanagertypesChannelKindDTO.msteams]: 'MS Teams',
|
||||
[AlertmanagertypesChannelKindDTO.googlechat]: 'Google Chat',
|
||||
[AlertmanagertypesChannelKindDTO.jira]: 'Jira',
|
||||
[AlertmanagertypesChannelKindDTO.jsmops]: 'JSM Ops',
|
||||
[AlertmanagertypesChannelKindDTO.incidentio]: 'incident.io',
|
||||
};
|
||||
|
||||
export const KIND_FILTER_ALL = 'all';
|
||||
|
||||
export const KIND_FILTER_OPTIONS = [
|
||||
{ value: KIND_FILTER_ALL, label: 'All types' },
|
||||
...Object.entries(CHANNEL_KIND_LABEL).map(([value, label]) => ({
|
||||
value,
|
||||
label,
|
||||
})),
|
||||
];
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useQueryClient } from 'react-query';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import {
|
||||
invalidateListNotificationChannels,
|
||||
useDeleteNotificationChannel,
|
||||
} from 'api/generated/services/channels';
|
||||
import { useDeleteConfirm } from 'components/DeleteConfirmModal/useDeleteConfirm';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import { ReactNode } from 'react';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
import type { Channel } from '../types';
|
||||
|
||||
export interface ChannelDeleteState {
|
||||
/** Must be rendered by the caller for the confirmation to appear. */
|
||||
contextHolder: ReactNode;
|
||||
request: (channel: Channel) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleting a channel goes through the shared destructive confirmation, the same
|
||||
* one dashboards and saved views use, so the wording and the danger button match.
|
||||
*/
|
||||
export function useChannelDelete(onDeleted?: () => void): ChannelDeleteState {
|
||||
const queryClient = useQueryClient();
|
||||
const { showErrorModal } = useErrorModal();
|
||||
const { contextHolder, confirmDelete } = useDeleteConfirm();
|
||||
const { mutateAsync } = useDeleteNotificationChannel();
|
||||
|
||||
const request = (channel: Channel): void => {
|
||||
confirmDelete({
|
||||
title: (
|
||||
<Typography.Title level={5}>
|
||||
Are you sure you want to delete the {channel.displayName} channel?
|
||||
</Typography.Title>
|
||||
),
|
||||
// Alert rules and routing policies reference a channel by name, so a
|
||||
// delete can silence them.
|
||||
content:
|
||||
'Alert rules and routing policies that notify this channel will stop reaching it.',
|
||||
// Returning the promise keeps Delete loading until the request settles.
|
||||
onConfirm: async (): Promise<void> => {
|
||||
try {
|
||||
await mutateAsync({ pathParams: { id: channel.id } });
|
||||
await invalidateListNotificationChannels(queryClient);
|
||||
onDeleted?.();
|
||||
} catch (error) {
|
||||
showErrorModal(error as APIError);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return { contextHolder, request };
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { generatePath } from 'react-router-dom';
|
||||
import ROUTES from 'constants/routes';
|
||||
import history from 'lib/history';
|
||||
import { openInNewTab } from 'utils/navigation';
|
||||
|
||||
export interface ChannelFormView {
|
||||
openCreate: () => void;
|
||||
openEdit: (channelId: string, options?: { newTab?: boolean }) => void;
|
||||
}
|
||||
|
||||
/** Create and edit both render on their own route. */
|
||||
export function useChannelFormView(): ChannelFormView {
|
||||
const openEdit = (channelId: string, options?: { newTab?: boolean }): void => {
|
||||
const path = generatePath(ROUTES.CHANNELS_EDIT, { channelId });
|
||||
|
||||
if (options?.newTab) {
|
||||
openInNewTab(path);
|
||||
return;
|
||||
}
|
||||
|
||||
history.push(path);
|
||||
};
|
||||
|
||||
return {
|
||||
openCreate: (): void => history.push(ROUTES.CHANNELS_NEW),
|
||||
openEdit,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { useListNotificationChannels } from 'api/generated/services/channels';
|
||||
import {
|
||||
AlertmanagertypesChannelKindDTO,
|
||||
AlertmanagertypesChannelListOrderDTO,
|
||||
AlertmanagertypesChannelListSortDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { SortState } from 'components/TanStackTableView';
|
||||
|
||||
import { KIND_FILTER_ALL } from '../constants';
|
||||
import type { Channel } from '../types';
|
||||
|
||||
/** Table column ids the list API can order by. */
|
||||
const SORT_BY_COLUMN: Record<string, AlertmanagertypesChannelListSortDTO> = {
|
||||
name: AlertmanagertypesChannelListSortDTO.name,
|
||||
createdAt: AlertmanagertypesChannelListSortDTO.created_at,
|
||||
updatedAt: AlertmanagertypesChannelListSortDTO.updated_at,
|
||||
};
|
||||
|
||||
interface UseChannelsDataArgs {
|
||||
search: string;
|
||||
kind: string;
|
||||
orderBy: SortState | null;
|
||||
page: number;
|
||||
limit: number;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export interface ChannelsData {
|
||||
channels: Channel[];
|
||||
total: number;
|
||||
isFetching: boolean;
|
||||
isError: boolean;
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search, kind filter, sort and paging all run on the API, so the table shows
|
||||
* one page at a time rather than filtering a full download in the browser.
|
||||
*/
|
||||
export function useChannelsData({
|
||||
search,
|
||||
kind,
|
||||
orderBy,
|
||||
page,
|
||||
limit,
|
||||
enabled = true,
|
||||
}: UseChannelsDataArgs): ChannelsData {
|
||||
const sort = orderBy ? SORT_BY_COLUMN[orderBy.columnName] : undefined;
|
||||
|
||||
const { data, isFetching, isError, refetch } = useListNotificationChannels(
|
||||
{
|
||||
limit,
|
||||
offset: (page - 1) * limit,
|
||||
...(sort
|
||||
? {
|
||||
sort,
|
||||
order: orderBy?.order as AlertmanagertypesChannelListOrderDTO,
|
||||
}
|
||||
: {}),
|
||||
...(search ? { query: search } : {}),
|
||||
...(kind !== KIND_FILTER_ALL
|
||||
? { kind: kind as AlertmanagertypesChannelKindDTO }
|
||||
: {}),
|
||||
},
|
||||
{ query: { enabled, keepPreviousData: true } },
|
||||
);
|
||||
|
||||
return {
|
||||
channels: data?.data?.channels ?? [],
|
||||
total: data?.data?.total ?? 0,
|
||||
isFetching,
|
||||
isError,
|
||||
refetch,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { TableColumnDef } from 'components/TanStackTableView';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
|
||||
|
||||
import { CHANNEL_KIND_LABEL } from './constants';
|
||||
import styles from './table.module.scss';
|
||||
import type { Channel } from './types';
|
||||
import { toRelativeTime } from './utils/relativeTime';
|
||||
|
||||
export function getChannelColumns(
|
||||
formatTimezoneAdjustedTimestamp: (date: string, format: string) => string,
|
||||
): TableColumnDef<Channel>[] {
|
||||
const timestampCell = (row: Channel, value: string): JSX.Element => {
|
||||
if (!value) {
|
||||
return <TanStackTable.Text>-</TanStackTable.Text>;
|
||||
}
|
||||
|
||||
return (
|
||||
<TanStackTable.HoverTooltip
|
||||
rowId={row.id}
|
||||
title={formatTimezoneAdjustedTimestamp(
|
||||
value,
|
||||
DATE_TIME_FORMATS.DASH_DATETIME,
|
||||
)}
|
||||
>
|
||||
{/* A plain inline-block hugs the text. TanStackTable.Text is a
|
||||
`-webkit-box` for line clamping, which fills the cell and leaves
|
||||
the arrow pointing at the cell's middle instead of the words. */}
|
||||
<span className={styles.timeText}>{toRelativeTime(value)}</span>
|
||||
</TanStackTable.HoverTooltip>
|
||||
);
|
||||
};
|
||||
|
||||
return [
|
||||
{
|
||||
id: 'name',
|
||||
header: 'Channel',
|
||||
accessorKey: 'displayName',
|
||||
width: { default: '100%', min: '220px' },
|
||||
enableSort: true,
|
||||
enableResize: true,
|
||||
enableRemove: false,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => (
|
||||
<TanStackTable.Text
|
||||
title={row.displayName}
|
||||
data-testid={`channel-row-${row.id}-name`}
|
||||
>
|
||||
{row.displayName}
|
||||
</TanStackTable.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'kind',
|
||||
header: 'Type',
|
||||
accessorKey: 'kind',
|
||||
width: { default: '150px', min: '110px' },
|
||||
enableSort: false,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => (
|
||||
<TanStackTable.Text data-testid={`channel-row-${row.id}-kind`}>
|
||||
{CHANNEL_KIND_LABEL[row.kind]}
|
||||
</TanStackTable.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'createdAt',
|
||||
header: 'Created At',
|
||||
accessorKey: 'createdAt',
|
||||
width: { default: '150px', min: '120px' },
|
||||
enableSort: true,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => timestampCell(row, row.createdAt),
|
||||
},
|
||||
{
|
||||
id: 'updatedAt',
|
||||
header: 'Updated At',
|
||||
accessorKey: 'updatedAt',
|
||||
width: { default: '150px', min: '120px' },
|
||||
enableSort: true,
|
||||
enableResize: true,
|
||||
enableMove: false,
|
||||
cell: ({ row }): JSX.Element => timestampCell(row, row.updatedAt),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
.timeText {
|
||||
display: inline-block;
|
||||
white-space: nowrap;
|
||||
font-size: var(--tanstack-plain-cell-font-size, 14px);
|
||||
line-height: var(--tanstack-plain-cell-line-height, 18px);
|
||||
color: inherit;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { AlertmanagertypesListedNotificationChannelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
/** A channel as the list API returns it: identity and kind, but no config. */
|
||||
export type Channel = AlertmanagertypesListedNotificationChannelDTO;
|
||||
@@ -0,0 +1,50 @@
|
||||
import { AlertmanagertypesGettableNotificationChannelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
export const SECRET_PLACEHOLDER = '••••••••';
|
||||
|
||||
/**
|
||||
* The spec fields the API marks `format: password`. A fetch by ID returns them
|
||||
* in the clear, so the JSON view hides them until asked.
|
||||
*/
|
||||
const SECRET_FIELDS_BY_KIND: Record<string, readonly string[]> = {
|
||||
slack: ['apiUrl'],
|
||||
webhook: ['url', 'password', 'bearerToken'],
|
||||
pagerduty: ['routingKey'],
|
||||
opsgenie: ['apiKey'],
|
||||
msteams: ['webhookUrl'],
|
||||
googlechat: ['webhookUrl'],
|
||||
jira: ['apiToken'],
|
||||
jsmops: ['apiKey'],
|
||||
incidentio: ['token'],
|
||||
};
|
||||
|
||||
export function channelToJson(
|
||||
channel: AlertmanagertypesGettableNotificationChannelDTO,
|
||||
showSecrets: boolean,
|
||||
): string {
|
||||
const { kind, spec } = channel.config;
|
||||
const secrets = SECRET_FIELDS_BY_KIND[kind] ?? [];
|
||||
|
||||
const safeSpec = showSecrets
|
||||
? spec
|
||||
: Object.fromEntries(
|
||||
Object.entries(spec).map(([key, value]) => [
|
||||
key,
|
||||
secrets.includes(key) && value ? SECRET_PLACEHOLDER : value,
|
||||
]),
|
||||
);
|
||||
|
||||
return JSON.stringify(
|
||||
{
|
||||
name: channel.name,
|
||||
displayName: channel.displayName,
|
||||
config: { kind, spec: safeSpec },
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
}
|
||||
|
||||
export function hasSecrets(kind: string): boolean {
|
||||
return (SECRET_FIELDS_BY_KIND[kind] ?? []).length > 0;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import dayjs from 'dayjs';
|
||||
import relativeTimePlugin from 'dayjs/plugin/relativeTime';
|
||||
|
||||
dayjs.extend(relativeTimePlugin);
|
||||
|
||||
/** "2 months ago". The exact timestamp stays available on hover. */
|
||||
export function toRelativeTime(value: string | undefined): string {
|
||||
const parsed = value ? dayjs(value) : null;
|
||||
return parsed?.isValid() ? parsed.fromNow() : '-';
|
||||
}
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
import {
|
||||
CHANNEL_MAX,
|
||||
channelNames,
|
||||
channelsResponse,
|
||||
notificationChannelsResponse,
|
||||
} from '../../stories/__story_mockdata__/alerts';
|
||||
import { AlertListSubTabs, AlertListTabs } from '../../types';
|
||||
|
||||
@@ -118,10 +118,10 @@ export const routingPoliciesMocks = defineStoryMocks({
|
||||
: res(ctx.status(200), ctx.json({ status: 'success', data: null })),
|
||||
),
|
||||
|
||||
rest.get('http://localhost/api/v1/channels', (_req, res, ctx) =>
|
||||
rest.get('http://localhost/api/v2/notification_channels', (_req, res, ctx) =>
|
||||
values.channelsState === 'error'
|
||||
? res(ctx.status(500), ctx.json({ status: 'error' }))
|
||||
: res(ctx.json(channelsResponse(values.channels))),
|
||||
: res(ctx.json(notificationChannelsResponse(values.channels))),
|
||||
),
|
||||
],
|
||||
config: () => ({
|
||||
|
||||
@@ -4,7 +4,6 @@ import { Tabs, TabsProps } from 'antd';
|
||||
import ConfigureIcon from 'assets/AlertHistory/ConfigureIcon';
|
||||
import HeaderRightSection from 'components/HeaderRightSection/HeaderRightSection';
|
||||
import ROUTES from 'constants/routes';
|
||||
import AllAlertChannels from 'container/AllAlertChannels';
|
||||
import AllAlertRules from 'container/ListAlertRules';
|
||||
import { PlannedDowntime } from 'container/PlannedDowntime/PlannedDowntime';
|
||||
import RoutingPolicies from 'container/RoutingPolicies';
|
||||
@@ -16,6 +15,8 @@ import AlertDetails from 'pages/AlertDetails';
|
||||
import ChannelsEdit from 'pages/ChannelsEdit';
|
||||
import ChannelsNew from 'pages/ChannelsNew';
|
||||
|
||||
import NotificationChannels from './NotificationChannels/NotificationChannels';
|
||||
|
||||
import { AlertListSubTabs, AlertListTabs } from './types';
|
||||
|
||||
import './AlertList.styles.scss';
|
||||
@@ -104,7 +105,7 @@ function AllAlertList(): JSX.Element {
|
||||
<div className="alert-rules-container">
|
||||
{isChannelsNew && <ChannelsNew />}
|
||||
{isChannelsEdit && <ChannelsEdit />}
|
||||
{!isChannelDetails && <AllAlertChannels />}
|
||||
{!isChannelDetails && <NotificationChannels />}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
|
||||
@@ -26,6 +26,9 @@ import {
|
||||
type RuletypesAlertCompositeQueryDTO,
|
||||
type RuletypesRuleConditionDTO,
|
||||
type RuletypesRuleDTO,
|
||||
type AlertmanagertypesChannelConfigDTO,
|
||||
type AlertmanagertypesGettableNotificationChannelDTO,
|
||||
type AlertmanagertypesListedNotificationChannelDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { NEW_ALERT_SCHEMA_VERSION } from 'types/api/alerts/alertTypesV2';
|
||||
import type { Channels } from 'types/api/channels/getAll';
|
||||
@@ -704,6 +707,22 @@ const buildChannel = (index: number): Channels => {
|
||||
};
|
||||
};
|
||||
|
||||
const buildListedChannel = (
|
||||
index: number,
|
||||
): AlertmanagertypesListedNotificationChannelDTO => {
|
||||
const seed = CHANNEL_SEEDS[index % CHANNEL_SEEDS.length];
|
||||
|
||||
return {
|
||||
id: String(index + 1),
|
||||
name: seed.name,
|
||||
displayName: seed.name,
|
||||
kind: seed.type as AlertmanagertypesListedNotificationChannelDTO['kind'],
|
||||
createdAt: ago((index + 10) * DAY),
|
||||
updatedAt: ago((index + 1) * DAY),
|
||||
};
|
||||
};
|
||||
|
||||
/** The v2 list, which is what the channel pickers read. */
|
||||
export const channelsResponse = (
|
||||
count: number,
|
||||
): { status: string; data: Channels[] } => ({
|
||||
@@ -711,10 +730,97 @@ export const channelsResponse = (
|
||||
data: Array.from({ length: count }, (_unused, index) => buildChannel(index)),
|
||||
});
|
||||
|
||||
/** The v2 list, which is what the redesigned channels list reads. */
|
||||
export const notificationChannelsResponse = (
|
||||
count: number,
|
||||
): {
|
||||
status: string;
|
||||
data: {
|
||||
channels: AlertmanagertypesListedNotificationChannelDTO[];
|
||||
total: number;
|
||||
};
|
||||
} => {
|
||||
const channels = Array.from({ length: count }, (_unused, index) =>
|
||||
buildListedChannel(index),
|
||||
);
|
||||
|
||||
return { status: 'success', data: { channels, total: channels.length } };
|
||||
};
|
||||
|
||||
/** Channel names the alert form and the routing policies pick from. */
|
||||
export const channelNames = (count: number): string[] =>
|
||||
channelsResponse(count).data.map((channel) => channel.name);
|
||||
|
||||
/**
|
||||
* The v2 spec each kind is fetched with, so the edit form renders populated
|
||||
* fields. Keys mirror the generated channel spec schemas.
|
||||
*/
|
||||
const CHANNEL_SPECS: Record<ChannelType, Record<string, unknown>> = {
|
||||
slack: {
|
||||
apiUrl: 'https://hooks.slack.com/services/T000/B000/story-token',
|
||||
channel: '#ops-alerts',
|
||||
title: '[{{ .Status | toUpper }}] {{ .CommonLabels.alertname }}',
|
||||
text: '{{ range .Alerts -}}*Alert:* {{ .Labels.alertname }}\n{{ end }}',
|
||||
sendResolved: true,
|
||||
},
|
||||
webhook: {
|
||||
url: 'https://example.com/story-hook',
|
||||
username: 'story-user',
|
||||
sendResolved: true,
|
||||
},
|
||||
pagerduty: {
|
||||
routingKey: 'story-routing-key',
|
||||
description: '{{ .CommonLabels.alertname }}',
|
||||
severity: 'critical',
|
||||
sendResolved: true,
|
||||
},
|
||||
opsgenie: {
|
||||
apiKey: 'story-opsgenie-key',
|
||||
message: '{{ .CommonLabels.alertname }}',
|
||||
description: 'Story channel',
|
||||
sendResolved: true,
|
||||
},
|
||||
email: {
|
||||
to: 'oncall@story.signoz.io',
|
||||
html: '<p>{{ .CommonLabels.alertname }}</p>',
|
||||
sendResolved: true,
|
||||
},
|
||||
msteams: {
|
||||
webhookUrl: 'https://story.webhook.office.com/webhookb2/story',
|
||||
title: '[{{ .Status | toUpper }}] {{ .CommonLabels.alertname }}',
|
||||
text: 'Story channel',
|
||||
sendResolved: true,
|
||||
},
|
||||
googlechat: {
|
||||
webhookUrl: 'https://chat.googleapis.com/v1/spaces/STORY/messages',
|
||||
title: '[{{ .Status | toUpper }}] {{ .CommonLabels.alertname }}',
|
||||
text: 'Story channel',
|
||||
sendResolved: true,
|
||||
},
|
||||
jira: {
|
||||
site: 'https://story.atlassian.net',
|
||||
project: 'OPS',
|
||||
issueType: 'Task',
|
||||
email: 'story@signoz.io',
|
||||
apiToken: 'story-jira-token',
|
||||
summary: '{{ .CommonLabels.alertname }}',
|
||||
sendResolved: true,
|
||||
},
|
||||
jsmops: {
|
||||
apiKey: 'story-jsm-key',
|
||||
message: '{{ .CommonLabels.alertname }}',
|
||||
description: 'Story channel',
|
||||
sendResolved: true,
|
||||
},
|
||||
incidentio: {
|
||||
url: 'https://api.incident.io/v2/alert_events/http/story',
|
||||
token: 'story-incidentio-token',
|
||||
title: '{{ .CommonLabels.alertname }}',
|
||||
sendResolved: true,
|
||||
},
|
||||
};
|
||||
|
||||
/** A single channel as the v2 API returns it, which the edit screen reads. */
|
||||
export const channelResponse = (
|
||||
id: string,
|
||||
type: ChannelType,
|
||||
@@ -727,6 +833,36 @@ export const channelResponse = (
|
||||
};
|
||||
};
|
||||
|
||||
/** The v2 fetch by id, which is what the redesigned screens read. */
|
||||
export const notificationChannelResponse = (
|
||||
id: string,
|
||||
type: ChannelType,
|
||||
): {
|
||||
status: string;
|
||||
data: AlertmanagertypesGettableNotificationChannelDTO;
|
||||
} => {
|
||||
const index = Math.max(
|
||||
CHANNEL_SEEDS.findIndex((seed) => seed.type === type),
|
||||
0,
|
||||
);
|
||||
const seed = CHANNEL_SEEDS[index];
|
||||
|
||||
return {
|
||||
status: 'success',
|
||||
data: {
|
||||
id,
|
||||
name: seed.name,
|
||||
displayName: seed.name,
|
||||
createdAt: ago((index + 10) * DAY),
|
||||
updatedAt: ago((index + 1) * DAY),
|
||||
config: {
|
||||
kind: type,
|
||||
spec: CHANNEL_SPECS[type],
|
||||
} as unknown as AlertmanagertypesChannelConfigDTO,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const CHANNEL_ACTION_OUTCOMES = ['succeeds', 'fails'] as const;
|
||||
|
||||
export type ChannelActionOutcome = (typeof CHANNEL_ACTION_OUTCOMES)[number];
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
alertPreviewSeries,
|
||||
} from '../../AlertList/stories/__story_mockdata__/alertQuery';
|
||||
import {
|
||||
channelsResponse,
|
||||
notificationChannelsResponse,
|
||||
CHANNEL_MAX,
|
||||
} from '../../AlertList/stories/__story_mockdata__/alerts';
|
||||
|
||||
@@ -127,8 +127,8 @@ export const createAlertMocks = defineStoryMocks({
|
||||
),
|
||||
|
||||
rest.get(
|
||||
'http://localhost/api/v1/channels',
|
||||
response.json(() => channelsResponse(values.channels)),
|
||||
'http://localhost/api/v2/notification_channels',
|
||||
response.json(() => notificationChannelsResponse(values.channels)),
|
||||
),
|
||||
|
||||
rest.post(
|
||||
|
||||
@@ -12,7 +12,10 @@ import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';
|
||||
import { useCopyToClipboard } from 'react-use';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
|
||||
import { defineJsonEditorTheme, JSON_EDITOR_THEME } from './editorTheme';
|
||||
import {
|
||||
defineJsonEditorTheme,
|
||||
JSON_EDITOR_THEME,
|
||||
} from 'lib/monaco/jsonEditorTheme';
|
||||
import styles from './JsonEditorDrawer.module.scss';
|
||||
import JsonEditorToolbar from './JsonEditorToolbar';
|
||||
import { useJsonEditor } from './useJsonEditor';
|
||||
|
||||
@@ -217,6 +217,8 @@ function ListPanelRenderer({
|
||||
log={logDetail.activeLog}
|
||||
selectedTab={logDetail.selectedTab}
|
||||
onClose={logDetail.onClose}
|
||||
onAddToQuery={logDetail.onAddToQuery}
|
||||
onClickActionItem={logDetail.onAddToQuery}
|
||||
onNavigateLog={logDetail.onNavigateLog}
|
||||
logs={logDetail.logs}
|
||||
isListViewPanel
|
||||
|
||||
@@ -18,6 +18,7 @@ export interface ListLogDetail {
|
||||
selectedTab: VIEWS;
|
||||
logs: ILog[];
|
||||
onClose: () => void;
|
||||
onAddToQuery: ReturnType<typeof useLogDetailHandlers>['onAddToQuery'];
|
||||
onNavigateLog: (log: ILog) => void;
|
||||
}
|
||||
|
||||
@@ -48,8 +49,13 @@ export function useListRowInteraction({
|
||||
const isLogs = signal === TelemetrytypesSignalDTO.logs;
|
||||
const isTraces = signal === TelemetrytypesSignalDTO.traces;
|
||||
|
||||
const { activeLog, selectedTab, handleSetActiveLog, handleCloseLogDetail } =
|
||||
useLogDetailHandlers();
|
||||
const {
|
||||
activeLog,
|
||||
onAddToQuery,
|
||||
selectedTab,
|
||||
handleSetActiveLog,
|
||||
handleCloseLogDetail,
|
||||
} = useLogDetailHandlers();
|
||||
|
||||
const logs = useMemo(
|
||||
() => (isLogs ? rows.map(rawRowToILog) : []),
|
||||
@@ -84,6 +90,7 @@ export function useListRowInteraction({
|
||||
selectedTab: selectedTab ?? VIEW_TYPES.OVERVIEW,
|
||||
logs,
|
||||
onClose: handleCloseLogDetail,
|
||||
onAddToQuery,
|
||||
onNavigateLog: handleSetActiveLog,
|
||||
}
|
||||
: null,
|
||||
@@ -93,6 +100,7 @@ export function useListRowInteraction({
|
||||
selectedTab,
|
||||
logs,
|
||||
handleCloseLogDetail,
|
||||
onAddToQuery,
|
||||
handleSetActiveLog,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
import {
|
||||
alertRuleByIdResponse,
|
||||
ALERT_SCHEMAS,
|
||||
channelsResponse,
|
||||
notificationChannelsResponse,
|
||||
CHANNEL_MAX,
|
||||
type AlertSchema,
|
||||
} from '../../AlertList/stories/__story_mockdata__/alerts';
|
||||
@@ -77,8 +77,8 @@ export const editRulesMocks = defineStoryMocks({
|
||||
),
|
||||
|
||||
rest.get(
|
||||
'http://localhost/api/v1/channels',
|
||||
response.json(() => channelsResponse(values.channels)),
|
||||
'http://localhost/api/v2/notification_channels',
|
||||
response.json(() => notificationChannelsResponse(values.channels)),
|
||||
),
|
||||
|
||||
rest.post(
|
||||
|
||||
@@ -71,20 +71,6 @@ func (provider *provider) addRulerRoutes(router *mux.Router) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/rules/{id}/clone", handler.New(provider.authzMiddleware.EditAccess(provider.rulerHandler.CloneRuleByID), handler.OpenAPIDef{
|
||||
ID: "CloneRuleByID",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Clone alert rule",
|
||||
Description: "This endpoint creates a new alert rule from the stored definition of an existing one. The clone keeps every modeled field of the source, including its enabled/disabled state, and gets the source's name suffixed with \" - Copy\" (or a bumped \" - Copy (n)\" counter when the source is itself a copy). The clone is owned by the caller.",
|
||||
Response: new(ruletypes.Rule),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusCreated,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleEditor),
|
||||
})).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/rules/{id}", handler.New(provider.authzMiddleware.EditAccess(provider.rulerHandler.UpdateRuleByID), handler.OpenAPIDef{
|
||||
ID: "UpdateRuleByID",
|
||||
Tags: []string{"rules"},
|
||||
|
||||
@@ -159,7 +159,7 @@ func NewBaseRule(
|
||||
id: id,
|
||||
orgID: orgID,
|
||||
externalURL: externalURL,
|
||||
name: p.AlertName.StringValue(),
|
||||
name: p.AlertName,
|
||||
typ: p.AlertType,
|
||||
ruleCondition: p.RuleCondition,
|
||||
evalWindow: p.EvalWindow,
|
||||
|
||||
@@ -126,7 +126,7 @@ func mergeFirstSeenMaps(maps ...map[telemetrytypes.MetricMetadataLookupKey]int64
|
||||
// createPostableRule creates a PostableRule with the given CompositeQuery
|
||||
func createPostableRule(compositeQuery *ruletypes.AlertCompositeQuery) ruletypes.PostableRule {
|
||||
return ruletypes.PostableRule{
|
||||
AlertName: valuer.NewDisplayName("Test Rule"),
|
||||
AlertName: "Test Rule",
|
||||
AlertType: ruletypes.AlertTypeMetric,
|
||||
RuleType: ruletypes.RuleTypeThreshold,
|
||||
Evaluation: &ruletypes.EvaluationEnvelope{
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user