diff --git a/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx b/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx index a57fae8081bea4..a830b299d655b7 100644 --- a/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx @@ -8,6 +8,7 @@ import { EuiButton, EuiLoadingSpinner } from '@elastic/eui'; import React, { useCallback, useEffect } from 'react'; import styled from 'styled-components'; +import { useDispatch } from 'react-redux'; import { CommentRequest } from '../../../../../case/common/api'; import { usePostComment } from '../../containers/use_post_comment'; import { Case } from '../../containers/types'; @@ -18,6 +19,12 @@ import { Form, useForm, UseField } from '../../../shared_imports'; import * as i18n from './translations'; import { schema } from './schema'; +import { + dispatchUpdateTimeline, + queryTimelineById, +} from '../../../timelines/components/open_timeline/helpers'; +import { updateIsLoading as dispatchUpdateIsLoading } from '../../../timelines/store/timeline/actions'; +import { useApolloClient } from '../../../common/utils/apollo_context'; const MySpinner = styled(EuiLoadingSpinner)` position: absolute; @@ -46,6 +53,8 @@ export const AddComment = React.memo( options: { stripEmptyFields: false }, schema, }); + const dispatch = useDispatch(); + const apolloClient = useApolloClient(); const { handleCursorChange, handleOnTimelineChange } = useInsertTimeline( form, 'comment' @@ -62,6 +71,28 @@ export const AddComment = React.memo( // eslint-disable-next-line react-hooks/exhaustive-deps }, [insertQuote]); + const handleTimelineClick = useCallback( + (timelineId: string) => { + queryTimelineById({ + apolloClient, + timelineId, + updateIsLoading: ({ + id: currentTimelineId, + isLoading: isLoadingTimeline, + }: { + id: string; + isLoading: boolean; + }) => + dispatch( + dispatchUpdateIsLoading({ id: currentTimelineId, isLoading: isLoadingTimeline }) + ), + updateTimeline: dispatchUpdateTimeline(dispatch), + }); + }, + // eslint-disable-next-line react-hooks/exhaustive-deps + [apolloClient] + ); + const onSubmit = useCallback(async () => { const { isValid, data } = await form.submit(); if (isValid) { @@ -86,6 +117,7 @@ export const AddComment = React.memo( dataTestSubj: 'add-comment', placeholder: i18n.ADD_COMMENT_HELP_TEXT, onCursorPositionUpdate: handleCursorChange, + onClickTimeline: handleTimelineClick, bottomRightContent: ( export const getCasesColumns = ( actions: Array>, - filterStatus: string -): CasesColumns[] => [ - { - name: i18n.NAME, - render: (theCase: Case) => { - if (theCase.id != null && theCase.title != null) { - const caseDetailsLinkComponent = ( - - {theCase.title} - - ); - return theCase.status === 'open' ? ( - caseDetailsLinkComponent - ) : ( - <> - + filterStatus: string, + isModal: boolean +): CasesColumns[] => { + const columns = [ + { + name: i18n.NAME, + render: (theCase: Case) => { + if (theCase.id != null && theCase.title != null) { + const caseDetailsLinkComponent = !isModal ? ( + + {theCase.title} + + ) : ( + {theCase.title} + ); + return theCase.status === 'open' ? ( + caseDetailsLinkComponent + ) : ( + <> {caseDetailsLinkComponent} - {i18n.CLOSED} - - - ); - } - return getEmptyTagValue(); + + {i18n.CLOSED} + + + ); + } + return getEmptyTagValue(); + }, }, - }, - { - field: 'createdBy', - name: i18n.REPORTER, - render: (createdBy: Case['createdBy']) => { - if (createdBy != null) { - return ( - <> - - - {createdBy.fullName ? createdBy.fullName : createdBy.username ?? ''} - - - ); - } - return getEmptyTagValue(); + { + field: 'createdBy', + name: i18n.REPORTER, + render: (createdBy: Case['createdBy']) => { + if (createdBy != null) { + return ( + <> + + + {createdBy.fullName ? createdBy.fullName : createdBy.username ?? ''} + + + ); + } + return getEmptyTagValue(); + }, + }, + { + field: 'tags', + name: i18n.TAGS, + render: (tags: Case['tags']) => { + if (tags != null && tags.length > 0) { + return ( + + {tags.map((tag: string, i: number) => ( + + {tag} + + ))} + + ); + } + return getEmptyTagValue(); + }, + truncateText: true, }, - }, - { - field: 'tags', - name: i18n.TAGS, - render: (tags: Case['tags']) => { - if (tags != null && tags.length > 0) { - return ( - - {tags.map((tag: string, i: number) => ( - - {tag} - - ))} - - ); - } - return getEmptyTagValue(); + { + align: 'right' as HorizontalAlignment, + field: 'totalComment', + name: i18n.COMMENTS, + sortable: true, + render: (totalComment: Case['totalComment']) => + totalComment != null + ? renderStringField(`${totalComment}`, `case-table-column-commentCount`) + : getEmptyTagValue(), }, - truncateText: true, - }, - { - align: 'right', - field: 'totalComment', - name: i18n.COMMENTS, - sortable: true, - render: (totalComment: Case['totalComment']) => - totalComment != null - ? renderStringField(`${totalComment}`, `case-table-column-commentCount`) - : getEmptyTagValue(), - }, - filterStatus === 'open' - ? { - field: 'createdAt', - name: i18n.OPENED_ON, - sortable: true, - render: (createdAt: Case['createdAt']) => { - if (createdAt != null) { - return ( - - - - ); - } - return getEmptyTagValue(); - }, - } - : { - field: 'closedAt', - name: i18n.CLOSED_ON, - sortable: true, - render: (closedAt: Case['closedAt']) => { - if (closedAt != null) { - return ( - - - - ); - } - return getEmptyTagValue(); + filterStatus === 'open' + ? { + field: 'createdAt', + name: i18n.OPENED_ON, + sortable: true, + render: (createdAt: Case['createdAt']) => { + if (createdAt != null) { + return ( + + + + ); + } + return getEmptyTagValue(); + }, + } + : { + field: 'closedAt', + name: i18n.CLOSED_ON, + sortable: true, + render: (closedAt: Case['closedAt']) => { + if (closedAt != null) { + return ( + + + + ); + } + return getEmptyTagValue(); + }, }, + { + name: i18n.EXTERNAL_INCIDENT, + render: (theCase: Case) => { + if (theCase.id != null) { + return ; + } + return getEmptyTagValue(); }, - { - name: i18n.EXTERNAL_INCIDENT, - render: (theCase: Case) => { - if (theCase.id != null) { - return ; - } - return getEmptyTagValue(); }, - }, - { - name: i18n.INCIDENT_MANAGEMENT_SYSTEM, - render: (theCase: Case) => { - if (theCase.externalService != null) { - return renderStringField( - `${theCase.externalService.connectorName}`, - `case-table-column-connector` - ); - } - return getEmptyTagValue(); + { + name: i18n.INCIDENT_MANAGEMENT_SYSTEM, + render: (theCase: Case) => { + if (theCase.externalService != null) { + return renderStringField( + `${theCase.externalService.connectorName}`, + `case-table-column-connector` + ); + } + return getEmptyTagValue(); + }, + }, + { + name: i18n.ACTIONS, + actions, }, - }, - { - name: i18n.ACTIONS, - actions, - }, -]; + ]; + if (isModal) { + columns.pop(); // remove actions if in modal + } + return columns; +}; interface Props { theCase: Case; diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx index e3f4fee15ce681..bbb96f433d3c8f 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx @@ -151,8 +151,22 @@ describe('AllCases', () => { expect(column.find('.euiTableRowCell--hideForDesktop').text()).toEqual(columnName); expect(column.find('span').text()).toEqual(emptyTag); }; - getCasesColumns([], 'open').map((i, key) => i.name != null && checkIt(`${i.name}`, key)); + getCasesColumns([], 'open', false).map((i, key) => i.name != null && checkIt(`${i.name}`, key)); }); + + it('should not render case link or actions on modal=true', () => { + const wrapper = mount( + + + + ); + const checkIt = (columnName: string) => { + expect(columnName).not.toEqual(i18n.ACTIONS); + }; + getCasesColumns([], 'open', true).map((i, key) => i.name != null && checkIt(`${i.name}`)); + expect(wrapper.find(`a[data-test-subj="case-details-link"]`).exists()).toBeFalsy(); + }); + it('should tableHeaderSortButton AllCases', () => { const wrapper = mount( diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx index 32a7c4078071ef..d27f383fb94e33 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - +/* eslint-disable react-hooks/exhaustive-deps */ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { EuiBasicTable, @@ -72,7 +72,6 @@ const ProgressLoader = styled(EuiProgress)` z-index: ${theme.eui.euiZHeader}; `} `; - const getSortField = (field: string): SortFieldCase => { if (field === SortFieldCase.createdAt) { return SortFieldCase.createdAt; @@ -83,368 +82,373 @@ const getSortField = (field: string): SortFieldCase => { }; interface AllCasesProps { + onRowClick?: (id: string) => void; + isModal?: boolean; userCanCrud: boolean; } -export const AllCases = React.memo(({ userCanCrud }) => { - const urlSearch = useGetUrlSearch(navTabs.case); - const { actionLicense } = useGetActionLicense(); - const { - countClosedCases, - countOpenCases, - isLoading: isCasesStatusLoading, - fetchCasesStatus, - } = useGetCasesStatus(); - const { - data, - dispatchUpdateCaseProperty, - filterOptions, - loading, - queryParams, - selectedCases, - refetchCases, - setFilters, - setQueryParams, - setSelectedCases, - } = useGetCases(); +export const AllCases = React.memo( + ({ onRowClick = () => {}, isModal = false, userCanCrud }) => { + const urlSearch = useGetUrlSearch(navTabs.case); + const { actionLicense } = useGetActionLicense(); + const { + countClosedCases, + countOpenCases, + isLoading: isCasesStatusLoading, + fetchCasesStatus, + } = useGetCasesStatus(); + const { + data, + dispatchUpdateCaseProperty, + filterOptions, + loading, + queryParams, + selectedCases, + refetchCases, + setFilters, + setQueryParams, + setSelectedCases, + } = useGetCases(); - // Delete case - const { - dispatchResetIsDeleted, - handleOnDeleteConfirm, - handleToggleModal, - isLoading: isDeleting, - isDeleted, - isDisplayConfirmDeleteModal, - } = useDeleteCases(); - - // Update case - const { - dispatchResetIsUpdated, - isLoading: isUpdating, - isUpdated, - updateBulkStatus, - } = useUpdateCases(); - const [deleteThisCase, setDeleteThisCase] = useState({ - title: '', - id: '', - }); - const [deleteBulk, setDeleteBulk] = useState([]); - const filterRefetch = useRef<() => void>(); - const setFilterRefetch = useCallback( - (refetchFilter: () => void) => { - filterRefetch.current = refetchFilter; - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [filterRefetch.current] - ); - const refreshCases = useCallback( - (dataRefresh = true) => { - if (dataRefresh) refetchCases(); - fetchCasesStatus(); - setSelectedCases([]); - setDeleteBulk([]); - if (filterRefetch.current != null) { - filterRefetch.current(); - } - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [filterOptions, queryParams, filterRefetch.current] - ); + // Delete case + const { + dispatchResetIsDeleted, + handleOnDeleteConfirm, + handleToggleModal, + isLoading: isDeleting, + isDeleted, + isDisplayConfirmDeleteModal, + } = useDeleteCases(); - useEffect(() => { - if (isDeleted) { - refreshCases(); - dispatchResetIsDeleted(); - } - if (isUpdated) { - refreshCases(); - dispatchResetIsUpdated(); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [isDeleted, isUpdated]); - const confirmDeleteModal = useMemo( - () => ( - 0} - onCancel={handleToggleModal} - onConfirm={handleOnDeleteConfirm.bind( - null, - deleteBulk.length > 0 ? deleteBulk : [deleteThisCase] - )} - /> - ), - // eslint-disable-next-line react-hooks/exhaustive-deps - [deleteBulk, deleteThisCase, isDisplayConfirmDeleteModal] - ); + // Update case + const { + dispatchResetIsUpdated, + isLoading: isUpdating, + isUpdated, + updateBulkStatus, + } = useUpdateCases(); + const [deleteThisCase, setDeleteThisCase] = useState({ + title: '', + id: '', + }); + const [deleteBulk, setDeleteBulk] = useState([]); + const filterRefetch = useRef<() => void>(); + const setFilterRefetch = useCallback( + (refetchFilter: () => void) => { + filterRefetch.current = refetchFilter; + }, + [filterRefetch.current] + ); + const refreshCases = useCallback( + (dataRefresh = true) => { + if (dataRefresh) refetchCases(); + fetchCasesStatus(); + setSelectedCases([]); + setDeleteBulk([]); + if (filterRefetch.current != null) { + filterRefetch.current(); + } + }, + [filterOptions, queryParams, filterRefetch.current] + ); - const toggleDeleteModal = useCallback((deleteCase: Case) => { - handleToggleModal(); - setDeleteThisCase(deleteCase); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + useEffect(() => { + if (isDeleted) { + refreshCases(); + dispatchResetIsDeleted(); + } + if (isUpdated) { + refreshCases(); + dispatchResetIsUpdated(); + } + }, [isDeleted, isUpdated]); + const confirmDeleteModal = useMemo( + () => ( + 0} + onCancel={handleToggleModal} + onConfirm={handleOnDeleteConfirm.bind( + null, + deleteBulk.length > 0 ? deleteBulk : [deleteThisCase] + )} + /> + ), + [deleteBulk, deleteThisCase, isDisplayConfirmDeleteModal] + ); - const toggleBulkDeleteModal = useCallback( - (caseIds: string[]) => { + const toggleDeleteModal = useCallback((deleteCase: Case) => { handleToggleModal(); - if (caseIds.length === 1) { - const singleCase = selectedCases.find((theCase) => theCase.id === caseIds[0]); - if (singleCase) { - return setDeleteThisCase({ id: singleCase.id, title: singleCase.title }); + setDeleteThisCase(deleteCase); + }, []); + + const toggleBulkDeleteModal = useCallback( + (caseIds: string[]) => { + handleToggleModal(); + if (caseIds.length === 1) { + const singleCase = selectedCases.find((theCase) => theCase.id === caseIds[0]); + if (singleCase) { + return setDeleteThisCase({ id: singleCase.id, title: singleCase.title }); + } } - } - const convertToDeleteCases: DeleteCase[] = caseIds.map((id) => ({ id })); - setDeleteBulk(convertToDeleteCases); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [selectedCases] - ); + const convertToDeleteCases: DeleteCase[] = caseIds.map((id) => ({ id })); + setDeleteBulk(convertToDeleteCases); + }, + [selectedCases] + ); - const handleUpdateCaseStatus = useCallback( - (status: string) => { - updateBulkStatus(selectedCases, status); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [selectedCases] - ); + const handleUpdateCaseStatus = useCallback( + (status: string) => { + updateBulkStatus(selectedCases, status); + }, + [selectedCases] + ); - const selectedCaseIds = useMemo( - (): string[] => selectedCases.map((caseObj: Case) => caseObj.id), - [selectedCases] - ); + const selectedCaseIds = useMemo( + (): string[] => selectedCases.map((caseObj: Case) => caseObj.id), + [selectedCases] + ); - const getBulkItemsPopoverContent = useCallback( - (closePopover: () => void) => ( - - ), - // eslint-disable-next-line react-hooks/exhaustive-deps - [selectedCaseIds, filterOptions.status, toggleBulkDeleteModal] - ); - const handleDispatchUpdate = useCallback( - (args: Omit) => { - dispatchUpdateCaseProperty({ ...args, refetchCasesStatus: fetchCasesStatus }); - }, - [dispatchUpdateCaseProperty, fetchCasesStatus] - ); + const getBulkItemsPopoverContent = useCallback( + (closePopover: () => void) => ( + + ), + [selectedCaseIds, filterOptions.status, toggleBulkDeleteModal] + ); + const handleDispatchUpdate = useCallback( + (args: Omit) => { + dispatchUpdateCaseProperty({ ...args, refetchCasesStatus: fetchCasesStatus }); + }, + [dispatchUpdateCaseProperty, fetchCasesStatus] + ); - const actions = useMemo( - () => - getActions({ - caseStatus: filterOptions.status, - deleteCaseOnClick: toggleDeleteModal, - dispatchUpdate: handleDispatchUpdate, - }), - [filterOptions.status, toggleDeleteModal, handleDispatchUpdate] - ); + const actions = useMemo( + () => + getActions({ + caseStatus: filterOptions.status, + deleteCaseOnClick: toggleDeleteModal, + dispatchUpdate: handleDispatchUpdate, + }), + [filterOptions.status, toggleDeleteModal, handleDispatchUpdate] + ); - const actionsErrors = useMemo(() => getActionLicenseError(actionLicense), [actionLicense]); + const actionsErrors = useMemo(() => getActionLicenseError(actionLicense), [actionLicense]); - const tableOnChangeCallback = useCallback( - ({ page, sort }: EuiBasicTableOnChange) => { - let newQueryParams = queryParams; - if (sort) { - newQueryParams = { - ...newQueryParams, - sortField: getSortField(sort.field), - sortOrder: sort.direction, - }; - } - if (page) { - newQueryParams = { - ...newQueryParams, - page: page.index + 1, - perPage: page.size, - }; - } - setQueryParams(newQueryParams); - refreshCases(false); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [queryParams] - ); + const tableOnChangeCallback = useCallback( + ({ page, sort }: EuiBasicTableOnChange) => { + let newQueryParams = queryParams; + if (sort) { + newQueryParams = { + ...newQueryParams, + sortField: getSortField(sort.field), + sortOrder: sort.direction, + }; + } + if (page) { + newQueryParams = { + ...newQueryParams, + page: page.index + 1, + perPage: page.size, + }; + } + setQueryParams(newQueryParams); + refreshCases(false); + }, + [queryParams] + ); - const onFilterChangedCallback = useCallback( - (newFilterOptions: Partial) => { - if (newFilterOptions.status && newFilterOptions.status === 'closed') { - setQueryParams({ sortField: SortFieldCase.closedAt }); - } else if (newFilterOptions.status && newFilterOptions.status === 'open') { - setQueryParams({ sortField: SortFieldCase.createdAt }); - } - setFilters(newFilterOptions); - refreshCases(false); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [filterOptions, queryParams] - ); + const onFilterChangedCallback = useCallback( + (newFilterOptions: Partial) => { + if (newFilterOptions.status && newFilterOptions.status === 'closed') { + setQueryParams({ sortField: SortFieldCase.closedAt }); + } else if (newFilterOptions.status && newFilterOptions.status === 'open') { + setQueryParams({ sortField: SortFieldCase.createdAt }); + } + setFilters(newFilterOptions); + refreshCases(false); + }, + [filterOptions, queryParams] + ); - const memoizedGetCasesColumns = useMemo( - () => getCasesColumns(userCanCrud ? actions : [], filterOptions.status), - [actions, filterOptions.status, userCanCrud] - ); - const memoizedPagination = useMemo( - () => ({ - pageIndex: queryParams.page - 1, - pageSize: queryParams.perPage, - totalItemCount: data.total, - pageSizeOptions: [5, 10, 15, 20, 25], - }), - [data, queryParams] - ); + const memoizedGetCasesColumns = useMemo( + () => getCasesColumns(userCanCrud ? actions : [], filterOptions.status, isModal), + [actions, filterOptions.status, userCanCrud, isModal] + ); + const memoizedPagination = useMemo( + () => ({ + pageIndex: queryParams.page - 1, + pageSize: queryParams.perPage, + totalItemCount: data.total, + pageSizeOptions: [5, 10, 15, 20, 25], + }), + [data, queryParams] + ); - const sorting: EuiTableSortingType = { - sort: { field: queryParams.sortField, direction: queryParams.sortOrder }, - }; - const euiBasicTableSelectionProps = useMemo>( - () => ({ onSelectionChange: setSelectedCases }), - // eslint-disable-next-line react-hooks/exhaustive-deps - [selectedCases] - ); - const isCasesLoading = useMemo( - () => loading.indexOf('cases') > -1 || loading.indexOf('caseUpdate') > -1, - [loading] - ); - const isDataEmpty = useMemo(() => data.total === 0, [data]); + const sorting: EuiTableSortingType = { + sort: { field: queryParams.sortField, direction: queryParams.sortOrder }, + }; + const euiBasicTableSelectionProps = useMemo>( + () => ({ onSelectionChange: setSelectedCases }), + [selectedCases] + ); + const isCasesLoading = useMemo( + () => loading.indexOf('cases') > -1 || loading.indexOf('caseUpdate') > -1, + [loading] + ); + const isDataEmpty = useMemo(() => data.total === 0, [data]); - return ( - <> - {!isEmpty(actionsErrors) && ( - - )} - - - - - - - - - - } - titleTooltip={!isEmpty(actionsErrors) ? actionsErrors[0].title : ''} - urlSearch={urlSearch} - /> - - - - {i18n.CREATE_TITLE} - - - - - {(isCasesLoading || isDeleting || isUpdating) && !isDataEmpty && ( - - )} - - - {isCasesLoading && isDataEmpty ? ( -
- -
- ) : ( -
- - - - - {i18n.SHOWING_CASES(data.total ?? 0)} - - - - - {i18n.SHOWING_SELECTED_CASES(selectedCases.length)} - - {userCanCrud && ( - - {i18n.BULK_ACTIONS} - - )} - - {i18n.REFRESH} - - - - - {i18n.NO_CASES}} - titleSize="xs" - body={i18n.NO_CASES_BODY} - actions={ - - {i18n.ADD_NEW_CASE} - - } + const TableWrap = useMemo(() => (isModal ? 'span' : Panel), [isModal]); + return ( + <> + {!isEmpty(actionsErrors) && ( + + )} + {!isModal && ( + + + + + + + - } - onChange={tableOnChangeCallback} - pagination={memoizedPagination} - selection={userCanCrud ? euiBasicTableSelectionProps : {}} - sorting={sorting} - /> -
+ + + } + titleTooltip={!isEmpty(actionsErrors) ? actionsErrors[0].title : ''} + urlSearch={urlSearch} + /> + + + + {i18n.CREATE_TITLE} + + + + + )} + {(isCasesLoading || isDeleting || isUpdating) && !isDataEmpty && ( + )} -
- {confirmDeleteModal} - - ); -}); + + + {isCasesLoading && isDataEmpty ? ( +
+ +
+ ) : ( +
+ + + + + {i18n.SHOWING_CASES(data.total ?? 0)} + + + {!isModal && ( + + + {i18n.SHOWING_SELECTED_CASES(selectedCases.length)} + + {userCanCrud && ( + + {i18n.BULK_ACTIONS} + + )} + + {i18n.REFRESH} + + + )} + + + {i18n.NO_CASES}} + titleSize="xs" + body={i18n.NO_CASES_BODY} + actions={ + + {i18n.ADD_NEW_CASE} + + } + /> + } + onChange={tableOnChangeCallback} + pagination={memoizedPagination} + rowProps={(item) => + isModal + ? { + onClick: () => onRowClick(item.id), + } + : {} + } + selection={userCanCrud && !isModal ? euiBasicTableSelectionProps : undefined} + sorting={sorting} + /> +
+ )} +
+ {confirmDeleteModal} + + ); + } +); AllCases.displayName = 'AllCases'; diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.test.tsx new file mode 100644 index 00000000000000..a24cb6a87de745 --- /dev/null +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.test.tsx @@ -0,0 +1,140 @@ +/* + * 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 { mount } from 'enzyme'; +import React from 'react'; +import { AllCasesModal } from '.'; +import { TestProviders } from '../../../common/mock'; + +import { useGetCasesMockState, basicCaseId } from '../../containers/mock'; +import { useDeleteCases } from '../../containers/use_delete_cases'; +import { useGetCases } from '../../containers/use_get_cases'; +import { useGetCasesStatus } from '../../containers/use_get_cases_status'; +import { useUpdateCases } from '../../containers/use_bulk_update_case'; +import { EuiTableRow } from '@elastic/eui'; + +jest.mock('../../containers/use_bulk_update_case'); +jest.mock('../../containers/use_delete_cases'); +jest.mock('../../containers/use_get_cases'); +jest.mock('../../containers/use_get_cases_status'); + +const useDeleteCasesMock = useDeleteCases as jest.Mock; +const useGetCasesMock = useGetCases as jest.Mock; +const useGetCasesStatusMock = useGetCasesStatus as jest.Mock; +const useUpdateCasesMock = useUpdateCases as jest.Mock; +jest.mock('../../../common/lib/kibana', () => { + const originalModule = jest.requireActual('../../../common/lib/kibana'); + return { + ...originalModule, + useGetUserSavedObjectPermissions: jest.fn(), + }; +}); + +const onCloseCaseModal = jest.fn(); +const onRowClick = jest.fn(); +const defaultProps = { + onCloseCaseModal, + onRowClick, + showCaseModal: true, +}; +describe('AllCasesModal', () => { + const dispatchResetIsDeleted = jest.fn(); + const dispatchResetIsUpdated = jest.fn(); + const dispatchUpdateCaseProperty = jest.fn(); + const handleOnDeleteConfirm = jest.fn(); + const handleToggleModal = jest.fn(); + const refetchCases = jest.fn(); + const setFilters = jest.fn(); + const setQueryParams = jest.fn(); + const setSelectedCases = jest.fn(); + const updateBulkStatus = jest.fn(); + const fetchCasesStatus = jest.fn(); + + const defaultGetCases = { + ...useGetCasesMockState, + dispatchUpdateCaseProperty, + refetchCases, + setFilters, + setQueryParams, + setSelectedCases, + }; + const defaultDeleteCases = { + dispatchResetIsDeleted, + handleOnDeleteConfirm, + handleToggleModal, + isDeleted: false, + isDisplayConfirmDeleteModal: false, + isLoading: false, + }; + const defaultCasesStatus = { + countClosedCases: 0, + countOpenCases: 5, + fetchCasesStatus, + isError: false, + isLoading: true, + }; + const defaultUpdateCases = { + isUpdated: false, + isLoading: false, + isError: false, + dispatchResetIsUpdated, + updateBulkStatus, + }; + /* eslint-disable no-console */ + // Silence until enzyme fixed to use ReactTestUtils.act() + const originalError = console.error; + beforeAll(() => { + console.error = jest.fn(); + }); + afterAll(() => { + console.error = originalError; + }); + /* eslint-enable no-console */ + beforeEach(() => { + jest.resetAllMocks(); + useUpdateCasesMock.mockImplementation(() => defaultUpdateCases); + useGetCasesMock.mockImplementation(() => defaultGetCases); + useDeleteCasesMock.mockImplementation(() => defaultDeleteCases); + useGetCasesStatusMock.mockImplementation(() => defaultCasesStatus); + }); + + it('renders with unselectable rows', () => { + const wrapper = mount( + + + + ); + expect(wrapper.find(`[data-test-subj='all-cases-modal']`).exists()).toBeTruthy(); + expect(wrapper.find(EuiTableRow).first().prop('isSelectable')).toBeFalsy(); + }); + it('does not render modal if showCaseModal: false', () => { + const wrapper = mount( + + + + ); + expect(wrapper.find(`[data-test-subj='all-cases-modal']`).exists()).toBeFalsy(); + }); + it('onRowClick called when row is clicked', () => { + const wrapper = mount( + + + + ); + const firstRow = wrapper.find(EuiTableRow).first(); + firstRow.simulate('click'); + expect(onRowClick.mock.calls[0][0]).toEqual(basicCaseId); + }); + it('Closing modal calls onCloseCaseModal', () => { + const wrapper = mount( + + + + ); + const modalClose = wrapper.find('.euiModal__closeIcon').first(); + modalClose.simulate('click'); + expect(onCloseCaseModal).toBeCalled(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.tsx new file mode 100644 index 00000000000000..d2ca0f0cd02ee2 --- /dev/null +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.tsx @@ -0,0 +1,56 @@ +/* + * 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 React from 'react'; +import { + EuiModal, + EuiModalBody, + EuiModalHeader, + EuiModalHeaderTitle, + EuiOverlayMask, +} from '@elastic/eui'; +import { useGetUserSavedObjectPermissions } from '../../../common/lib/kibana'; +import { AllCases } from '../all_cases'; +import * as i18n from './translations'; + +interface AllCasesModalProps { + onCloseCaseModal: () => void; + showCaseModal: boolean; + onRowClick: (id: string) => void; +} + +export const AllCasesModalComponent = ({ + onCloseCaseModal, + onRowClick, + showCaseModal, +}: AllCasesModalProps) => { + const userPermissions = useGetUserSavedObjectPermissions(); + let modal; + if (showCaseModal) { + modal = ( + + + + {i18n.SELECT_CASE_TITLE} + + + + + + + ); + } + + return <>{modal}; +}; + +export const AllCasesModal = React.memo(AllCasesModalComponent); + +AllCasesModal.displayName = 'AllCasesModal'; diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/translations.ts b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/translations.ts new file mode 100644 index 00000000000000..e0f84d85414241 --- /dev/null +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/translations.ts @@ -0,0 +1,10 @@ +/* + * 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 { i18n } from '@kbn/i18n'; +export const SELECT_CASE_TITLE = i18n.translate('xpack.securitySolution.case.caseModal.title', { + defaultMessage: 'Select case to attach timeline', +}); diff --git a/x-pack/plugins/security_solution/public/cases/pages/case_details.tsx b/x-pack/plugins/security_solution/public/cases/pages/case_details.tsx index 5dfe12179b9900..780de303c02d34 100644 --- a/x-pack/plugins/security_solution/public/cases/pages/case_details.tsx +++ b/x-pack/plugins/security_solution/public/cases/pages/case_details.tsx @@ -10,7 +10,6 @@ import { useParams, Redirect } from 'react-router-dom'; import { WrapperPage } from '../../common/components/wrapper_page'; import { useGetUrlSearch } from '../../common/components/navigation/use_get_url_search'; import { useGetUserSavedObjectPermissions } from '../../common/lib/kibana'; -import { SpyRoute } from '../../common/utils/route/spy_routes'; import { getCaseUrl } from '../../common/components/link_to'; import { navTabs } from '../../app/home/home_navigations'; import { CaseView } from '../components/case_view'; @@ -36,7 +35,6 @@ export const CaseDetailsPage = React.memo(() => { )} - ) : null; }); diff --git a/x-pack/plugins/security_solution/public/common/mock/global_state.ts b/x-pack/plugins/security_solution/public/common/mock/global_state.ts index 4af39ade70d255..3e84e4035e15ed 100644 --- a/x-pack/plugins/security_solution/public/common/mock/global_state.ts +++ b/x-pack/plugins/security_solution/public/common/mock/global_state.ts @@ -229,6 +229,7 @@ export const mockGlobalState: State = { status: TimelineStatus.active, }, }, + insertTimeline: null, }, /** * These state's are wrapped in `Immutable`, but for compatibility with the overall app architecture, diff --git a/x-pack/plugins/security_solution/public/common/mock/index.ts b/x-pack/plugins/security_solution/public/common/mock/index.ts index bdad0ab1712abe..30eb4c63f40b85 100644 --- a/x-pack/plugins/security_solution/public/common/mock/index.ts +++ b/x-pack/plugins/security_solution/public/common/mock/index.ts @@ -15,3 +15,4 @@ export * from './test_providers'; export * from './utils'; export * from './mock_ecs'; export * from './timeline_results'; +export * from './kibana_react'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/flyout/header/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/flyout/header/index.tsx index ab8a24889e9bf5..8ad32d6e2cad01 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/flyout/header/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/flyout/header/index.tsx @@ -33,14 +33,14 @@ const StatefulFlyoutHeader = React.memo( associateNote, createTimeline, description, - isFavorite, isDataInTimeline, isDatepickerLocked, - title, + isFavorite, noteIds, notesById, status, timelineId, + title, toggleLock, updateDescription, updateIsFavorite, @@ -61,15 +61,15 @@ const StatefulFlyoutHeader = React.memo( isDataInTimeline={isDataInTimeline} isDatepickerLocked={isDatepickerLocked} isFavorite={isFavorite} - title={title} noteIds={noteIds} status={status} timelineId={timelineId} + title={title} toggleLock={toggleLock} updateDescription={updateDescription} updateIsFavorite={updateIsFavorite} - updateTitle={updateTitle} updateNote={updateNote} + updateTitle={updateTitle} usersViewing={usersViewing} /> ); diff --git a/x-pack/plugins/security_solution/public/timelines/components/flyout/header_with_close_button/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/flyout/header_with_close_button/index.test.tsx index 34a20e72159064..e5fc8b68b1cb7a 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/flyout/header_with_close_button/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/flyout/header_with_close_button/index.test.tsx @@ -10,22 +10,26 @@ import React from 'react'; import { TestProviders } from '../../../../common/mock'; import { FlyoutHeaderWithCloseButton } from '.'; -jest.mock('../../../../common/lib/kibana', () => { - return { - useKibana: jest.fn().mockReturnValue({ - services: { - application: { - capabilities: { - securitySolution: { - crud: true, - }, +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useHistory: jest.fn(), +})); +jest.mock('../../../../common/lib/kibana', () => ({ + ...jest.requireActual('../../../../common/lib/kibana'), + useKibana: jest.fn().mockReturnValue({ + services: { + application: { + capabilities: { + securitySolution: { + crud: true, }, }, }, - }), - useUiSetting$: jest.fn().mockReturnValue([]), - }; -}); + }, + }), + useUiSetting$: jest.fn().mockReturnValue([]), + useGetUserSavedObjectPermissions: jest.fn(), +})); describe('FlyoutHeaderWithCloseButton', () => { test('renders correctly against snapshot', () => { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/__snapshots__/timeline.test.tsx.snap b/x-pack/plugins/security_solution/public/timelines/components/timeline/__snapshots__/timeline.test.tsx.snap index 4ed0b52fc0f146..4e6cce618880b1 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/__snapshots__/timeline.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/__snapshots__/timeline.test.tsx.snap @@ -606,19 +606,40 @@ exports[`Timeline rendering renders correctly against snapshot 1`] = ` }, "filters": Array [], "uiSettings": Object { - "get": [Function], - "get$": [MockFunction], - "getAll": [MockFunction], - "getSaved$": [MockFunction], - "getUpdate$": [MockFunction], - "getUpdateErrors$": [MockFunction], - "isCustom": [MockFunction], - "isDeclared": [MockFunction], - "isDefault": [MockFunction], - "isOverridden": [MockFunction], - "overrideLocalDefault": [MockFunction], - "remove": [MockFunction], - "set": [MockFunction], + "get": [MockFunction] { + "calls": Array [ + Array [ + "query:allowLeadingWildcards", + ], + Array [ + "query:queryString:options", + ], + Array [ + "courier:ignoreFilterIfFieldNotInIndex", + ], + Array [ + "dateFormat:tz", + ], + ], + "results": Array [ + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + ], + }, }, "updated$": Subject { "_isScalar": false, @@ -826,7 +847,7 @@ exports[`Timeline rendering renders correctly against snapshot 1`] = ` } inputId="timeline" /> - - + `; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx index 931623d080198a..31101298676287 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx @@ -26,15 +26,25 @@ import { mockDataProviders } from './data_providers/mock/mock_data_providers'; import { StatefulTimeline, Props as StatefulTimelineProps } from './index'; import { Timeline } from './timeline'; -jest.mock('../../../common/lib/kibana'); +jest.mock('../../../common/lib/kibana', () => { + const originalModule = jest.requireActual('../../../common/lib/kibana'); + return { + ...originalModule, + useGetUserSavedObjectPermissions: jest.fn(), + }; +}); + const mockUseResizeObserver: jest.Mock = useResizeObserver as jest.Mock; jest.mock('use-resize-observer/polyfilled'); mockUseResizeObserver.mockImplementation(() => ({})); const mockUseSignalIndex: jest.Mock = useSignalIndex as jest.Mock; jest.mock('../../../alerts/containers/detection_engine/alerts/use_signal_index'); +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useHistory: jest.fn(), +})); jest.mock('../flyout/header_with_close_button'); - describe('StatefulTimeline', () => { let props = {} as StatefulTimelineProps; const sort: Sort = { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.test.tsx index 0a70413b7ea295..2ffbae1f7eb5c0 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.test.tsx @@ -17,6 +17,14 @@ jest.mock('react-redux', () => { return { ...reactRedux, useDispatch: () => mockDispatch, + useSelector: jest + .fn() + .mockReturnValueOnce({ + timelineId: 'timeline-id', + timelineSavedObjectId: '34578-3497-5893-47589-34759', + timelineTitle: 'Timeline title', + }) + .mockReturnValue(null), }; }); const mockLocation = { @@ -25,17 +33,6 @@ const mockLocation = { search: '', state: '', }; -const mockLocationWithState = { - ...mockLocation, - state: { - insertTimeline: { - timelineId: 'timeline-id', - timelineSavedObjectId: '34578-3497-5893-47589-34759', - timelineTitle: 'Timeline title', - }, - }, -}; - const onTimelineChange = jest.fn(); const defaultProps = { isDisabled: false, @@ -43,18 +40,21 @@ const defaultProps = { }; describe('Insert timeline popover ', () => { - beforeEach(() => { - jest.resetAllMocks(); + afterEach(() => { + jest.clearAllMocks(); }); it('should insert a timeline when passed in the router state', () => { - jest.spyOn(routeData, 'useLocation').mockReturnValue(mockLocationWithState); mount(); - expect(mockDispatch).toBeCalledWith({ + expect(mockDispatch.mock.calls[0][0]).toEqual({ payload: { id: 'timeline-id', show: false }, type: 'x-pack/security_solution/local/timeline/SHOW_TIMELINE', }); expect(onTimelineChange).toBeCalledWith('Timeline title', '34578-3497-5893-47589-34759'); + expect(mockDispatch.mock.calls[1][0]).toEqual({ + payload: null, + type: 'x-pack/security_solution/local/timeline/SET_INSERT_TIMELINE', + }); }); it('should do nothing when router state', () => { jest.spyOn(routeData, 'useLocation').mockReturnValue(mockLocation); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.tsx index ed4d742bb8b4d2..de199d9a1cc2eb 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.tsx @@ -6,14 +6,15 @@ import { EuiButtonIcon, EuiPopover, EuiSelectableOption, EuiToolTip } from '@elastic/eui'; import React, { memo, useCallback, useEffect, useMemo, useState } from 'react'; -import { useLocation } from 'react-router-dom'; -import { useDispatch } from 'react-redux'; +import { useDispatch, useSelector } from 'react-redux'; import { OpenTimelineResult } from '../../open_timeline/types'; import { SelectableTimeline } from '../selectable_timeline'; import * as i18n from '../translations'; -import { timelineActions } from '../../../../timelines/store/timeline'; +import { timelineActions, timelineSelectors } from '../../../../timelines/store/timeline'; import { TimelineType } from '../../../../../common/types/timeline'; +import { State } from '../../../../common/store'; +import { setInsertTimeline } from '../../../store/timeline/actions'; interface InsertTimelinePopoverProps { isDisabled: boolean; @@ -21,14 +22,6 @@ interface InsertTimelinePopoverProps { onTimelineChange: (timelineTitle: string, timelineId: string | null) => void; } -interface RouterState { - insertTimeline: { - timelineId: string; - timelineSavedObjectId: string; - timelineTitle: string; - }; -} - type Props = InsertTimelinePopoverProps; export const InsertTimelinePopoverComponent: React.FC = ({ @@ -38,22 +31,18 @@ export const InsertTimelinePopoverComponent: React.FC = ({ }) => { const dispatch = useDispatch(); const [isPopoverOpen, setIsPopoverOpen] = useState(false); - const { state } = useLocation(); - const [routerState, setRouterState] = useState(state ?? null); + const insertTimeline = useSelector((state: State) => { + return timelineSelectors.selectInsertTimeline(state); + }); useEffect(() => { - if (routerState && routerState.insertTimeline) { - dispatch( - timelineActions.showTimeline({ id: routerState.insertTimeline.timelineId, show: false }) - ); - onTimelineChange( - routerState.insertTimeline.timelineTitle, - routerState.insertTimeline.timelineSavedObjectId - ); - setRouterState(null); + if (insertTimeline != null) { + dispatch(timelineActions.showTimeline({ id: insertTimeline.timelineId, show: false })); + onTimelineChange(insertTimeline.timelineTitle, insertTimeline.timelineSavedObjectId); + dispatch(setInsertTimeline(null)); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [routerState]); + }, [insertTimeline, dispatch]); const handleClosePopover = useCallback(() => { setIsPopoverOpen(false); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/use_insert_timeline.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/use_insert_timeline.tsx index 0f9e64082a603d..6269bc1b4a1a33 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/use_insert_timeline.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/use_insert_timeline.tsx @@ -17,7 +17,7 @@ export const useInsertTimeline = (form: FormHook, fieldNa }); const handleOnTimelineChange = useCallback( (title: string, id: string | null) => { - const builtLink = `${basePath}/app/siem#/timelines?timeline=(id:'${id}',isOpen:!t)`; + const builtLink = `${basePath}/app/security#/timelines?timeline=(id:'${id}',isOpen:!t)`; const currentValue = form.getFormData()[fieldName]; const newValue: string = [ currentValue.slice(0, cursorPosition.start), diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.tsx index 9e74298f3aca9e..00a0e573248415 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.tsx @@ -21,7 +21,7 @@ import React, { useCallback } from 'react'; import uuid from 'uuid'; import styled from 'styled-components'; import { useHistory } from 'react-router-dom'; -import { useSelector } from 'react-redux'; +import { useDispatch, useSelector } from 'react-redux'; import { TimelineTypeLiteral, @@ -41,6 +41,7 @@ import { AssociateNote, UpdateNote } from '../../notes/helpers'; import { NOTES_PANEL_WIDTH } from './notes_size'; import { ButtonContainer, DescriptionContainer, LabelText, NameField, StyledStar } from './styles'; import * as i18n from './translations'; +import { setInsertTimeline } from '../../../store/timeline/actions'; import { useCreateTimelineButton } from './use_create_timeline'; export const historyToolTip = 'The chronological history of actions related to this timeline'; @@ -144,23 +145,25 @@ interface NewCaseProps { export const NewCase = React.memo( ({ onClosePopover, timelineId, timelineStatus, timelineTitle }) => { const history = useHistory(); + const dispatch = useDispatch(); const { savedObjectId } = useSelector((state: State) => timelineSelectors.selectTimeline(state, timelineId) ); + const handleClick = useCallback(() => { onClosePopover(); history.push({ pathname: `/${SiemPageName.case}/create`, - state: { - insertTimeline: { - timelineId, - timelineSavedObjectId: savedObjectId, - timelineTitle: timelineTitle.length > 0 ? timelineTitle : i18n.UNTITLED_TIMELINE, - }, - }, }); + dispatch( + setInsertTimeline({ + timelineId, + timelineSavedObjectId: savedObjectId, + timelineTitle: timelineTitle.length > 0 ? timelineTitle : i18n.UNTITLED_TIMELINE, + }) + ); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [onClosePopover, history, timelineId, timelineTitle]); + }, [dispatch, onClosePopover, history, timelineId, timelineTitle]); return ( ( ); NewCase.displayName = 'NewCase'; +interface ExistingCaseProps { + onClosePopover: () => void; + onOpenCaseModal: () => void; + timelineStatus: TimelineStatus; +} +export const ExistingCase = React.memo( + ({ onClosePopover, onOpenCaseModal, timelineStatus }) => { + const handleClick = useCallback(() => { + onClosePopover(); + onOpenCaseModal(); + }, [onOpenCaseModal, onClosePopover]); + + return ( + <> + + {i18n.ATTACH_TIMELINE_TO_EXISTING_CASE} + + + ); + } +); +ExistingCase.displayName = 'ExistingCase'; + export interface NewTimelineProps { createTimeline?: CreateTimeline; closeGearMenu?: () => void; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx index 952a7c104e19eb..505d0b8cba8548 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx @@ -6,33 +6,43 @@ import { mount } from 'enzyme'; import React from 'react'; -import { Provider as ReduxStoreProvider } from 'react-redux'; - import { TimelineStatus } from '../../../../../common/types/timeline'; import { mockGlobalState, apolloClientObservable, SUB_PLUGINS_REDUCER, + TestProviders, } from '../../../../common/mock'; import { createStore, State } from '../../../../common/store'; import { useThrottledResizeObserver } from '../../../../common/components/utils'; import { Properties, showDescriptionThreshold, showNotesThreshold } from '.'; +import { SiemPageName } from '../../../../app/types'; +import { setInsertTimeline } from '../../../store/timeline/actions'; +export { nextTick } from '../../../../../../../test_utils'; + +import { act } from 'react-dom/test-utils'; -jest.mock('../../../../common/lib/kibana', () => ({ - useKibana: jest.fn().mockReturnValue({ - services: { - application: { - capabilities: { - securitySolution: { - crud: true, +jest.mock('../../../../common/lib/kibana', () => { + const originalModule = jest.requireActual('../../../../common/lib/kibana'); + return { + ...originalModule, + useKibana: jest.fn().mockReturnValue({ + services: { + application: { + capabilities: { + securitySolution: { + crud: true, + }, }, }, }, - }, - }), - useUiSetting$: jest.fn().mockReturnValue([]), -})); + }), + useUiSetting$: jest.fn().mockReturnValue([]), + useGetUserSavedObjectPermissions: jest.fn(), + }; +}); +const mockDispatch = jest.fn(); jest.mock('../../../../common/components/utils', () => { return { useThrottledResizeObserver: jest.fn(), @@ -48,21 +58,44 @@ jest.mock('react-redux', () => { }; }); -jest.mock('react-router-dom', () => { - const originalModule = jest.requireActual('react-router-dom'); +jest.mock('react-redux', () => ({ + ...jest.requireActual('react-redux'), + useDispatch: () => mockDispatch, + useSelector: jest.fn().mockReturnValue({ savedObjectId: '1', urlState: {} }), +})); +const mockHistoryPush = jest.fn(); - return { - ...originalModule, - useHistory: jest.fn(), - }; -}); +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useHistory: () => ({ + push: mockHistoryPush, + }), +})); jest.mock('./use_create_timeline', () => ({ useCreateTimelineButton: jest.fn().mockReturnValue({ getButton: jest.fn() }), })); - +const usersViewing = ['elastic']; +const defaultProps = { + associateNote: jest.fn(), + createTimeline: jest.fn(), + isDataInTimeline: false, + isDatepickerLocked: false, + isFavorite: false, + title: '', + description: '', + getNotesByIds: jest.fn(), + noteIds: [], + status: TimelineStatus.active, + timelineId: 'abc', + toggleLock: jest.fn(), + updateDescription: jest.fn(), + updateIsFavorite: jest.fn(), + updateTitle: jest.fn(), + updateNote: jest.fn(), + usersViewing, +}; describe('Properties', () => { - const usersViewing = ['elastic']; const state: State = mockGlobalState; let mockedWidth = 1000; let store = createStore(state, SUB_PLUGINS_REDUCER, apolloClientObservable); @@ -75,27 +108,9 @@ describe('Properties', () => { test('renders correctly', () => { const wrapper = mount( - - - + + + ); wrapper.find('[data-test-subj="settings-gear"]').at(0).simulate('click'); @@ -104,31 +119,16 @@ describe('Properties', () => { expect(wrapper.find('button[data-test-subj="attach-timeline-case"]').prop('disabled')).toEqual( false ); + expect( + wrapper.find('button[data-test-subj="attach-timeline-existing-case"]').prop('disabled') + ).toEqual(false); }); test('renders correctly draft timeline', () => { const wrapper = mount( - - - + + + ); wrapper.find('[data-test-subj="settings-gear"]').at(0).simulate('click'); @@ -136,31 +136,16 @@ describe('Properties', () => { expect(wrapper.find('button[data-test-subj="attach-timeline-case"]').prop('disabled')).toEqual( true ); + expect( + wrapper.find('button[data-test-subj="attach-timeline-existing-case"]').prop('disabled') + ).toEqual(true); }); test('it renders an empty star icon when it is NOT a favorite', () => { const wrapper = mount( - - - + + + ); expect(wrapper.find('[data-test-subj="timeline-favorite-empty-star"]').exists()).toEqual(true); @@ -168,27 +153,9 @@ describe('Properties', () => { test('it renders a filled star icon when it is a favorite', () => { const wrapper = mount( - - - + + + ); expect(wrapper.find('[data-test-subj="timeline-favorite-filled-star"]').exists()).toEqual(true); @@ -198,27 +165,9 @@ describe('Properties', () => { const title = 'foozle'; const wrapper = mount( - - - + + + ); expect(wrapper.find('[data-test-subj="timeline-title"]').first().props().value).toEqual(title); @@ -226,27 +175,9 @@ describe('Properties', () => { test('it renders the date picker with the lock icon', () => { const wrapper = mount( - - - + + + ); expect( @@ -259,27 +190,9 @@ describe('Properties', () => { test('it renders the lock icon when isDatepickerLocked is true', () => { const wrapper = mount( - - - + + + ); expect( wrapper @@ -291,27 +204,9 @@ describe('Properties', () => { test('it renders the unlock icon when isDatepickerLocked is false', () => { const wrapper = mount( - - - + + + ); expect( wrapper @@ -328,27 +223,9 @@ describe('Properties', () => { (useThrottledResizeObserver as jest.Mock).mockReturnValue({ width: showDescriptionThreshold }); const wrapper = mount( - - - + + + ); expect( @@ -369,27 +246,9 @@ describe('Properties', () => { }); const wrapper = mount( - - - + + + ); expect( @@ -404,27 +263,9 @@ describe('Properties', () => { mockedWidth = showNotesThreshold; const wrapper = mount( - - - + + + ); expect( @@ -442,27 +283,9 @@ describe('Properties', () => { }); const wrapper = mount( - - - + + + ); expect( @@ -475,27 +298,9 @@ describe('Properties', () => { test('it renders a settings icon', () => { const wrapper = mount( - - - + + + ); expect(wrapper.find('[data-test-subj="settings-gear"]').exists()).toEqual(true); @@ -505,27 +310,9 @@ describe('Properties', () => { const title = 'port scan'; const wrapper = mount( - - - + + + ); expect(wrapper.find('[data-test-subj="avatar"]').exists()).toEqual(true); @@ -533,29 +320,45 @@ describe('Properties', () => { test('it does NOT render an avatar for the current user viewing the timeline when it does NOT have a title', () => { const wrapper = mount( - - - + + + ); expect(wrapper.find('[data-test-subj="avatar"]').exists()).toEqual(false); }); + + test('insert timeline - new case', () => { + const wrapper = mount( + + + + ); + wrapper.find('[data-test-subj="settings-gear"]').at(0).simulate('click'); + wrapper.find('[data-test-subj="attach-timeline-case"]').first().simulate('click'); + + expect(mockHistoryPush).toBeCalledWith({ pathname: `/${SiemPageName.case}/create` }); + expect(mockDispatch).toBeCalledWith( + setInsertTimeline({ + timelineId: defaultProps.timelineId, + timelineSavedObjectId: '1', + timelineTitle: 'coolness', + }) + ); + }); + + test('insert timeline - existing case', async () => { + const wrapper = mount( + + + + ); + wrapper.find('[data-test-subj="settings-gear"]').at(0).simulate('click'); + wrapper.find('[data-test-subj="attach-timeline-existing-case"]').first().simulate('click'); + + await act(async () => { + await Promise.resolve({}); + }); + expect(wrapper.find('[data-test-subj="all-cases-modal"]').exists()).toBeTruthy(); + }); }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx index d4c43c9929f0ed..be79c0773bf88e 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx @@ -6,6 +6,8 @@ import React, { useState, useCallback, useMemo } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import { useHistory } from 'react-router-dom'; import { TimelineStatus, TimelineTypeLiteral } from '../../../../../common/types/timeline'; import { useThrottledResizeObserver } from '../../../../common/components/utils'; import { Note } from '../../../../common/lib/note'; @@ -16,6 +18,12 @@ import { AssociateNote, UpdateNote } from '../../notes/helpers'; import { TimelineProperties } from './styles'; import { PropertiesRight } from './properties_right'; import { PropertiesLeft } from './properties_left'; +import { AllCasesModal } from '../../../../cases/components/all_cases_modal'; +import { SiemPageName } from '../../../../app/types'; +import * as i18n from './translations'; +import { State } from '../../../../common/store'; +import { timelineSelectors } from '../../../store/timeline'; +import { setInsertTimeline } from '../../../store/timeline/actions'; type CreateTimeline = ({ id, @@ -87,6 +95,7 @@ export const Properties = React.memo( const [showActions, setShowActions] = useState(false); const [showNotes, setShowNotes] = useState(false); const [showTimelineModal, setShowTimelineModal] = useState(false); + const dispatch = useDispatch(); const onButtonClick = useCallback(() => setShowActions(!showActions), [showActions]); const onToggleShowNotes = useCallback(() => setShowNotes(!showNotes), [showNotes]); @@ -98,6 +107,30 @@ export const Properties = React.memo( setShowTimelineModal(true); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + const [showCaseModal, setShowCaseModal] = useState(false); + const onCloseCaseModal = useCallback(() => setShowCaseModal(false), []); + const onOpenCaseModal = useCallback(() => setShowCaseModal(true), []); + const history = useHistory(); + const currentTimeline = useSelector((state: State) => + timelineSelectors.selectTimeline(state, timelineId) + ); + + const onRowClick = useCallback( + (id: string) => { + onCloseCaseModal(); + history.push({ + pathname: `/${SiemPageName.case}/${id}`, + }); + dispatch( + setInsertTimeline({ + timelineId, + timelineSavedObjectId: currentTimeline.savedObjectId, + timelineTitle: title.length > 0 ? title : i18n.UNTITLED_TIMELINE, + }) + ); + }, + [onCloseCaseModal, currentTimeline, dispatch, history, timelineId, title] + ); const datePickerWidth = useMemo( () => @@ -144,6 +177,7 @@ export const Properties = React.memo( onButtonClick={onButtonClick} onClosePopover={onClosePopover} onCloseTimelineModal={onCloseTimelineModal} + onOpenCaseModal={onOpenCaseModal} onOpenTimelineModal={onOpenTimelineModal} onToggleShowNotes={onToggleShowNotes} showActions={showActions} @@ -159,6 +193,11 @@ export const Properties = React.memo( updateNote={updateNote} usersViewing={usersViewing} /> + ); } diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.test.tsx index 58927e7b236e7b..e297a3cc595d6d 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.test.tsx @@ -28,9 +28,10 @@ jest.mock('./new_template_timeline', () => { jest.mock('./helpers', () => { return { Description: jest.fn().mockReturnValue(
), - NotesButton: jest.fn().mockReturnValue(
), + ExistingCase: jest.fn().mockReturnValue(
), NewCase: jest.fn().mockReturnValue(
), NewTimeline: jest.fn().mockReturnValue(
), + NotesButton: jest.fn().mockReturnValue(
), }; }); @@ -62,6 +63,7 @@ describe('Properties Right', () => { noteIds: [], onToggleShowNotes: jest.fn(), onCloseTimelineModal: jest.fn(), + onOpenCaseModal: jest.fn(), onOpenTimelineModal: jest.fn(), status: TimelineStatus.active, showTimelineModal: false, diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.tsx index f9ab7fb2e69ae1..a9baf73676ffb1 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.tsx @@ -14,6 +14,7 @@ import { EuiToolTip, EuiAvatar, } from '@elastic/eui'; +import { NewTimeline, Description, NotesButton, NewCase, ExistingCase } from './helpers'; import { disableTemplate } from '../../../../../common/constants'; import { TimelineStatus } from '../../../../../common/types/timeline'; @@ -27,7 +28,6 @@ import { OpenTimelineModalButton } from '../../open_timeline/open_timeline_modal import { OpenTimelineModal } from '../../open_timeline/open_timeline_modal'; import * as i18n from './translations'; -import { Description, NotesButton, NewCase, NewTimeline } from './helpers'; import { NewTemplateTimeline } from './new_template_timeline'; export const PropertiesRightStyle = styled(EuiFlexGroup)` @@ -64,54 +64,56 @@ Avatar.displayName = 'Avatar'; type UpdateDescription = ({ id, description }: { id: string; description: string }) => void; export type UpdateNote = (note: Note) => void; -export interface PropertiesRightComponentProps { - onButtonClick: () => void; - onClosePopover: () => void; - showActions: boolean; - timelineId: string; - isDataInTimeline: boolean; - showNotes: boolean; - showNotesFromWidth: boolean; - showDescription: boolean; - showUsersView: boolean; - usersViewing: string[]; - description: string; - updateDescription: UpdateDescription; +interface PropertiesRightComponentProps { associateNote: AssociateNote; + description: string; getNotesByIds: (noteIds: string[]) => Note[]; + isDataInTimeline: boolean; noteIds: string[]; - onToggleShowNotes: () => void; + onButtonClick: () => void; + onClosePopover: () => void; onCloseTimelineModal: () => void; + onOpenCaseModal: () => void; onOpenTimelineModal: () => void; + onToggleShowNotes: () => void; + showActions: boolean; + showDescription: boolean; + showNotes: boolean; + showNotesFromWidth: boolean; showTimelineModal: boolean; + showUsersView: boolean; status: TimelineStatus; + timelineId: string; title: string; + updateDescription: UpdateDescription; updateNote: UpdateNote; + usersViewing: string[]; } const PropertiesRightComponent: React.FC = ({ - onButtonClick, - showActions, - onClosePopover, - timelineId, - isDataInTimeline, - showNotesFromWidth, - showNotes, - showDescription, - showUsersView, - usersViewing, - description, - updateDescription, associateNote, + description, getNotesByIds, + isDataInTimeline, noteIds, + onButtonClick, + onClosePopover, + onCloseTimelineModal, + onOpenCaseModal, + onOpenTimelineModal, onToggleShowNotes, - updateNote, + showActions, + showDescription, + showNotes, + showNotesFromWidth, showTimelineModal, + showUsersView, status, - onCloseTimelineModal, - onOpenTimelineModal, + timelineId, title, + updateDescription, + updateNote, + usersViewing, }) => { const uiCapabilities = useKibana().services.application.capabilities; const capabilitiesCanUserCRUD: boolean = !!uiCapabilities.securitySolution.crud; @@ -170,6 +172,13 @@ const PropertiesRightComponent: React.FC = ({ timelineStatus={status} /> + + + ({})); +jest.mock('react-router-dom', () => { + const originalModule = jest.requireActual('react-router-dom'); + return { + ...originalModule, + useHistory: jest.fn(), + }; +}); +jest.mock('../../../common/lib/kibana', () => { + const originalModule = jest.requireActual('../../../common/lib/kibana'); + return { + ...originalModule, + useKibana: jest.fn().mockReturnValue({ + services: { + uiSettings: { + get: jest.fn(), + }, + savedObjects: { + client: {}, + }, + }, + }), + useGetUserSavedObjectPermissions: jest.fn(), + }; +}); describe('Timeline', () => { let props = {} as TimelineComponentProps; const sort: Sort = { diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts index e8b5ba68eecdf1..c5df017604b0c6 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts @@ -17,6 +17,7 @@ import { KueryFilterQuery, SerializedFilterQuery } from '../../../common/store/t import { EventType, KqlMode, TimelineModel, ColumnHeaderOptions } from './model'; import { TimelineNonEcsData } from '../../../graphql/types'; import { TimelineTypeLiteral } from '../../../../common/types/timeline'; +import { InsertTimeline } from './types'; const actionCreator = actionCreatorFactory('x-pack/security_solution/local/timeline'); @@ -98,6 +99,8 @@ export const addTimeline = actionCreator<{ timeline: TimelineModel; }>('ADD_TIMELINE'); +export const setInsertTimeline = actionCreator('SET_INSERT_TIMELINE'); + export const startTimelineSaving = actionCreator<{ id: string; }>('START_TIMELINE_SAVING'); diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts index 97ac423cee653c..03e9ca176ee821 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts @@ -36,6 +36,7 @@ export const initialTimelineState: TimelineState = { newTimelineModel: null, }, showCallOutUnauthorizedMsg: false, + insertTimeline: null, }; interface AddTimelineHistoryParams { diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.ts index 3666968e8ab923..5e314f15974513 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.ts @@ -6,14 +6,17 @@ import { reducerWithInitialState } from 'typescript-fsa-reducers'; import { - addTimeline, addHistory, addNote, addNoteToEvent, addProvider, + addTimeline, applyDeltaToColumnWidth, applyDeltaToWidth, applyKqlFilterQuery, + clearEventsDeleted, + clearEventsLoading, + clearSelected, createTimeline, dataProviderEdited, endTimelineSaving, @@ -21,12 +24,12 @@ import { removeColumn, removeProvider, setEventsDeleted, - clearEventsDeleted, setEventsLoading, - clearEventsLoading, + setFilters, + setInsertTimeline, setKqlFilterQueryDraft, + setSavedQueryId, setSelected, - clearSelected, showCallOutUnauthorizedMsg, showTimeline, startTimelineSaving, @@ -37,9 +40,11 @@ import { updateDataProviderExcluded, updateDataProviderKqlQuery, updateDescription, + updateEventType, updateHighlightedDropAndProviderId, updateIsFavorite, updateIsLive, + updateIsLoading, updateItemsPerPage, updateItemsPerPageOptions, updateKqlMode, @@ -50,10 +55,6 @@ import { updateTimeline, updateTitle, upsertColumn, - updateIsLoading, - setSavedQueryId, - setFilters, - updateEventType, } from './actions'; import { addNewTimeline, @@ -107,6 +108,7 @@ export const initialTimelineState: TimelineState = { newTimelineModel: null, }, showCallOutUnauthorizedMsg: false, + insertTimeline: null, }; /** The reducer for all timeline actions */ @@ -486,4 +488,8 @@ export const timelineReducer = reducerWithInitialState(initialTimelineState) timelineById: state.timelineById, }), })) + .case(setInsertTimeline, (state, insertTimeline) => ({ + ...state, + insertTimeline, + })) .build(); diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/selectors.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/selectors.ts index af7ac075468c38..a80a28660e28b9 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/selectors.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/selectors.ts @@ -10,7 +10,7 @@ import { isFromKueryExpressionValid } from '../../../common/lib/keury'; import { State } from '../../../common/store/types'; import { TimelineModel } from './model'; -import { AutoSavedWarningMsg, TimelineById } from './types'; +import { AutoSavedWarningMsg, InsertTimeline, TimelineById } from './types'; const selectTimelineById = (state: State): TimelineById => state.timeline.timelineById; @@ -22,6 +22,9 @@ const selectCallOutUnauthorizedMsg = (state: State): boolean => export const selectTimeline = (state: State, timelineId: string): TimelineModel => state.timeline.timelineById[timelineId]; +export const selectInsertTimeline = (state: State): InsertTimeline | null => + state.timeline.insertTimeline; + export const autoSaveMsgSelector = createSelector(selectAutoSaveMsg, (autoSaveMsg) => autoSaveMsg); export const timelineByIdSelector = createSelector( diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/types.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/types.ts index 1cc4517d2c9642..aa6c3086142872 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/types.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/types.ts @@ -16,6 +16,12 @@ export interface TimelineById { [id: string]: TimelineModel; } +export interface InsertTimeline { + timelineId: string; + timelineSavedObjectId: string | null; + timelineTitle: string; +} + export const EMPTY_TIMELINE_BY_ID: TimelineById = {}; // stable reference /** The state of all timelines is stored here */ @@ -23,6 +29,7 @@ export interface TimelineState { timelineById: TimelineById; autoSavedWarningMsg: AutoSavedWarningMsg; showCallOutUnauthorizedMsg: boolean; + insertTimeline: InsertTimeline | null; } export interface ActionTimeline extends Action {