Merge pull request #7304 from AlexSCorey/7233-ApplicationsList

Adds lists and list items and delete functionality

Reviewed-by: https://github.com/apps/softwarefactory-project-zuul
This commit is contained in:
softwarefactory-project-zuul[bot] 2020-06-11 19:47:56 +00:00 committed by GitHub
commit 26083bdef6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 572 additions and 5 deletions

View File

@ -1,4 +1,5 @@
import AdHocCommands from './models/AdHocCommands';
import Applications from './models/Applications';
import Config from './models/Config';
import CredentialInputSources from './models/CredentialInputSources';
import CredentialTypes from './models/CredentialTypes';
@ -31,6 +32,7 @@ import WorkflowJobTemplates from './models/WorkflowJobTemplates';
import WorkflowJobs from './models/WorkflowJobs';
const AdHocCommandsAPI = new AdHocCommands();
const ApplicationsAPI = new Applications();
const ConfigAPI = new Config();
const CredentialInputSourcesAPI = new CredentialInputSources();
const CredentialTypesAPI = new CredentialTypes();
@ -64,6 +66,7 @@ const WorkflowJobsAPI = new WorkflowJobs();
export {
AdHocCommandsAPI,
ApplicationsAPI,
ConfigAPI,
CredentialInputSourcesAPI,
CredentialTypesAPI,

View File

@ -0,0 +1,10 @@
import Base from '../Base';
class Applications extends Base {
constructor(http) {
super(http);
this.baseUrl = '/api/v2/applications/';
}
}
export default Applications;

View File

@ -0,0 +1,189 @@
import React from 'react';
import { act } from 'react-dom/test-utils';
import {
mountWithContexts,
waitForElement,
} from '../../../../testUtils/enzymeHelpers';
import { ApplicationsAPI } from '../../../api';
import ApplicationsList from './ApplicationsList';
jest.mock('../../../api/models/Applications');
const applications = {
data: {
results: [
{
id: 1,
name: 'Foo',
summary_fields: {
organization: { name: 'Org 1', id: 10 },
user_capabilities: { edit: true, delete: true },
},
url: '',
organiation: 10,
},
{
id: 2,
name: 'Bar',
summary_fields: {
organization: { name: 'Org 2', id: 20 },
user_capabilities: { edit: true, delete: true },
},
url: '',
organization: 20,
},
],
count: 2,
},
};
const options = { data: { actions: { POST: true } } };
describe('<ApplicationsList/>', () => {
let wrapper;
test('should mount properly', async () => {
ApplicationsAPI.read.mockResolvedValue(applications);
ApplicationsAPI.readOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<ApplicationsList />);
});
await waitForElement(wrapper, 'ApplicationsList', el => el.length > 0);
});
test('should have data fetched and render 2 rows', async () => {
ApplicationsAPI.read.mockResolvedValue(applications);
ApplicationsAPI.readOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<ApplicationsList />);
});
await waitForElement(wrapper, 'ApplicationsList', el => el.length > 0);
expect(wrapper.find('ApplicationListItem').length).toBe(2);
expect(ApplicationsAPI.read).toBeCalled();
expect(ApplicationsAPI.readOptions).toBeCalled();
});
test('should delete item successfully', async () => {
ApplicationsAPI.read.mockResolvedValue(applications);
ApplicationsAPI.readOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<ApplicationsList />);
});
waitForElement(wrapper, 'ApplicationsList', el => el.length > 0);
wrapper
.find('input#select-application-1')
.simulate('change', applications.data.results[0]);
wrapper.update();
expect(wrapper.find('input#select-application-1').prop('checked')).toBe(
true
);
await act(async () =>
wrapper.find('Button[aria-label="Delete"]').prop('onClick')()
);
wrapper.update();
await act(async () =>
wrapper.find('Button[aria-label="confirm delete"]').prop('onClick')()
);
expect(ApplicationsAPI.destroy).toBeCalledWith(
applications.data.results[0].id
);
});
test('should throw content error', async () => {
ApplicationsAPI.read.mockRejectedValue(
new Error({
response: {
config: {
method: 'get',
url: '/api/v2/applications/',
},
data: 'An error occurred',
},
})
);
ApplicationsAPI.readOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<ApplicationsList />);
});
await waitForElement(wrapper, 'ApplicationsList', el => el.length > 0);
expect(wrapper.find('ContentError').length).toBe(1);
});
test('should render deletion error modal', async () => {
ApplicationsAPI.destroy.mockRejectedValue(
new Error({
response: {
config: {
method: 'delete',
url: '/api/v2/applications/',
},
data: 'An error occurred',
},
})
);
ApplicationsAPI.read.mockResolvedValue(applications);
ApplicationsAPI.readOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<ApplicationsList />);
});
waitForElement(wrapper, 'ApplicationsList', el => el.length > 0);
wrapper.find('input#select-application-1').simulate('change', 'a');
wrapper.update();
expect(wrapper.find('input#select-application-1').prop('checked')).toBe(
true
);
await act(async () =>
wrapper.find('Button[aria-label="Delete"]').prop('onClick')()
);
wrapper.update();
await act(async () =>
wrapper.find('Button[aria-label="confirm delete"]').prop('onClick')()
);
wrapper.update();
expect(wrapper.find('ErrorDetail').length).toBe(1);
});
test('should not render add button', async () => {
ApplicationsAPI.read.mockResolvedValue(applications);
ApplicationsAPI.readOptions.mockResolvedValue({
data: { actions: { POST: false } },
});
await act(async () => {
wrapper = mountWithContexts(<ApplicationsList />);
});
waitForElement(wrapper, 'ApplicationsList', el => el.length > 0);
expect(wrapper.find('ToolbarAddButton').length).toBe(0);
});
test('should not render edit button for first list item', async () => {
applications.data.results[0].summary_fields.user_capabilities.edit = false;
ApplicationsAPI.read.mockResolvedValue(applications);
ApplicationsAPI.readOptions.mockResolvedValue({
data: { actions: { POST: false } },
});
await act(async () => {
wrapper = mountWithContexts(<ApplicationsList />);
});
waitForElement(wrapper, 'ApplicationsList', el => el.length > 0);
expect(
wrapper
.find('ApplicationListItem')
.at(0)
.find('PencilAltIcon').length
).toBe(0);
expect(
wrapper
.find('ApplicationListItem')
.at(1)
.find('PencilAltIcon').length
).toBe(1);
});
});

