Adds Copy Button to Inventory List and Project List

This commit is contained in:
Alex Corey
2020-05-06 14:00:47 -04:00
parent 3aa6e8a457
commit d566b465aa
7 changed files with 435 additions and 176 deletions

View File

@@ -167,6 +167,7 @@ function InventoryList({ i18n }) {
key={inventory.id} key={inventory.id}
value={inventory.name} value={inventory.name}
inventory={inventory} inventory={inventory}
fetchInventories={fetchInventories}
detailUrl={ detailUrl={
inventory.kind === 'smart' inventory.kind === 'smart'
? `${match.url}/smart_inventory/${inventory.id}/details` ? `${match.url}/smart_inventory/${inventory.id}/details`
@@ -182,6 +183,7 @@ function InventoryList({ i18n }) {
<AlertModal <AlertModal
isOpen={deletionError} isOpen={deletionError}
variant="error" variant="error"
aria-label={i18n._(t`Deletion Error`)}
title={i18n._(t`Error!`)} title={i18n._(t`Error!`)}
onClose={clearDeletionError} onClose={clearDeletionError}
> >

View File

@@ -279,7 +279,7 @@ describe('<InventoryList />', () => {
}); });
wrapper.update(); wrapper.update();
const modal = wrapper.find('Modal'); const modal = wrapper.find('Modal[aria-label="Deletion Error"]');
expect(modal).toHaveLength(1); expect(modal).toHaveLength(1);
expect(modal.prop('title')).toEqual('Error!'); expect(modal.prop('title')).toEqual('Error!');
}); });

View File

