Skip to content

Commit

Permalink
[Cases] Enable case search by ID (#149233)
Browse files Browse the repository at this point in the history
Fixes #148084

[The uuid PR was merged](#149135)
so I am removing the `draft` status here.

## Summary

This PR introduces search by UUID in the Cases table. 

If a user puts a UUID in the search bar and presses enter the search
result will now return the case with that ID.

Additionally, we look for the matches of that search text in the title
and description fields.

See the example below:

<img width="1554" alt="Screenshot 2023-01-19 at 16 06 53"
src="https://user-images.githubusercontent.com/1533137/213477884-498d34c0-d4d1-405d-8d76-f077d46157aa.png">

We are searching for `733e1c40-9586-11ed-a29f-8b57be9cf211`. There are
two matches because that search text matches the ID of a case and the
title of another.

### Checklist

Delete any items that are not applicable to this PR.

- [x] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [x] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [x] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))


### Release notes

Users can now search for Cases by ID.

Co-authored-by: kibanamachine <[email protected]>
  • Loading branch information
adcoelho and kibanamachine authored Jan 25, 2023
1 parent 7f2bf93 commit a04a03b
Show file tree
Hide file tree
Showing 16 changed files with 323 additions and 42 deletions.
4 changes: 4 additions & 0 deletions x-pack/plugins/cases/common/api/cases/case.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,10 @@ export const CasesFindRequestRt = rt.partial({
* The fields to perform the simple_query_string parsed query against
*/
searchFields: rt.union([rt.array(rt.string), rt.string]),
/**
* The root fields to perform the simple_query_string parsed query against
*/
rootSearchFields: rt.array(rt.string),
/**
* The field to use for sorting the found objects.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export const INCIDENT_MANAGEMENT_SYSTEM = i18n.translate('xpack.cases.caseTable.
});

export const SEARCH_PLACEHOLDER = i18n.translate('xpack.cases.caseTable.searchPlaceholder', {
defaultMessage: 'e.g. case name',
defaultMessage: 'Search cases',
});

export const CLOSED = i18n.translate('xpack.cases.caseTable.closed', {
Expand Down
4 changes: 3 additions & 1 deletion x-pack/plugins/cases/server/authorization/mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ export type AuthorizationMock = jest.Mocked<Schema>;
export const createAuthorizationMock = () => {
const mocked: AuthorizationMock = {
ensureAuthorized: jest.fn(),
getAuthorizationFilter: jest.fn(),
getAuthorizationFilter: jest.fn().mockImplementation(async () => {
return { filter: undefined, ensureSavedObjectsAreAuthorized: () => {} };
}),
getAndEnsureAuthorizedEntities: jest.fn(),
};
return mocked;
Expand Down
66 changes: 66 additions & 0 deletions x-pack/plugins/cases/server/client/cases/find.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* 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 { v1 as uuidv1 } from 'uuid';

import type { CaseResponse } from '../../../common/api';

import { flattenCaseSavedObject } from '../../common/utils';
import { mockCases } from '../../mocks';
import { createCasesClientMockArgs, createCasesClientMockFindRequest } from '../mocks';
import { find } from './find';

describe('find', () => {
describe('constructSearch', () => {
const clientArgs = createCasesClientMockArgs();
const casesMap = new Map<string, CaseResponse>(
mockCases.map((obj) => {
return [obj.id, flattenCaseSavedObject({ savedObject: obj, totalComment: 2 })];
})
);
clientArgs.services.caseService.findCasesGroupedByID.mockResolvedValue({
page: 1,
perPage: 10,
total: casesMap.size,
casesMap,
});
clientArgs.services.caseService.getCaseStatusStats.mockResolvedValue({
open: 1,
'in-progress': 2,
closed: 3,
});

afterEach(() => {
jest.clearAllMocks();
});

it('search by uuid updates search term and adds rootSearchFields', async () => {
const search = uuidv1();
const findRequest = createCasesClientMockFindRequest({ search });

await find(findRequest, clientArgs);
await expect(clientArgs.services.caseService.findCasesGroupedByID).toHaveBeenCalled();

const call = clientArgs.services.caseService.findCasesGroupedByID.mock.calls[0][0];

expect(call.caseOptions.search).toBe(`"${search}" "cases:${search}"`);
expect(call.caseOptions).toHaveProperty('rootSearchFields');
expect(call.caseOptions.rootSearchFields).toStrictEqual(['_id']);
});

it('regular search term does not cause rootSearchFields to be appended', async () => {
const search = 'foobar';
const findRequest = createCasesClientMockFindRequest({ search });
await find(findRequest, clientArgs);
await expect(clientArgs.services.caseService.findCasesGroupedByID).toHaveBeenCalled();

const call = clientArgs.services.caseService.findCasesGroupedByID.mock.calls[0][0];

expect(call.caseOptions.search).toBe(search);
expect(call.caseOptions).not.toHaveProperty('rootSearchFields');
});
});
});
7 changes: 6 additions & 1 deletion x-pack/plugins/cases/server/client/cases/find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { CasesFindRequestRt, throwErrors, CasesFindResponseRt, excess } from '..

import { createCaseError } from '../../common/error';
import { asArray, transformCases } from '../../common/utils';
import { constructQueryOptions } from '../utils';
import { constructQueryOptions, constructSearch } from '../utils';
import { includeFieldsRequiredForAuthentication } from '../../authorization/utils';
import { Operations } from '../../authorization';
import type { CasesClientArgs } from '..';
Expand All @@ -36,6 +36,8 @@ export const find = async (
services: { caseService, licensingService },
authorization,
logger,
savedObjectsSerializer,
spaceId,
} = clientArgs;

try {
Expand Down Expand Up @@ -85,11 +87,14 @@ export const find = async (

const caseQueryOptions = constructQueryOptions({ ...queryArgs, authorizationFilter });

const caseSearch = constructSearch(queryParams.search, spaceId, savedObjectsSerializer);

const [cases, statusStats] = await Promise.all([
caseService.findCasesGroupedByID({
caseOptions: {
...queryParams,
...caseQueryOptions,
...caseSearch,
searchFields: asArray(queryParams.searchFields),
fields: includeFieldsRequiredForAuthentication(fields),
},
Expand Down
1 change: 1 addition & 0 deletions x-pack/plugins/cases/server/client/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ export class CasesClientFactory {
securityStartPlugin: this.options.securityPluginStart,
publicBaseUrl: this.options.publicBaseUrl,
spaceId: this.options.spacesPluginStart.spacesService.getSpaceId(request),
savedObjectsSerializer,
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,6 @@ function createMockClientArgs() {
});

const authorization = createAuthorizationMock();
authorization.getAuthorizationFilter.mockImplementation(async () => {
return { filter: undefined, ensureSavedObjectsAreAuthorized: () => {} };
});

const soClient = savedObjectsClientMock.create();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,6 @@ export function createMockClient() {

export function createMockClientArgs() {
const authorization = createAuthorizationMock();
authorization.getAuthorizationFilter.mockImplementation(async () => {
return { filter: undefined, ensureSavedObjectsAreAuthorized: () => {} };
});

const soClient = savedObjectsClientMock.create();

Expand Down
61 changes: 50 additions & 11 deletions x-pack/plugins/cases/server/client/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,29 @@

import type { PublicContract, PublicMethodsOf } from '@kbn/utility-types';
import { loggingSystemMock, savedObjectsClientMock } from '@kbn/core/server/mocks';
import { securityMock } from '@kbn/security-plugin/server/mocks';
import type { ISavedObjectsSerializer } from '@kbn/core-saved-objects-server';

import { securityMock } from '@kbn/security-plugin/server/mocks';
import { actionsClientMock } from '@kbn/actions-plugin/server/actions_client.mock';
import { makeLensEmbeddableFactory } from '@kbn/lens-plugin/server/embeddable/make_lens_embeddable_factory';
import { serializerMock } from '@kbn/core-saved-objects-base-server-mocks';

import type { CasesFindRequest } from '../../common/api';
import type { CasesClient } from '.';
import type { AttachmentsSubClient } from './attachments/client';
import type { CasesSubClient } from './cases/client';
import type { ConfigureSubClient } from './configure/client';
import type { CasesClientFactory } from './factory';
import type { MetricsSubClient } from './metrics/client';
import type { UserActionsSubClient } from './user_actions/client';

import { CaseStatuses } from '../../common';
import { CaseSeverity } from '../../common/api';
import { SortFieldCase } from '../../public/containers/types';
import {
createExternalReferenceAttachmentTypeRegistryMock,
createPersistableStateAttachmentTypeRegistryMock,
} from '../attachment_framework/mocks';
import { createAuthorizationMock } from '../authorization/mock';
import {
connectorMappingsServiceMock,
Expand All @@ -23,16 +41,6 @@ import {
createUserActionServiceMock,
createNotificationServiceMock,
} from '../services/mocks';
import type { AttachmentsSubClient } from './attachments/client';
import type { CasesSubClient } from './cases/client';
import type { ConfigureSubClient } from './configure/client';
import type { CasesClientFactory } from './factory';
import type { MetricsSubClient } from './metrics/client';
import type { UserActionsSubClient } from './user_actions/client';
import {
createExternalReferenceAttachmentTypeRegistryMock,
createPersistableStateAttachmentTypeRegistryMock,
} from '../attachment_framework/mocks';

type CasesSubClientMock = jest.Mocked<CasesSubClient>;

Expand Down Expand Up @@ -127,6 +135,20 @@ export const createCasesClientFactory = (): CasesClientFactoryMock => {
return factory as unknown as CasesClientFactoryMock;
};

type SavedObjectsSerializerMock = jest.Mocked<ISavedObjectsSerializer>;

export const createSavedObjectsSerializerMock = (): SavedObjectsSerializerMock => {
const serializer = serializerMock.create();
serializer.generateRawId.mockImplementation(
(namespace: string | undefined, type: string, id: string) => {
const namespacePrefix = namespace ? `${namespace}:` : '';
return `${namespacePrefix}${type}:${id}`;
}
);

return serializer;
};

export const createCasesClientMockArgs = () => {
return {
services: {
Expand Down Expand Up @@ -160,5 +182,22 @@ export const createCasesClientMockArgs = () => {
{}
)
),
savedObjectsSerializer: createSavedObjectsSerializerMock(),
};
};

export const createCasesClientMockFindRequest = (
overwrites?: CasesFindRequest
): CasesFindRequest => ({
search: '',
searchFields: ['title', 'description'],
severity: CaseSeverity.LOW,
assignees: [],
reporters: [],
status: CaseStatuses.open,
tags: [],
owner: [],
sortField: SortFieldCase.createdAt,
sortOrder: 'desc',
...overwrites,
});
2 changes: 2 additions & 0 deletions x-pack/plugins/cases/server/client/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type { ActionsClient } from '@kbn/actions-plugin/server';
import type { LensServerPluginSetup } from '@kbn/lens-plugin/server';
import type { SecurityPluginStart } from '@kbn/security-plugin/server';
import type { IBasePath } from '@kbn/core-http-browser';
import type { ISavedObjectsSerializer } from '@kbn/core-saved-objects-server';
import type { KueryNode } from '@kbn/es-query';
import type { CasesFindRequest, User } from '../../common/api';
import type { Authorization } from '../authorization/authorization';
Expand Down Expand Up @@ -53,6 +54,7 @@ export interface CasesClientArgs {
readonly externalReferenceAttachmentTypeRegistry: ExternalReferenceAttachmentTypeRegistry;
readonly securityStartPlugin: SecurityPluginStart;
readonly spaceId: string;
readonly savedObjectsSerializer: ISavedObjectsSerializer;
readonly publicBaseUrl?: IBasePath['publicBaseUrl'];
}

Expand Down
46 changes: 42 additions & 4 deletions x-pack/plugins/cases/server/client/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,23 @@
* 2.0.
*/

import { v1 as uuidv1 } from 'uuid';

import { DEFAULT_NAMESPACE_STRING } from '@kbn/core-saved-objects-utils-server';
import { toElasticsearchQuery } from '@kbn/es-query';

import { CaseStatuses } from '../../common';
import { CaseSeverity } from '../../common/api';
import { ESCaseSeverity, ESCaseStatus } from '../services/cases/types';
import { createSavedObjectsSerializerMock } from './mocks';
import {
arraysDifference,
buildNestedFilter,
buildRangeFilter,
constructQueryOptions,
constructSearch,
convertSortField,
} from './utils';
import { toElasticsearchQuery } from '@kbn/es-query';
import { CaseStatuses } from '../../common';
import { CaseSeverity } from '../../common/api';
import { ESCaseSeverity, ESCaseStatus } from '../services/cases/types';

describe('utils', () => {
describe('convertSortField', () => {
Expand Down Expand Up @@ -916,4 +922,36 @@ describe('utils', () => {
});
});
});

describe('constructSearchById', () => {
const savedObjectsSerializer = createSavedObjectsSerializerMock();

it('returns the rootSearchFields and search with correct values when given a uuid', () => {
const uuid = uuidv1(); // the specific version is irrelevant

expect(constructSearch(uuid, DEFAULT_NAMESPACE_STRING, savedObjectsSerializer))
.toMatchInlineSnapshot(`
Object {
"rootSearchFields": Array [
"_id",
],
"search": "\\"${uuid}\\" \\"cases:${uuid}\\"",
}
`);
});

it('search value not changed and no rootSearchFields when search is non-uuid', () => {
const search = 'foobar';
const result = constructSearch(search, DEFAULT_NAMESPACE_STRING, savedObjectsSerializer);

expect(result).not.toHaveProperty('rootSearchFields');
expect(result).toEqual({ search });
});

it('returns undefined if search term undefined', () => {
expect(constructSearch(undefined, DEFAULT_NAMESPACE_STRING, savedObjectsSerializer)).toEqual(
undefined
);
});
});
});
Loading

0 comments on commit a04a03b

Please sign in to comment.