View File

@ -0,0 +1,112 @@
import React from 'react';
import { string, bool, func } from 'prop-types';
import { withI18n } from '@lingui/react';
import {
Button,
DataListAction as _DataListAction,
DataListCheck,
DataListItem,
DataListItemCells,
DataListItemRow,
Tooltip,
} from '@patternfly/react-core';
import { t } from '@lingui/macro';
import { Link } from 'react-router-dom';
import styled from 'styled-components';
import { PencilAltIcon } from '@patternfly/react-icons';
import { formatDateString } from '../../../util/dates';
import { Application } from '../../../types';
import DataListCell from '../../../components/DataListCell';
const DataListAction = styled(_DataListAction)`
align-items: center;
display: grid;
grid-gap: 16px;
grid-template-columns: 40px;
`;
const Label = styled.b`
margin-right: 20px;
`;
function ApplicationListItem({
application,
isSelected,
onSelect,
detailUrl,
i18n,
}) {
const labelId = `check-action-${application.id}`;
return (
<DataListItem
key={application.id}
aria-labelledby={labelId}
id={`${application.id}`}
>
<DataListItemRow>
<DataListCheck
id={`select-application-${application.id}`}
checked={isSelected}
onChange={onSelect}
aria-labelledby={labelId}
/>
<DataListItemCells
dataListCells={[
<DataListCell
key="divider"
aria-label={i18n._(t`application name`)}
>
<Link to={`${detailUrl}`}>
<b>{application.name}</b>
</Link>
</DataListCell>,
<DataListCell
key="organization"
aria-label={i18n._(t`organization name`)}
>
<Link
to={`/organizations/${application.summary_fields.organization.id}`}
>
<b>{application.summary_fields.organization.name}</b>
</Link>
</DataListCell>,
<DataListCell key="modified" aria-label={i18n._(t`last modified`)}>
<Label>{i18n._(t`Last Modified`)}</Label>
<span>{formatDateString(application.modified)}</span>
</DataListCell>,
]}
/>
<DataListAction
aria-label="actions"
aria-labelledby={labelId}
id={labelId}
>
{application.summary_fields.user_capabilities.edit ? (
<Tooltip content={i18n._(t`Edit application`)} position="top">
<Button
aria-label={i18n._(t`Edit application`)}
variant="plain"
component={Link}
to={`/applications/${application.id}/edit`}
>
<PencilAltIcon />
</Button>
</Tooltip>
) : (
''
)}
</DataListAction>
</DataListItemRow>
</DataListItem>
);
}
ApplicationListItem.propTypes = {
application: Application.isRequired,
detailUrl: string.isRequired,
isSelected: bool.isRequired,
onSelect: func.isRequired,
};
export default withI18n()(ApplicationListItem);

