Skip to content

Commit

Permalink
chore(rca): show full name in notes and store profile id in model (el…
Browse files Browse the repository at this point in the history
  • Loading branch information
kdelemme committed Sep 18, 2024
1 parent 5bf4501 commit bfbcf62
Show file tree
Hide file tree
Showing 12 changed files with 163 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

export const investigationKeys = {
all: ['investigations'] as const,
userProfiles: (profileIds: Set<string>) =>
[...investigationKeys.all, 'userProfiles', ...profileIds] as const,
tags: () => [...investigationKeys.all, 'tags'] as const,
stats: () => [...investigationKeys.all, 'stats'] as const,
lists: () => [...investigationKeys.all, 'list'] as const,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* 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 { i18n } from '@kbn/i18n';
import { UserProfile } from '@kbn/security-plugin/common';
import { useQuery } from '@tanstack/react-query';
import { Dictionary, keyBy } from 'lodash';
import { investigationKeys } from './query_key_factory';
import { useKibana } from './use_kibana';

export interface Params {
profileIds: Set<string>;
}

export interface Response {
isInitialLoading: boolean;
isLoading: boolean;
isRefetching: boolean;
isSuccess: boolean;
isError: boolean;
data: Dictionary<UserProfile> | undefined;
}

export function useFetchUserProfiles({ profileIds }: Params) {
const {
core: {
notifications: { toasts },
userProfile,
},
} = useKibana();

const { isInitialLoading, isLoading, isError, isSuccess, isRefetching, data } = useQuery({
queryKey: investigationKeys.userProfiles(profileIds),
queryFn: async () => {
const userProfiles = await userProfile.bulkGet({ uids: profileIds });
return keyBy(userProfiles, 'uid');
},
enabled: profileIds.size > 0,
retry: false,
cacheTime: Infinity,
staleTime: Infinity,
onError: (error: Error) => {
toasts.addError(error, {
title: i18n.translate('xpack.investigateApp.useFetchUserProfiles.errorTitle', {
defaultMessage: 'Something went wrong while fetching user profiles',
}),
});
},
});

return {
data,
isInitialLoading,
isLoading,
isRefetching,
isSuccess,
isError,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { i18n } from '@kbn/i18n';
import { InvestigationNoteResponse } from '@kbn/investigation-shared';
import { AuthenticatedUser } from '@kbn/security-plugin/common';
import React, { useState } from 'react';
import { useFetchUserProfiles } from '../../../../hooks/use_fetch_user_profiles';
import { useTheme } from '../../../../hooks/use_theme';
import { useInvestigation } from '../../contexts/investigation_context';
import { Note } from './note';
Expand All @@ -30,8 +31,11 @@ export interface Props {
export function InvestigationNotes({ user }: Props) {
const theme = useTheme();
const { investigation, addNote, isAddingNote } = useInvestigation();
const [noteInput, setNoteInput] = useState('');
const { data: userProfiles, isLoading: isLoadingUserProfiles } = useFetchUserProfiles({
profileIds: new Set(investigation?.notes.map((note) => note.createdBy)),
});

const [noteInput, setNoteInput] = useState('');
const onAddNote = async (content: string) => {
await addNote(content);
setNoteInput('');
Expand Down Expand Up @@ -59,7 +63,9 @@ export function InvestigationNotes({ user }: Props) {
<Note
key={currNote.id}
note={currNote}
disabled={currNote.createdBy !== user.username}
userProfile={userProfiles?.[currNote.createdBy]}
userProfileLoading={isLoadingUserProfiles}
isOwner={currNote.createdBy === user.profile_uid}
/>
);
})}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@
* 2.0.
*/
import {
EuiAvatar,
EuiButtonEmpty,
EuiFlexGroup,
EuiFlexItem,
EuiLoadingSpinner,
EuiMarkdownFormat,
EuiText,
} from '@elastic/eui';
import { css } from '@emotion/css';
import { InvestigationNoteResponse } from '@kbn/investigation-shared';
import { UserProfile } from '@kbn/security-plugin/common';
// eslint-disable-next-line import/no-extraneous-dependencies
import { formatDistance } from 'date-fns';
import React, { useState } from 'react';
Expand All @@ -27,14 +28,16 @@ const textContainerClassName = css`

interface Props {
note: InvestigationNoteResponse;
disabled: boolean;
isOwner: boolean;
userProfile?: UserProfile;
userProfileLoading: boolean;
}

export function Note({ note, disabled }: Props) {
export function Note({ note, isOwner, userProfile, userProfileLoading }: Props) {
const theme = useTheme();
const [isEditing, setIsEditing] = useState(false);
const { deleteNote, isDeletingNote } = useInvestigation();

const theme = useTheme();
const timelineContainerClassName = css`
padding-bottom: 16px;
border-bottom: 1px solid ${theme.colors.lightShade};
Expand All @@ -43,51 +46,65 @@ export function Note({ note, disabled }: Props) {
}
`;

const actionButtonClassname = css`
color: ${theme.colors.mediumShade};
:hover {
color: ${theme.colors.darkShade};
}
`;

const timestampClassName = css`
color: ${theme.colors.darkShade};
`;

return (
<EuiFlexGroup direction="column" gutterSize="s" className={timelineContainerClassName}>
<EuiFlexGroup direction="row" alignItems="center" justifyContent="spaceBetween">
<EuiFlexGroup direction="row" alignItems="center" justifyContent="flexStart" gutterSize="s">
<EuiFlexGroup direction="row" justifyContent="spaceBetween">
<EuiFlexGroup direction="column" gutterSize="xs">
<EuiFlexItem grow={false}>
<EuiAvatar name={note.createdBy} size="s" />
{userProfileLoading ? (
<EuiLoadingSpinner size="s" />
) : (
<EuiText size="s">
{userProfile?.user.full_name ?? userProfile?.user.username ?? note?.createdBy}
</EuiText>
)}
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiText size="xs">
<EuiText size="xs" className={timestampClassName}>
{formatDistance(new Date(note.createdAt), new Date(), { addSuffix: true })}
</EuiText>
</EuiFlexItem>
</EuiFlexGroup>

<EuiFlexGroup
direction="row"
alignItems="center"
justifyContent="flexEnd"
gutterSize="none"
>
<EuiFlexItem grow={false}>
<EuiButtonEmpty
data-test-subj="editInvestigationNoteButton"
size="s"
iconSize="s"
color="text"
iconType="pencil"
disabled={disabled || isDeletingNote}
onClick={() => {
setIsEditing(!isEditing);
}}
/>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiButtonEmpty
size="s"
iconSize="s"
color="text"
iconType="trash"
disabled={disabled || isDeletingNote}
onClick={async () => await deleteNote(note.id)}
data-test-subj="deleteInvestigationNoteButton"
/>
</EuiFlexItem>
</EuiFlexGroup>
{isOwner && (
<EuiFlexGroup direction="row" justifyContent="flexEnd" gutterSize="none">
<EuiFlexItem grow={false}>
<EuiButtonEmpty
data-test-subj="editInvestigationNoteButton"
size="s"
iconSize="s"
iconType="pencil"
disabled={isDeletingNote}
onClick={() => {
setIsEditing(!isEditing);
}}
className={actionButtonClassname}
/>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiButtonEmpty
size="s"
iconSize="s"
iconType="trash"
disabled={isDeletingNote}
onClick={async () => await deleteNote(note.id)}
data-test-subj="deleteInvestigationNoteButton"
className={actionButtonClassname}
/>
</EuiFlexItem>
</EuiFlexGroup>
)}
</EuiFlexGroup>
<EuiFlexItem className={textContainerClassName}>
{isEditing ? (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/
import {
Criteria,
EuiAvatar,
EuiBadge,
EuiBasicTable,
EuiBasicTableColumn,
Expand All @@ -22,6 +23,7 @@ import React, { useState } from 'react';
import { paths } from '../../../../common/paths';
import { InvestigationStatusBadge } from '../../../components/investigation_status_badge/investigation_status_badge';
import { useFetchInvestigationList } from '../../../hooks/use_fetch_investigation_list';
import { useFetchUserProfiles } from '../../../hooks/use_fetch_user_profiles';
import { useKibana } from '../../../hooks/use_kibana';
import { InvestigationListActions } from './investigation_list_actions';
import { InvestigationStats } from './investigation_stats';
Expand Down Expand Up @@ -51,6 +53,10 @@ export function InvestigationList() {
filter: toFilter(status, tags),
});

const { data: userProfiles, isLoading: isUserProfilesLoading } = useFetchUserProfiles({
profileIds: new Set(data?.results.map((i) => i.createdBy)),
});

const investigations = data?.results ?? [];
const totalItemCount = data?.total ?? 0;

Expand All @@ -77,6 +83,27 @@ export function InvestigationList() {
defaultMessage: 'Created by',
}),
truncateText: true,
render: (value: InvestigationResponse['createdBy']) => {
return isUserProfilesLoading ? (
<EuiLoadingSpinner size="m" />
) : (
<EuiFlexGroup gutterSize="s" direction="row">
<EuiAvatar
name={
userProfiles?.[value]?.user.full_name ??
userProfiles?.[value]?.user.username ??
value
}
size="s"
/>
<EuiText size="s">
{userProfiles?.[value]?.user.full_name ??
userProfiles?.[value]?.user.username ??
value}
</EuiText>
</EuiFlexGroup>
);
},
},
{
field: 'tags',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export async function createInvestigation(
...params,
updatedAt: now,
createdAt: now,
createdBy: user.username,
createdBy: user.profile_uid!,
status: 'triage',
notes: [],
items: [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export async function createInvestigationItem(
const now = Date.now();
const investigationItem = {
id: v4(),
createdBy: user.username,
createdBy: user.profile_uid!,
createdAt: now,
updatedAt: now,
...params,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export async function createInvestigationNote(
const investigationNote = {
id: v4(),
content: params.content,
createdBy: user.username,
createdBy: user.profile_uid!,
updatedAt: now,
createdAt: now,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export async function deleteInvestigationItem(
throw new Error('Note not found');
}

if (item.createdBy !== user.username) {
if (item.createdBy !== user.profile_uid) {
throw new Error('User does not have permission to delete note');
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export async function deleteInvestigationNote(
throw new Error('Note not found');
}

if (note.createdBy !== user.username) {
if (note.createdBy !== user.profile_uid) {
throw new Error('User does not have permission to delete note');
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export async function updateInvestigationItem(
throw new Error('Cannot change item type');
}

if (item.createdBy !== user.username) {
if (item.createdBy !== user.profile_uid) {
throw new Error('User does not have permission to update item');
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export async function updateInvestigationNote(
throw new Error('Note not found');
}

if (note.createdBy !== user.username) {
if (note.createdBy !== user.profile_uid) {
throw new Error('User does not have permission to update note');
}

Expand Down

0 comments on commit bfbcf62

Please sign in to comment.