Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Edit alert flyout #58964

Merged
merged 17 commits into from
Mar 4, 2020
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ const DEFAULT_VALUES = {
THRESHOLD_COMPARATOR: COMPARATORS.GREATER_THAN,
TIME_WINDOW_SIZE: 5,
TIME_WINDOW_UNIT: 'm',
TRIGGER_INTERVAL_SIZE: 1,
TRIGGER_INTERVAL_UNIT: 'm',
THRESHOLD: [1000, 5000],
GROUP_BY: 'all',
};
Expand Down Expand Up @@ -136,14 +134,14 @@ export const IndexThresholdAlertTypeExpression: React.FunctionComponent<IndexThr

const setDefaultExpressionValues = () => {
setAlertProperty('params', {
aggType: DEFAULT_VALUES.AGGREGATION_TYPE,
termSize: DEFAULT_VALUES.TERM_SIZE,
thresholdComparator: DEFAULT_VALUES.THRESHOLD_COMPARATOR,
timeWindowSize: DEFAULT_VALUES.TIME_WINDOW_SIZE,
timeWindowUnit: DEFAULT_VALUES.TIME_WINDOW_UNIT,
triggerIntervalUnit: DEFAULT_VALUES.TRIGGER_INTERVAL_UNIT,
groupBy: DEFAULT_VALUES.GROUP_BY,
threshold: DEFAULT_VALUES.THRESHOLD,
...alertParams,
aggType: aggType ?? DEFAULT_VALUES.AGGREGATION_TYPE,
termSize: termSize ?? DEFAULT_VALUES.TERM_SIZE,
thresholdComparator: thresholdComparator ?? DEFAULT_VALUES.THRESHOLD_COMPARATOR,
timeWindowSize: timeWindowSize ?? DEFAULT_VALUES.TIME_WINDOW_SIZE,
timeWindowUnit: timeWindowUnit ?? DEFAULT_VALUES.TIME_WINDOW_UNIT,
groupBy: groupBy ?? DEFAULT_VALUES.GROUP_BY,
threshold: threshold ?? DEFAULT_VALUES.THRESHOLD,
});
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { builtInGroupByTypes, builtInAggregationTypes } from '../../../../common

export function getAlertType(): AlertTypeModel {
return {
id: 'threshold',
id: '.index-threshold',
name: 'Index Threshold',
iconClass: 'alert',
alertParamsExpression: IndexThresholdAlertTypeExpression,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ import { TypeRegistry } from '../type_registry';
import { AlertTypeModel, ActionTypeModel } from '../../types';

export interface AlertsContextValue {
addFlyoutVisible: boolean;
setAddFlyoutVisibility: React.Dispatch<React.SetStateAction<boolean>>;
reloadAlerts?: () => Promise<void>;
http: HttpSetup;
alertTypeRegistry: TypeRegistry<AlertTypeModel>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ describe('updateAlert', () => {
Array [
"/api/alert/123",
Object {
"body": "{\\"throttle\\":\\"1m\\",\\"consumer\\":\\"alerting\\",\\"name\\":\\"test\\",\\"tags\\":[\\"foo\\"],\\"schedule\\":{\\"interval\\":\\"1m\\"},\\"params\\":{},\\"actions\\":[],\\"createdAt\\":\\"1970-01-01T00:00:00.000Z\\",\\"updatedAt\\":\\"1970-01-01T00:00:00.000Z\\",\\"apiKey\\":null,\\"apiKeyOwner\\":null}",
"body": "{\\"throttle\\":\\"1m\\",\\"name\\":\\"test\\",\\"tags\\":[\\"foo\\"],\\"schedule\\":{\\"interval\\":\\"1m\\"},\\"params\\":{},\\"actions\\":[]}",
},
]
`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,14 @@ export async function updateAlert({
id: string;
}): Promise<Alert> {
return await http.put(`${BASE_ALERT_API_PATH}/${id}`, {
body: JSON.stringify(alert),
body: JSON.stringify({
throttle: alert.throttle,
name: alert.name,
tags: alert.tags,
schedule: alert.schedule,
params: alert.params,
actions: alert.actions,
}),
YulNaumenko marked this conversation as resolved.
Show resolved Hide resolved
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,6 @@ describe('alert_add', () => {
wrapper = mountWithIntl(
<AlertsContextProvider
value={{
addFlyoutVisible: true,
setAddFlyoutVisibility: state => {},
reloadAlerts: () => {
return new Promise<void>(() => {});
},
Expand All @@ -102,7 +100,11 @@ describe('alert_add', () => {
uiSettings: deps.uiSettings,
}}
>
<AlertAdd consumer={'alerting'} />
<AlertAdd
consumer={'alerting'}
addFlyoutVisible={true}
setAddFlyoutVisibility={state => {}}
/>
</AlertsContextProvider>
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,19 @@ import { createAlert } from '../../lib/alert_api';

interface AlertAddProps {
consumer: string;
addFlyoutVisible: boolean;
setAddFlyoutVisibility: React.Dispatch<React.SetStateAction<boolean>>;
alertTypeId?: string;
canChangeTrigger?: boolean;
}

export const AlertAdd = ({ consumer, canChangeTrigger, alertTypeId }: AlertAddProps) => {
export const AlertAdd = ({
consumer,
addFlyoutVisible,
setAddFlyoutVisibility,
canChangeTrigger,
alertTypeId,
}: AlertAddProps) => {
const initialAlert = ({
params: {},
consumer,
Expand All @@ -51,8 +59,6 @@ export const AlertAdd = ({ consumer, canChangeTrigger, alertTypeId }: AlertAddPr
};

const {
addFlyoutVisible,
setAddFlyoutVisibility,
reloadAlerts,
http,
toastNotifications,
Expand Down Expand Up @@ -106,7 +112,7 @@ export const AlertAdd = ({ consumer, canChangeTrigger, alertTypeId }: AlertAddPr
const newAlert = await createAlert({ http, alert });
if (toastNotifications) {
toastNotifications.addSuccess(
i18n.translate('xpack.triggersActionsUI.sections.alertForm.saveSuccessNotificationText', {
i18n.translate('xpack.triggersActionsUI.sections.alertAdd.saveSuccessNotificationText', {
defaultMessage: "Saved '{alertName}'",
values: {
alertName: newAlert.name,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import * as React from 'react';
import { mountWithIntl } from 'test_utils/enzyme_helpers';
import { act } from 'react-dom/test-utils';
import { coreMock } from '../../../../../../../src/core/public/mocks';
import { actionTypeRegistryMock } from '../../action_type_registry.mock';
import { ValidationResult } from '../../../types';
import { AppDeps } from '../../app';
import { AlertsContextProvider } from '../../context/alerts_context';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { chartPluginMock } from '../../../../../../../src/plugins/charts/public/mocks';
import { dataPluginMock } from '../../../../../../../src/plugins/data/public/mocks';
import { ReactWrapper } from 'enzyme';
import { AlertEdit } from './alert_edit';
const actionTypeRegistry = actionTypeRegistryMock.create();
const alertTypeRegistry = alertTypeRegistryMock.create();

describe('alert_edit', () => {
let deps: AppDeps | null;
let wrapper: ReactWrapper<any>;

beforeAll(async () => {
const mockes = coreMock.createSetup();
const [
{
chrome,
docLinks,
application: { capabilities },
},
] = await mockes.getStartServices();
deps = {
chrome,
docLinks,
toastNotifications: mockes.notifications.toasts,
injectedMetadata: mockes.injectedMetadata,
http: mockes.http,
uiSettings: mockes.uiSettings,
dataPlugin: dataPluginMock.createStartContract(),
charts: chartPluginMock.createStartContract(),
capabilities: {
...capabilities,
alerting: {
delete: true,
save: true,
show: true,
},
},
setBreadcrumbs: jest.fn(),
actionTypeRegistry: actionTypeRegistry as any,
alertTypeRegistry: alertTypeRegistry as any,
};
YulNaumenko marked this conversation as resolved.
Show resolved Hide resolved
const alertType = {
id: 'my-alert-type',
iconClass: 'test',
name: 'test-alert',
validate: (): ValidationResult => {
return { errors: {} };
},
alertParamsExpression: () => <React.Fragment />,
};

const actionTypeModel = {
id: 'my-action-type',
iconClass: 'test',
selectMessage: 'test',
validateConnector: (): ValidationResult => {
return { errors: {} };
},
validateParams: (): ValidationResult => {
const validationResult = { errors: {} };
return validationResult;
},
actionConnectorFields: null,
actionParamsFields: null,
};

const alert = {
id: 'ab5661e0-197e-45ee-b477-302d89193b5e',
params: {
aggType: 'average',
threshold: [1000, 5000],
index: 'kibana_sample_data_flights',
timeField: 'timestamp',
aggField: 'DistanceMiles',
window: '1s',
comparator: 'between',
},
consumer: 'alerting',
alertTypeId: 'my-alert-type',
enabled: false,
schedule: { interval: '1m' },
actions: [
{
actionTypeId: 'my-action-type',
group: 'threshold met',
params: { message: 'Alert [{{ctx.metadata.name}}] has exceeded the threshold' },
message: 'Alert [{{ctx.metadata.name}}] has exceeded the threshold',
id: '917f5d41-fbc4-4056-a8ad-ac592f7dcee2',
},
],
tags: [],
name: 'Serhii',
YulNaumenko marked this conversation as resolved.
Show resolved Hide resolved
throttle: null,
apiKeyOwner: null,
createdBy: 'elastic',
updatedBy: 'elastic',
createdAt: new Date(),
muteAll: false,
mutedInstanceIds: [],
updatedAt: new Date(),
};
actionTypeRegistry.get.mockReturnValueOnce(actionTypeModel);
actionTypeRegistry.has.mockReturnValue(true);
alertTypeRegistry.list.mockReturnValue([alertType]);
alertTypeRegistry.get.mockReturnValue(alertType);
alertTypeRegistry.has.mockReturnValue(true);
actionTypeRegistry.list.mockReturnValue([actionTypeModel]);
actionTypeRegistry.has.mockReturnValue(true);

await act(async () => {
wrapper = mountWithIntl(
<AlertsContextProvider
value={{
reloadAlerts: () => {
return new Promise<void>(() => {});
},
http: deps!.http,
actionTypeRegistry: deps!.actionTypeRegistry,
alertTypeRegistry: deps!.alertTypeRegistry,
toastNotifications: deps!.toastNotifications,
uiSettings: deps!.uiSettings,
}}
>
<AlertEdit
editFlyoutVisible={true}
setEditFlyoutVisibility={state => {}}
initialAlert={alert}
/>
</AlertsContextProvider>
);
});
await waitForRender(wrapper);
});

it('renders alert add flyout', () => {
expect(wrapper.find('[data-test-subj="editAlertFlyoutTitle"]').exists()).toBeTruthy();
expect(wrapper.find('[data-test-subj="saveEditedAlertButton"]').exists()).toBeTruthy();
});
});

async function waitForRender(wrapper: ReactWrapper<any, any>) {
await Promise.resolve();
await Promise.resolve();
wrapper.update();
YulNaumenko marked this conversation as resolved.
Show resolved Hide resolved
}
Loading