View File

@ -0,0 +1,68 @@
import React from 'react';
import { act } from 'react-dom/test-utils';
import { mountWithContexts } from '../../../../testUtils/enzymeHelpers';
import ApplicationListItem from './ApplicationListItem';
describe('<ApplicationListItem/>', () => {
let wrapper;
const application = {
id: 1,
name: 'Foo',
summary_fields: {
organization: { id: 2, name: 'Organization' },
user_capabilities: { edit: true },
},
};
test('should mount successfully', async () => {
await act(async () => {
wrapper = mountWithContexts(
<ApplicationListItem
application={application}
detailUrl="/organizations/2/details"
isSelected={false}
onSelect={() => {}}
/>
);
});
expect(wrapper.find('ApplicationListItem').length).toBe(1);
});
test('should render the proper data', async () => {
await act(async () => {
wrapper = mountWithContexts(
<ApplicationListItem
application={application}
detailUrl="/organizations/2/details"
isSelected={false}
onSelect={() => {}}
/>
);
});
expect(
wrapper.find('DataListCell[aria-label="application name"]').text()
).toBe('Foo');
expect(
wrapper.find('DataListCell[aria-label="organization name"]').text()
).toBe('Organization');
expect(wrapper.find('input#select-application-1').prop('checked')).toBe(
false
);
expect(wrapper.find('PencilAltIcon').length).toBe(1);
});
test('should be checked', async () => {
await act(async () => {
wrapper = mountWithContexts(
<ApplicationListItem
application={application}
detailUrl="/organizations/2/details"
isSelected
onSelect={() => {}}
/>
);
});
expect(wrapper.find('input#select-application-1').prop('checked')).toBe(
true
);
});
});

View File