@@ -1,4 +1,4 @@
import React from 'react'; import React, { useState, useCallback } from 'react';
import { string, bool, func } from 'prop-types'; import { string, bool, func } from 'prop-types';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { import {
@@ -16,26 +16,41 @@ import { t } from '@lingui/macro';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import styled from 'styled-components'; import styled from 'styled-components';
import { PencilAltIcon } from '@patternfly/react-icons'; import { PencilAltIcon } from '@patternfly/react-icons';
import { timeOfDay } from '@util/dates';
import { InventoriesAPI } from '@api';
import { Inventory } from '@types'; import { Inventory } from '@types';
import CopyButton from '../../../components/CopyButton/CopyButton';
const DataListAction = styled(_DataListAction)` const DataListAction = styled(_DataListAction)`
align-items: center; align-items: center;
display: grid; display: grid;
grid-gap: 16px; grid-gap: 16px;
grid-template-columns: 40px; grid-template-columns: repeat(2, 40px);
`; `;
class InventoryListItem extends React.Component { function InventoryListItem({
static propTypes = { inventory,
isSelected,
onSelect,
detailUrl,
i18n,
fetchInventories,
}) {
InventoryListItem.propTypes = {
inventory: Inventory.isRequired, inventory: Inventory.isRequired,
detailUrl: string.isRequired, detailUrl: string.isRequired,
isSelected: bool.isRequired, isSelected: bool.isRequired,
onSelect: func.isRequired, onSelect: func.isRequired,
}; };
const [isDisabled, setIsDisabled] = useState(false);
const copyInventory = useCallback(async () => {
await InventoriesAPI.copy(inventory.id, {
name: `${inventory.name} @ ${timeOfDay()}`,
});
await fetchInventories();
}, [inventory.id, inventory.name, fetchInventories]);
render() {
const { inventory, isSelected, onSelect, detailUrl, i18n } = this.props;
const labelId = `check-action-${inventory.id}`; const labelId = `check-action-${inventory.id}`;
return ( return (
<DataListItem <DataListItem
@@ -72,6 +87,7 @@ class InventoryListItem extends React.Component {
{inventory.summary_fields.user_capabilities.edit ? ( {inventory.summary_fields.user_capabilities.edit ? (
<Tooltip content={i18n._(t`Edit Inventory`)} position="top"> <Tooltip content={i18n._(t`Edit Inventory`)} position="top">
<Button <Button
isDisabled={isDisabled}
aria-label={i18n._(t`Edit Inventory`)} aria-label={i18n._(t`Edit Inventory`)}
variant="plain" variant="plain"
component={Link} component={Link}
@@ -85,10 +101,21 @@ class InventoryListItem extends React.Component {
) : ( ) : (
'' ''
)} )}
{inventory.summary_fields.user_capabilities.copy && (
<CopyButton
copyItem={copyInventory}
isDisabled={isDisabled}
onLoading={() => setIsDisabled(true)}
onDoneLoading={() => setIsDisabled(false)}
helperText={{
tooltip: i18n._(t`Copy Inventory`),
errorMessage: i18n._(t`Failed to copy inventory.`),
}}
/>
)}
</DataListAction> </DataListAction>
</DataListItemRow> </DataListItemRow>
</DataListItem> </DataListItem>
); );
}
} }
export default withI18n()(InventoryListItem); export default withI18n()(InventoryListItem);

View File

@@ -1,9 +1,13 @@
import React from 'react'; import React from 'react';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { I18nProvider } from '@lingui/react'; import { I18nProvider } from '@lingui/react';
import { act } from 'react-dom/test-utils';
import { mountWithContexts } from '@testUtils/enzymeHelpers'; import { mountWithContexts } from '@testUtils/enzymeHelpers';
import { InventoriesAPI } from '@api';
import InventoryListItem from './InventoryListItem'; import InventoryListItem from './InventoryListItem';
jest.mock('@api/models/Inventories');
describe('<InventoryListItem />', () => { describe('<InventoryListItem />', () => {
test('initially renders succesfully', () => { test('initially renders succesfully', () => {
mountWithContexts( mountWithContexts(
@@ -85,4 +89,104 @@ describe('<InventoryListItem />', () => {
); );
expect(wrapper.find('PencilAltIcon').exists()).toBeFalsy(); expect(wrapper.find('PencilAltIcon').exists()).toBeFalsy();
}); });
test('should call api to copy inventory', async () => {
InventoriesAPI.copy.mockResolvedValue();
const wrapper = mountWithContexts(
<I18nProvider>
<MemoryRouter initialEntries={['/inventories']} initialIndex={0}>
<InventoryListItem
inventory={{
id: 1,
name: 'Inventory',
summary_fields: {
organization: {
id: 1,
name: 'Default',
},
user_capabilities: {
edit: false,
copy: true,
},
},
}}
detailUrl="/inventories/inventory/1"
isSelected
onSelect={() => {}}
/>
</MemoryRouter>
</I18nProvider>
);
await act(async () =>
wrapper.find('Button[aria-label="Copy"]').prop('onClick')()
);
expect(InventoriesAPI.copy).toHaveBeenCalled();
jest.clearAllMocks();
});
test('should render proper alert modal on copy error', async () => {
InventoriesAPI.copy.mockRejectedValue(new Error());
const wrapper = mountWithContexts(
<I18nProvider>
<MemoryRouter initialEntries={['/inventories']} initialIndex={0}>
<InventoryListItem
inventory={{
id: 1,
name: 'Inventory',
summary_fields: {
organization: {
id: 1,
name: 'Default',
},
user_capabilities: {
edit: false,
copy: true,
},
},
}}
detailUrl="/inventories/inventory/1"
isSelected
onSelect={() => {}}
/>
</MemoryRouter>
</I18nProvider>
);
await act(async () =>
wrapper.find('Button[aria-label="Copy"]').prop('onClick')()
);
wrapper.update();
expect(wrapper.find('Modal').prop('isOpen')).toBe(true);
jest.clearAllMocks();
});
test('should not render copy button', async () => {
const wrapper = mountWithContexts(
<I18nProvider>
<MemoryRouter initialEntries={['/inventories']} initialIndex={0}>
<InventoryListItem
inventory={{
id: 1,
name: 'Inventory',
summary_fields: {
organization: {
id: 1,
name: 'Default',
},
user_capabilities: {
edit: false,
copy: false,
},
},
}}
detailUrl="/inventories/inventory/1"
isSelected
onSelect={() => {}}
/>
</MemoryRouter>
</I18nProvider>
);
expect(wrapper.find('CopyButton').length).toBe(0);
});
}); });

View File

@@ -170,6 +170,7 @@ function ProjectList({ i18n }) {
)} )}
renderItem={o => ( renderItem={o => (
<ProjectListItem <ProjectListItem
fetchProjects={fetchProjects}
key={o.id} key={o.id}
project={o} project={o}
detailUrl={`${match.url}/${o.id}`} detailUrl={`${match.url}/${o.id}`}
@@ -188,6 +189,7 @@ function ProjectList({ i18n }) {
<AlertModal <AlertModal
isOpen={deletionError} isOpen={deletionError}
variant="error" variant="error"
aria-label={i18n._(t`Deletion Error`)}
title={i18n._(t`Error!`)} title={i18n._(t`Error!`)}
onClose={clearDeletionError} onClose={clearDeletionError}
> >

View File

@@ -1,4 +1,4 @@
import React, { Fragment } from 'react'; import React, { Fragment, useState, useCallback } from 'react';
import { string, bool, func } from 'prop-types'; import { string, bool, func } from 'prop-types';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { import {
@@ -16,35 +16,45 @@ import { t } from '@lingui/macro';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { PencilAltIcon, SyncIcon } from '@patternfly/react-icons'; import { PencilAltIcon, SyncIcon } from '@patternfly/react-icons';
import styled from 'styled-components'; import styled from 'styled-components';
import { timeOfDay } from '@util/dates';
import { ProjectsAPI } from '@api';
import ClipboardCopyButton from '@components/ClipboardCopyButton'; import ClipboardCopyButton from '@components/ClipboardCopyButton';
import ProjectSyncButton from '../shared/ProjectSyncButton';
import StatusIcon from '@components/StatusIcon'; import StatusIcon from '@components/StatusIcon';
import { toTitleCase } from '@util/strings'; import { toTitleCase } from '@util/strings';
import CopyButton from '@components/CopyButton';
import ProjectSyncButton from '../shared/ProjectSyncButton';
import { Project } from '@types'; import { Project } from '@types';
const DataListAction = styled(_DataListAction)` const DataListAction = styled(_DataListAction)`
align-items: center; align-items: center;
display: grid; display: grid;
grid-gap: 16px; grid-gap: 16px;
grid-template-columns: repeat(2, 40px); grid-template-columns: repeat(3, 40px);
`; `;
class ProjectListItem extends React.Component { function ProjectListItem({
static propTypes = { project,
isSelected,
onSelect,
detailUrl,
i18n,
fetchProjects,
}) {
const [isDisabled, setIsDisabled] = useState(false);
ProjectListItem.propTypes = {
project: Project.isRequired, project: Project.isRequired,
detailUrl: string.isRequired, detailUrl: string.isRequired,
isSelected: bool.isRequired, isSelected: bool.isRequired,
onSelect: func.isRequired, onSelect: func.isRequired,
}; };
constructor(props) { const copyProject = useCallback(async () => {
super(props); await ProjectsAPI.copy(project.id, {
name: `${project.name} @ ${timeOfDay()}`,
});
await fetchProjects();
}, [project.id, project.name, fetchProjects]);
this.generateLastJobTooltip = this.generateLastJobTooltip.bind(this); const generateLastJobTooltip = job => {
}
generateLastJobTooltip = job => {
const { i18n } = this.props;
return ( return (
<Fragment> <Fragment>
<div>{i18n._(t`MOST RECENT SYNC`)}</div> <div>{i18n._(t`MOST RECENT SYNC`)}</div>
@@ -63,8 +73,6 @@ class ProjectListItem extends React.Component {
); );
}; };
render() {
const { project, isSelected, onSelect, detailUrl, i18n } = this.props;
const labelId = `check-action-${project.id}`; const labelId = `check-action-${project.id}`;
return ( return (
<DataListItem <DataListItem
@@ -85,7 +93,7 @@ class ProjectListItem extends React.Component {
{project.summary_fields.last_job && ( {project.summary_fields.last_job && (
<Tooltip <Tooltip
position="top" position="top"
content={this.generateLastJobTooltip( content={generateLastJobTooltip(
project.summary_fields.last_job project.summary_fields.last_job
)} )}
key={project.summary_fields.last_job.id} key={project.summary_fields.last_job.id}
@@ -132,8 +140,8 @@ class ProjectListItem extends React.Component {
<ProjectSyncButton projectId={project.id}> <ProjectSyncButton projectId={project.id}>
{handleSync => ( {handleSync => (
<Button <Button
isDisabled={isDisabled}
aria-label={i18n._(t`Sync Project`)} aria-label={i18n._(t`Sync Project`)}
css="grid-column: 1"
variant="plain" variant="plain"
onClick={handleSync} onClick={handleSync}
> >
@@ -148,8 +156,8 @@ class ProjectListItem extends React.Component {
{project.summary_fields.user_capabilities.edit ? ( {project.summary_fields.user_capabilities.edit ? (
<Tooltip content={i18n._(t`Edit Project`)} position="top"> <Tooltip content={i18n._(t`Edit Project`)} position="top">
<Button <Button
isDisabled={isDisabled}
aria-label={i18n._(t`Edit Project`)} aria-label={i18n._(t`Edit Project`)}
css="grid-column: 2"
variant="plain" variant="plain"
component={Link} component={Link}
to={`/projects/${project.id}/edit`} to={`/projects/${project.id}/edit`}
@@ -160,10 +168,21 @@ class ProjectListItem extends React.Component {
) : ( ) : (
'' ''
)} )}
{project.summary_fields.user_capabilities.copy && (
<CopyButton
copyItem={copyProject}
isDisabled={isDisabled}
onLoading={() => setIsDisabled(true)}
onDoneLoading={() => setIsDisabled(false)}
helperText={{
tooltip: i18n._(t`Copy Project`),
errorMessage: i18n._(t`Failed to copy project.`),
}}
/>
)}
</DataListAction> </DataListAction>
</DataListItemRow> </DataListItemRow>
</DataListItem> </DataListItem>
); );
}
} }
export default withI18n()(ProjectListItem); export default withI18n()(ProjectListItem);

View File

@@ -1,8 +1,11 @@
import React from 'react'; import React from 'react';
import { mountWithContexts } from '@testUtils/enzymeHelpers'; import { mountWithContexts } from '@testUtils/enzymeHelpers';
import { act } from 'react-dom/test-utils';
import ProjectsListItem from './ProjectListItem'; import ProjectsListItem from './ProjectListItem';
import { ProjectsAPI } from '@api';
jest.mock('@api/models/Projects');
describe('<ProjectsListItem />', () => { describe('<ProjectsListItem />', () => {
test('launch button shown to users with start capabilities', () => { test('launch button shown to users with start capabilities', () => {
@@ -32,6 +35,7 @@ describe('<ProjectsListItem />', () => {
); );
expect(wrapper.find('ProjectSyncButton').exists()).toBeTruthy(); expect(wrapper.find('ProjectSyncButton').exists()).toBeTruthy();
}); });
test('launch button hidden from users without start capabilities', () => { test('launch button hidden from users without start capabilities', () => {
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<ProjectsListItem <ProjectsListItem
@@ -59,6 +63,7 @@ describe('<ProjectsListItem />', () => {
); );
expect(wrapper.find('ProjectSyncButton').exists()).toBeFalsy(); expect(wrapper.find('ProjectSyncButton').exists()).toBeFalsy();
}); });
test('edit button shown to users with edit capabilities', () => { test('edit button shown to users with edit capabilities', () => {
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<ProjectsListItem <ProjectsListItem
@@ -86,6 +91,7 @@ describe('<ProjectsListItem />', () => {
); );
expect(wrapper.find('PencilAltIcon').exists()).toBeTruthy(); expect(wrapper.find('PencilAltIcon').exists()).toBeTruthy();
}); });
test('edit button hidden from users without edit capabilities', () => { test('edit button hidden from users without edit capabilities', () => {
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<ProjectsListItem <ProjectsListItem
@@ -113,4 +119,103 @@ describe('<ProjectsListItem />', () => {
); );
expect(wrapper.find('PencilAltIcon').exists()).toBeFalsy(); expect(wrapper.find('PencilAltIcon').exists()).toBeFalsy();
}); });
test('should call api to copy project', async () => {
ProjectsAPI.copy.mockResolvedValue();
const wrapper = mountWithContexts(
<ProjectsListItem
isSelected={false}
detailUrl="/project/1"
onSelect={() => {}}
project={{
id: 1,
name: 'Project 1',
url: '/api/v2/projects/1',
type: 'project',
scm_type: 'git',
scm_revision: '7788f7erga0jijodfgsjisiodf98sdga9hg9a98gaf',
summary_fields: {
last_job: {
id: 9000,
status: 'successful',
},
user_capabilities: {
edit: false,
copy: true,
},
},
}}
/>
);
await act(async () =>
wrapper.find('Button[aria-label="Copy"]').prop('onClick')()
);
expect(ProjectsAPI.copy).toHaveBeenCalled();
jest.clearAllMocks();
});
test('should render proper alert modal on copy error', async () => {
ProjectsAPI.copy.mockRejectedValue(new Error());
const wrapper = mountWithContexts(
<ProjectsListItem
isSelected={false}
detailUrl="/project/1"
onSelect={() => {}}
project={{
id: 1,
name: 'Project 1',
url: '/api/v2/projects/1',
type: 'project',
scm_type: 'git',
scm_revision: '7788f7erga0jijodfgsjisiodf98sdga9hg9a98gaf',
summary_fields: {
last_job: {
id: 9000,
status: 'successful',
},
user_capabilities: {
edit: false,
copy: true,
},
},
}}
/>
);
await act(async () =>
wrapper.find('Button[aria-label="Copy"]').prop('onClick')()
);
wrapper.update();
expect(wrapper.find('Modal').prop('isOpen')).toBe(true);
jest.clearAllMocks();
});
test('should not render copy button', async () => {
const wrapper = mountWithContexts(
<ProjectsListItem
isSelected={false}
detailUrl="/foo/bar"
onSelect={() => {}}
project={{
id: 1,
name: 'Project 1',
url: '/api/v2/projects/1',
type: 'project',
scm_type: 'git',
scm_revision: '7788f7erga0jijodfgsjisiodf98sdga9hg9a98gaf',
summary_fields: {
last_job: {
id: 9000,
status: 'successful',
},
user_capabilities: {
edit: false,
copy: false,
},
},
}}
/>
);
expect(wrapper.find('CopyButton').length).toBe(0);
});
}); });