Skip to content

Commit

Permalink
feat(rca): create and edit investigation form in flyout (elastic#192208)
Browse files Browse the repository at this point in the history
  • Loading branch information
kdelemme authored Sep 10, 2024
1 parent 4cd23a1 commit 6ef9f6c
Show file tree
Hide file tree
Showing 13 changed files with 467 additions and 177 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
"esql",
"kibanaReact",
"kibanaUtils",
"esqlDataGrid",
],
"optionalPlugins": [],
"extraPublicDirs": []
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { EuiIcon, EuiFormRow, EuiComboBox } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import React from 'react';
import { Controller, useFormContext } from 'react-hook-form';
import { InvestigationForm } from '../investigation_edit_form';

const I18N_STATUS_LABEL = i18n.translate(
'xpack.investigateApp.investigationEditForm.span.statusLabel',
{ defaultMessage: 'Status' }
);

const options = [
{
label: 'Ongoing',
value: 'ongoing',
prepend: <EuiIcon size="s" type="dot" color="danger" />,
},
{
label: 'Closed',
value: 'closed',
prepend: <EuiIcon size="s" type="dot" color="success" />,
},
];

export function StatusField() {
const { control, getFieldState } = useFormContext<InvestigationForm>();

return (
<EuiFormRow label={I18N_STATUS_LABEL} fullWidth isInvalid={getFieldState('status').invalid}>
<Controller
control={control}
name="status"
rules={{ required: true }}
render={({ field, fieldState }) => (
<EuiComboBox
{...field}
fullWidth
isInvalid={fieldState.invalid}
isClearable={false}
aria-label={I18N_STATUS_LABEL}
placeholder={I18N_STATUS_LABEL}
options={options}
selectedOptions={options.filter((option) => option.value === field.value)}
onChange={(selected) => {
return field.onChange(selected[0].value);
}}
singleSelection={{ asPlainText: true }}
/>
)}
/>
</EuiFormRow>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import {
EuiButton,
EuiButtonEmpty,
EuiFieldText,
EuiFlexGroup,
EuiFlexItem,
EuiFlyout,
EuiFlyoutBody,
EuiFlyoutFooter,
EuiFlyoutHeader,
EuiFormRow,
EuiLoadingSpinner,
EuiTitle,
} from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { pick } from 'lodash';
import React from 'react';
import { Controller, FormProvider, useForm } from 'react-hook-form';
import { v4 as uuidv4 } from 'uuid';
import { useCreateInvestigation } from '../../hooks/use_create_investigation';
import { useFetchInvestigation } from '../../hooks/use_fetch_investigation';
import { useUpdateInvestigation } from '../../hooks/use_update_investigation';
import { InvestigationNotFound } from '../investigation_not_found/investigation_not_found';
import { StatusField } from './fields/status_field';
import { useKibana } from '../../hooks/use_kibana';
import { paths } from '../../../common/paths';

export interface InvestigationForm {
title: string;
status: 'ongoing' | 'closed';
}

interface Props {
investigationId?: string;
onClose: () => void;
}

export function InvestigationEditForm({ investigationId, onClose }: Props) {
const {
core: {
http: { basePath },
application: { navigateToUrl },
},
} = useKibana();
const isEditing = Boolean(investigationId);

const {
data: investigation,
isLoading,
isError,
refetch,
} = useFetchInvestigation({ id: investigationId });

const { mutateAsync: updateInvestigation } = useUpdateInvestigation();
const { mutateAsync: createInvestigation } = useCreateInvestigation();

const methods = useForm<InvestigationForm>({
defaultValues: { title: 'New investigation', status: 'ongoing' },
values: investigation ? pick(investigation, ['title', 'status']) : undefined,
mode: 'all',
});

if (isError) {
return <InvestigationNotFound />;
}

if (isEditing && (isLoading || !investigation)) {
return <EuiLoadingSpinner size="xl" />;
}

const onSubmit = async (data: InvestigationForm) => {
if (isEditing) {
await updateInvestigation({
investigationId: investigationId!,
payload: { title: data.title, status: data.status },
});
refetch();
onClose();
} else {
const resp = await createInvestigation({
id: uuidv4(),
title: data.title,
params: {
timeRange: {
from: new Date(new Date().getTime() - 30 * 60 * 1000).getTime(),
to: new Date().getTime(),
},
},
origin: {
type: 'blank',
},
});
navigateToUrl(basePath.prepend(paths.investigationDetails(resp.id)));
}
};

return (
<FormProvider {...methods}>
<form onSubmit={methods.handleSubmit(onSubmit)}>
<EuiFlyout ownFocus onClose={() => onClose()} size="s">
<EuiFlyoutHeader hasBorder>
<EuiTitle size="m">
<h2>
{isEditing
? i18n.translate('xpack.investigateApp.investigationDetailsPage.h2.editLabel', {
defaultMessage: 'Edit',
})
: i18n.translate('xpack.investigateApp.investigationDetailsPage.h2.createLabel', {
defaultMessage: 'Create',
})}
</h2>
</EuiTitle>
</EuiFlyoutHeader>
<EuiFlyoutBody>
<EuiFlexGroup direction="column" gutterSize="l">
<EuiFlexItem grow>
<EuiFormRow
fullWidth
label={i18n.translate(
'xpack.investigateApp.investigationEditForm.span.titleLabel',
{ defaultMessage: 'Title' }
)}
isInvalid={methods.getFieldState('title').invalid}
>
<Controller
name="title"
control={methods.control}
rules={{ required: true }}
render={({ field: { ref, ...field }, fieldState }) => (
<EuiFieldText
{...field}
fullWidth
data-test-subj="titleInput"
required
isInvalid={fieldState.invalid}
value={field.value}
onChange={(event) => field.onChange(event.target.value)}
/>
)}
/>
</EuiFormRow>
</EuiFlexItem>
<EuiFlexItem grow>
<StatusField />
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlyoutBody>
<EuiFlyoutFooter>
<EuiFlexGroup justifyContent="spaceBetween">
<EuiFlexItem grow={false}>
<EuiButtonEmpty
data-test-subj="closeBtn"
iconType="cross"
onClick={() => onClose()}
flush="left"
>
{i18n.translate(
'xpack.investigateApp.investigationDetailsPage.closeButtonEmptyLabel',
{ defaultMessage: 'Close' }
)}
</EuiButtonEmpty>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiButton data-test-subj="saveBtn" onClick={methods.handleSubmit(onSubmit)} fill>
{i18n.translate('xpack.investigateApp.investigationDetailsPage.saveButtonLabel', {
defaultMessage: 'Save',
})}
</EuiButton>
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlyoutFooter>
</EuiFlyout>
</form>
</FormProvider>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { EuiEmptyPrompt } from '@elastic/eui';
import React from 'react';
import { i18n } from '@kbn/i18n';

export function InvestigationNotFound() {
return (
<EuiEmptyPrompt
iconType="error"
color="danger"
title={
<h2>
{i18n.translate('xpack.investigateApp.investigationEditForm.h2.unableToLoadTheLabel', {
defaultMessage: 'Unable to load the investigation form',
})}
</h2>
}
body={
<p>
{i18n.translate('xpack.investigateApp.investigationEditForm.p.thereWasAnErrorLabel', {
defaultMessage:
'There was an error loading the Investigation. Contact your administrator for help.',
})}
</p>
}
/>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { IHttpFetchError, ResponseErrorBody } from '@kbn/core/public';
import {
CreateInvestigationParams,
CreateInvestigationResponse,
FindInvestigationsResponse,
} from '@kbn/investigation-shared';
import { QueryKey, useMutation } from '@tanstack/react-query';
import { useKibana } from './use_kibana';

type ServerError = IHttpFetchError<ResponseErrorBody>;

export function useCreateInvestigation() {
const {
core: {
http,
notifications: { toasts },
},
} = useKibana();

return useMutation<
CreateInvestigationResponse,
ServerError,
CreateInvestigationParams,
{ previousData?: FindInvestigationsResponse; queryKey?: QueryKey }
>(
['createInvestigation'],
(investigation) => {
const body = JSON.stringify(investigation);
return http.post<CreateInvestigationResponse>(`/api/observability/investigations`, {
body,
version: '2023-10-31',
});
},

{
onSuccess: (response, investigation, context) => {
toasts.addSuccess('Investigation created');
},
onError: (error, investigation, context) => {
toasts.addError(new Error(error.body?.message ?? 'An error occurred'), { title: 'Error' });
},
}
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { investigationKeys } from './query_key_factory';
import { useKibana } from './use_kibana';

export interface Params {
id: string;
id?: string;
initialInvestigation?: GetInvestigationResponse;
}

Expand Down Expand Up @@ -45,13 +45,14 @@ export function useFetchInvestigation({

const { isInitialLoading, isLoading, isError, isSuccess, isRefetching, data, refetch } = useQuery(
{
queryKey: investigationKeys.fetch({ id }),
queryKey: investigationKeys.fetch({ id: id! }),
queryFn: async ({ signal }) => {
return await http.get<GetInvestigationResponse>(`/api/observability/investigations/${id}`, {
version: '2023-10-31',
signal,
});
},
enabled: Boolean(id),
initialData: initialInvestigation,
refetchOnWindowFocus: false,
refetchInterval: 15 * 1000,
Expand Down
Loading

0 comments on commit 6ef9f6c

Please sign in to comment.