@ -1,15 +1,188 @@
import React from 'react';
import { Card, PageSection } from '@patternfly/react-core';
import React, { useCallback, useEffect } from 'react';
import { t } from '@lingui/macro';
import { withI18n } from '@lingui/react';
import { useLocation, useRouteMatch } from 'react-router-dom';
import { Card, PageSection } from '@patternfly/react-core';
import { getQSConfig, parseQueryString } from '../../../util/qs';
import useRequest, { useDeleteItems } from '../../../util/useRequest';
import ErrorDetail from '../../../components/ErrorDetail';
import AlertModal from '../../../components/AlertModal';
import DatalistToolbar from '../../../components/DataListToolbar';
import { ApplicationsAPI } from '../../../api';
import PaginatedDataList, {
ToolbarDeleteButton,
ToolbarAddButton,
} from '../../../components/PaginatedDataList';
import useSelected from '../../../util/useSelected';
import ApplicationListItem from './ApplicationListItem';
const QS_CONFIG = getQSConfig('applications', {
page: 1,
page_size: 20,
order_by: 'name',
});
function ApplicationsList({ i18n }) {
const location = useLocation();
const match = useRouteMatch();
const {
isLoading,
error,
request: fetchApplications,
result: { applications, itemCount, actions },
} = useRequest(
useCallback(async () => {
const params = parseQueryString(QS_CONFIG, location.search);
const [response, actionsResponse] = await Promise.all([
ApplicationsAPI.read(params),
ApplicationsAPI.readOptions(),
]);
return {
applications: response.data.results,
itemCount: response.data.count,
actions: actionsResponse.data.actions,
};
}, [location]),
{
applications: [],
itemCount: 0,
actions: {},
}
);
useEffect(() => {
fetchApplications();
}, [fetchApplications]);
const { selected, isAllSelected, handleSelect, setSelected } = useSelected(
applications
);
const {
isLoading: deleteLoading,
deletionError,
deleteItems: handleDeleteApplications,
clearDeletionError,
} = useDeleteItems(
useCallback(async () => {
await Promise.all(selected.map(({ id }) => ApplicationsAPI.destroy(id)));
}, [selected]),
{
qsConfig: QS_CONFIG,
allItemsSelected: isAllSelected,
fetchItems: fetchApplications,
}
);
const handleDelete = async () => {
await handleDeleteApplications();
setSelected([]);
};
const canAdd = actions && actions.POST;
function ApplicationsList() {
return (
<>
<PageSection>
<Card>
<div>Applications List</div>
<PaginatedDataList
contentError={error}
hasContentLoading={isLoading || deleteLoading}
items={applications}
itemCount={itemCount}
pluralizedItemName={i18n._(t`Applications`)}
qsConfig={QS_CONFIG}
onRowClick={handleSelect}
toolbarSearchColumns={[
{
name: i18n._(t`Name`),
key: 'name',
isDefault: true,
},
{
name: i18n._(t`Description`),
key: 'description',
},
]}
toolbarSortColumns={[
{
name: i18n._(t`Name`),
key: 'name',
},
{
name: i18n._(t`Created`),
key: 'created',
},
{
name: i18n._(t`Organization`),
key: 'organization',
},
{
name: i18n._(t`Description`),
key: 'description',
},
]}
renderToolbar={props => (
<DatalistToolbar
{...props}
showSelectAll
showExpandCollapse
isAllSelected={isAllSelected}
onSelectAll={isSelected =>
setSelected(isSelected ? [...applications] : [])
}
qsConfig={QS_CONFIG}
additionalControls={[
...(canAdd
? [
<ToolbarAddButton
key="add"
linkTo={`${match.url}/add`}
/>,
]
: []),
<ToolbarDeleteButton
key="delete"
onDelete={handleDelete}
itemsToDelete={selected}
pluralizedItemName={i18n._(t`Applications`)}
/>,
]}
/>
)}
renderItem={application => (
<ApplicationListItem
key={application.id}
value={application.name}
application={application}
detailUrl={`${match.url}/${application.id}/details`}
onSelect={() => handleSelect(application)}
isSelected={selected.some(row => row.id === application.id)}
/>
)}
emptyStateControls={
canAdd && (
<ToolbarAddButton key="add" linkTo={`${match.url}/add`} />
)
}
/>
</Card>
</PageSection>
<AlertModal
isOpen={deletionError}
variant="error"
title={i18n._(t`Error!`)}
onClose={clearDeletionError}
>
{i18n._(t`Failed to delete one or more applications.`)}
<ErrorDetail error={deletionError} />
</AlertModal>
</>
);
}
export default ApplicationsList;
export default withI18n()(ApplicationsList);

View File

@ -42,6 +42,18 @@ export const AccessRecord = shape({
type: string,
});
export const Application = shape({
id: number.isRequired,
name: string.isRequired,
organization: number,
summary_fields: shape({
organization: shape({
id: number.isRequired,
name: string.isRequired,
}),
}),
});
export const Organization = shape({
id: number.isRequired,
name: string.isRequired,