Skip to content

Commit

Permalink
[8.x] chore(rca): show full name in notes and store profile id in mod…
Browse files Browse the repository at this point in the history
…el (#193211) (#193330)

# Backport

This will backport the following commits from `main` to `8.x`:
- [chore(rca): show full name in notes and store profile id in model
(#193211)](#193211)

<!--- Backport version: 9.4.3 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sqren/backport)

<!--BACKPORT [{"author":{"name":"Kevin
Delemme","email":"[email protected]"},"sourceCommit":{"committedDate":"2024-09-18T15:25:42Z","message":"chore(rca):
show full name in notes and store profile id in model
(#193211)","sha":"bfbcf6291edcb82448e99f4d5a479fecf7f58211","branchLabelMapping":{"^v9.0.0$":"main","^v8.16.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","v9.0.0","ci:project-deploy-observability","Team:obs-ux-management","v8.16.0"],"title":"chore(rca):
show full name in notes and store profile id in
model","number":193211,"url":"https://github.com/elastic/kibana/pull/193211","mergeCommit":{"message":"chore(rca):
show full name in notes and store profile id in model
(#193211)","sha":"bfbcf6291edcb82448e99f4d5a479fecf7f58211"}},"sourceBranch":"main","suggestedTargetBranches":["8.x"],"targetPullRequestStates":[{"branch":"main","label":"v9.0.0","branchLabelMappingKey":"^v9.0.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/193211","number":193211,"mergeCommit":{"message":"chore(rca):
show full name in notes and store profile id in model
(#193211)","sha":"bfbcf6291edcb82448e99f4d5a479fecf7f58211"}},{"branch":"8.x","label":"v8.16.0","branchLabelMappingKey":"^v8.16.0$","isSourceBranch":false,"state":"NOT_CREATED"}]}]
BACKPORT-->

Co-authored-by: Kevin Delemme <[email protected]>
  • Loading branch information
kibanamachine and kdelemme authored Sep 18, 2024
1 parent b5e09d1 commit 5cdbd66
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,
lists: () => [...investigationKeys.all, 'list'] as const,
list: (params: { page: number; perPage: number; search?: string; filter?: string }) =>
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 @@ -21,6 +22,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 { InvestigationsError } from './investigations_error';
Expand Down Expand Up @@ -49,6 +51,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 @@ -75,6 +81,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 5cdbd66

Please sign in to comment.