1
0
mirror of https://github.com/ansible/awx.git synced 2024-10-27 09:25:10 +03:00

Merge pull request #5119 from mabashian/ui-next-teams

Adds basic teams list and add/edit forms

Reviewed-by: https://github.com/apps/softwarefactory-project-zuul
This commit is contained in:
softwarefactory-project-zuul[bot] 2019-11-08 21:28:04 +00:00 committed by GitHub
commit 4746bc7c09
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 1545 additions and 60 deletions

View File

@ -1,6 +1,7 @@
import { DataListCheck as PFDataListCheck } from '@patternfly/react-core';
import styled from 'styled-components';
PFDataListCheck.displayName = 'PFDataListCheck';
export default styled(PFDataListCheck)`
padding-top: 18px;
@media screen and (min-width: 768px) {

View File

@ -12,13 +12,13 @@ const mockMe = {
is_system_auditor: false,
};
describe.only('<Host />', () => {
describe('<Host />', () => {
test('initially renders succesfully', () => {
HostsAPI.readDetail.mockResolvedValue({ data: mockDetails });
mountWithContexts(<Host setBreadcrumb={() => {}} me={mockMe} />);
});
test('should show content error when user attempts to navigate to erroneous route', async done => {
test('should show content error when user attempts to navigate to erroneous route', async () => {
const history = createMemoryHistory({
initialEntries: ['/hosts/1/foobar'],
});
@ -41,6 +41,5 @@ describe.only('<Host />', () => {
}
);
await waitForElement(wrapper, 'ContentError', el => el.length === 1);
done();
});
});

View File

@ -175,7 +175,8 @@ class HostsList extends Component {
const canAdd =
actions && Object.prototype.hasOwnProperty.call(actions, 'POST');
const isAllSelected = selected.length === hosts.length;
const isAllSelected =
selected.length > 0 && selected.length === hosts.length;
return (
<Fragment>

View File

@ -11,7 +11,7 @@ InventoriesAPI.readDetail.mockResolvedValue({
data: mockInventory,
});
describe.only('<Inventory />', () => {
describe('<Inventory />', () => {
test('initially renders succesfully', async done => {
const wrapper = mountWithContexts(
<Inventory setBreadcrumb={() => {}} match={{ params: { id: 1 } }} />
@ -29,7 +29,7 @@ describe.only('<Inventory />', () => {
await waitForElement(wrapper, '.pf-c-tabs__item', el => el.length === 6);
done();
});
test('should show content error when user attempts to navigate to erroneous route', async done => {
test('should show content error when user attempts to navigate to erroneous route', async () => {
const history = createMemoryHistory({
initialEntries: ['/inventories/inventory/1/foobar'],
});
@ -49,6 +49,5 @@ describe.only('<Inventory />', () => {
},
});
await waitForElement(wrapper, 'ContentError', el => el.length === 1);
done();
});
});

View File

@ -174,7 +174,8 @@ class InventoriesList extends Component {
const { match, i18n } = this.props;
const canAdd =
actions && Object.prototype.hasOwnProperty.call(actions, 'POST');
const isAllSelected = selected.length === inventories.length;
const isAllSelected =
selected.length > 0 && selected.length === inventories.length;
return (
<PageSection>
<Card>

View File

@ -11,7 +11,7 @@ InventoriesAPI.readDetail.mockResolvedValue({
data: mockSmartInventory,
});
describe.only('<SmartInventory />', () => {
describe('<SmartInventory />', () => {
test('initially renders succesfully', async done => {
const wrapper = mountWithContexts(
<SmartInventory setBreadcrumb={() => {}} match={{ params: { id: 1 } }} />
@ -29,7 +29,7 @@ describe.only('<SmartInventory />', () => {
await waitForElement(wrapper, '.pf-c-tabs__item', el => el.length === 4);
done();
});
test('should show content error when user attempts to navigate to erroneous route', async done => {
test('should show content error when user attempts to navigate to erroneous route', async () => {
const history = createMemoryHistory({
initialEntries: ['/inventories/smart_inventory/1/foobar'],
});
@ -52,6 +52,5 @@ describe.only('<SmartInventory />', () => {
}
);
await waitForElement(wrapper, 'ContentError', el => el.length === 1);
done();
});
});

View File

@ -33,7 +33,7 @@ async function getOrganizations(params) {
};
}
describe.only('<Organization />', () => {
describe('<Organization />', () => {
test('initially renders succesfully', () => {
OrganizationsAPI.readDetail.mockResolvedValue({ data: mockOrganization });
OrganizationsAPI.read.mockImplementation(getOrganizations);
@ -77,7 +77,7 @@ describe.only('<Organization />', () => {
done();
});
test('should show content error when user attempts to navigate to erroneous route', async done => {
test('should show content error when user attempts to navigate to erroneous route', async () => {
const history = createMemoryHistory({
initialEntries: ['/organizations/1/foobar'],
});
@ -100,6 +100,5 @@ describe.only('<Organization />', () => {
}
);
await waitForElement(wrapper, 'ContentError', el => el.length === 1);
done();
});
});

View File

@ -1,13 +1,10 @@
import React from 'react';
import { createMemoryHistory } from 'history';
import {
mountWithContexts,
waitForElement,
} from '../../../../testUtils/enzymeHelpers';
import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers';
import OrganizationAdd from './OrganizationAdd';
import { OrganizationsAPI } from '../../../api';
import { OrganizationsAPI } from '@api';
jest.mock('../../../api');
jest.mock('@api');
describe('<OrganizationAdd />', () => {
test('handleSubmit should post to api', () => {

View File

@ -24,7 +24,7 @@ async function getOrganizations() {
};
}
describe.only('<Project />', () => {
describe('<Project />', () => {
test('initially renders succesfully', () => {
ProjectsAPI.readDetail.mockResolvedValue({ data: mockDetails });
OrganizationsAPI.read.mockImplementation(getOrganizations);
@ -68,7 +68,7 @@ describe.only('<Project />', () => {
done();
});
test('should show content error when user attempts to navigate to erroneous route', async done => {
test('should show content error when user attempts to navigate to erroneous route', async () => {
const history = createMemoryHistory({
initialEntries: ['/projects/1/foobar'],
});
@ -91,6 +91,5 @@ describe.only('<Project />', () => {
}
);
await waitForElement(wrapper, 'ContentError', el => el.length === 1);
done();
});
});

View File

@ -141,7 +141,8 @@ class ProjectsList extends Component {
const canAdd =
actions && Object.prototype.hasOwnProperty.call(actions, 'POST');
const isAllSelected = selected.length === projects.length;
const isAllSelected =
selected.length > 0 && selected.length === projects.length;
return (
<Fragment>

View File

@ -0,0 +1,178 @@
import React, { Component } from 'react';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import { Switch, Route, withRouter, Redirect, Link } from 'react-router-dom';
import {
Card,
CardHeader as PFCardHeader,
PageSection,
} from '@patternfly/react-core';
import styled from 'styled-components';
import CardCloseButton from '@components/CardCloseButton';
import RoutedTabs from '@components/RoutedTabs';
import ContentError from '@components/ContentError';
import TeamDetail from './TeamDetail';
import TeamEdit from './TeamEdit';
import { TeamsAPI } from '@api';
const CardHeader = styled(PFCardHeader)`
--pf-c-card--first-child--PaddingTop: 0;
--pf-c-card--child--PaddingLeft: 0;
--pf-c-card--child--PaddingRight: 0;
position: relative;
`;
class Team extends Component {
constructor(props) {
super(props);
this.state = {
team: null,
hasContentLoading: true,
contentError: null,
isInitialized: false,
};
this.loadTeam = this.loadTeam.bind(this);
}
async componentDidMount() {
await this.loadTeam();
this.setState({ isInitialized: true });
}
async componentDidUpdate(prevProps) {
const { location, match } = this.props;
const url = `/teams/${match.params.id}/`;
if (
prevProps.location.pathname.startsWith(url) &&
prevProps.location !== location &&
location.pathname === `${url}details`
) {
await this.loadTeam();
}
}
async loadTeam() {
const { match, setBreadcrumb } = this.props;
const id = parseInt(match.params.id, 10);
this.setState({ contentError: null, hasContentLoading: true });
try {
const { data } = await TeamsAPI.readDetail(id);
setBreadcrumb(data);
this.setState({ team: data });
} catch (err) {
this.setState({ contentError: err });
} finally {
this.setState({ hasContentLoading: false });
}
}
render() {
const { location, match, history, i18n } = this.props;
const { team, contentError, hasContentLoading, isInitialized } = this.state;
const tabsArray = [
{ name: i18n._(t`Details`), link: `${match.url}/details`, id: 0 },
{ name: i18n._(t`Users`), link: `${match.url}/users`, id: 1 },
{ name: i18n._(t`Access`), link: `${match.url}/access`, id: 2 },
];
let cardHeader = (
<CardHeader style={{ padding: 0 }}>
<RoutedTabs
match={match}
history={history}
labeltext={i18n._(t`Team detail tabs`)}
tabsArray={tabsArray}
/>
<CardCloseButton linkTo="/teams" />
</CardHeader>
);
if (!isInitialized) {
cardHeader = null;
}
if (!match) {
cardHeader = null;
}
if (location.pathname.endsWith('edit')) {
cardHeader = null;
}
if (!hasContentLoading && contentError) {
return (
<PageSection>
<Card className="awx-c-card">
<ContentError error={contentError}>
{contentError.response.status === 404 && (
<span>
{i18n._(`Team not found.`)}{' '}
<Link to="/teams">{i18n._(`View all Teams.`)}</Link>
</span>
)}
</ContentError>
</Card>
</PageSection>
);
}
return (
<PageSection>
<Card className="awx-c-card">
{cardHeader}
<Switch>
<Redirect from="/teams/:id" to="/teams/:id/details" exact />
{team && (
<Route
path="/teams/:id/edit"
render={() => <TeamEdit match={match} team={team} />}
/>
)}
{team && (
<Route
path="/teams/:id/details"
render={() => <TeamDetail match={match} team={team} />}
/>
)}
{team && (
<Route
path="/teams/:id/users"
render={() => <span>Coming soon :)</span>}
/>
)}
{team && (
<Route
path="/teams/:id/access"
render={() => <span>Coming soon :)</span>}
/>
)}
<Route
key="not-found"
path="*"
render={() =>
!hasContentLoading && (
<ContentError isNotFound>
{match.params.id && (
<Link to={`/teams/${match.params.id}/details`}>
{i18n._(`View Team Details`)}
</Link>
)}
</ContentError>
)
}
/>
,
</Switch>
</Card>
</PageSection>
);
}
}
export default withI18n()(withRouter(Team));
export { Team as _Team };

View File

@ -0,0 +1,67 @@
import React from 'react';
import { createMemoryHistory } from 'history';
import { TeamsAPI } from '@api';
import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers';
import Team from './Team';
jest.mock('@api');
const mockMe = {
is_super_user: true,
is_system_auditor: false,
};
const mockTeam = {
id: 1,
name: 'Test Team',
summary_fields: {
organization: {
id: 1,
name: 'Default',
},
},
};
async function getTeams() {
return {
count: 1,
next: null,
previous: null,
data: {
results: [mockTeam],
},
};
}
describe('<Team />', () => {
test('initially renders succesfully', () => {
TeamsAPI.readDetail.mockResolvedValue({ data: mockTeam });
TeamsAPI.read.mockImplementation(getTeams);
mountWithContexts(<Team setBreadcrumb={() => {}} me={mockMe} />);
});
test('should show content error when user attempts to navigate to erroneous route', async () => {
const history = createMemoryHistory({
initialEntries: ['/teams/1/foobar'],
});
const wrapper = mountWithContexts(
<Team setBreadcrumb={() => {}} me={mockMe} />,
{
context: {
router: {
history,
route: {
location: history.location,
match: {
params: { id: 1 },
url: '/teams/1/foobar',
path: '/teams/1/foobar',
},
},
},
},
}
);
await waitForElement(wrapper, 'ContentError', el => el.length === 1);
});
});

View File

@ -0,0 +1,73 @@
import React from 'react';
import { withRouter } from 'react-router-dom';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import {
PageSection,
Card,
CardHeader,
CardBody,
Tooltip,
} from '@patternfly/react-core';
import { TeamsAPI } from '@api';
import { Config } from '@contexts/Config';
import CardCloseButton from '@components/CardCloseButton';
import TeamForm from '../shared/TeamForm';
class TeamAdd extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleCancel = this.handleCancel.bind(this);
this.state = { error: '' };
}
async handleSubmit(values) {
const { history } = this.props;
try {
const { data: response } = await TeamsAPI.create(values);
history.push(`/teams/${response.id}`);
} catch (error) {
this.setState({ error });
}
}
handleCancel() {
const { history } = this.props;
history.push('/teams');
}
render() {
const { error } = this.state;
const { i18n } = this.props;
return (
<PageSection>
<Card>
<CardHeader className="at-u-textRight">
<Tooltip content={i18n._(t`Close`)} position="top">
<CardCloseButton onClick={this.handleCancel} />
</Tooltip>
</CardHeader>
<CardBody>
<Config>
{({ me }) => (
<TeamForm
handleSubmit={this.handleSubmit}
handleCancel={this.handleCancel}
me={me || {}}
/>
)}
</Config>
{error ? <div>error</div> : ''}
</CardBody>
</Card>
</PageSection>
);
}
}
export { TeamAdd as _TeamAdd };
export default withI18n()(withRouter(TeamAdd));

View File

@ -0,0 +1,65 @@
import React from 'react';
import { createMemoryHistory } from 'history';
import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers';
import TeamAdd from './TeamAdd';
import { TeamsAPI } from '@api';
jest.mock('@api');
describe('<TeamAdd />', () => {
test('handleSubmit should post to api', () => {
const wrapper = mountWithContexts(<TeamAdd />);
const updatedTeamData = {
name: 'new name',
description: 'new description',
organization: 1,
};
wrapper.find('TeamForm').prop('handleSubmit')(updatedTeamData);
expect(TeamsAPI.create).toHaveBeenCalledWith(updatedTeamData);
});
test('should navigate to teams list when cancel is clicked', () => {
const history = createMemoryHistory({});
const wrapper = mountWithContexts(<TeamAdd />, {
context: { router: { history } },
});
wrapper.find('button[aria-label="Cancel"]').prop('onClick')();
expect(history.location.pathname).toEqual('/teams');
});
test('should navigate to teams list when close (x) is clicked', () => {
const history = createMemoryHistory({});
const wrapper = mountWithContexts(<TeamAdd />, {
context: { router: { history } },
});
wrapper.find('button[aria-label="Close"]').prop('onClick')();
expect(history.location.pathname).toEqual('/teams');
});
test('successful form submission should trigger redirect', async () => {
const history = createMemoryHistory({});
const teamData = {
name: 'new name',
description: 'new description',
organization: 1,
};
TeamsAPI.create.mockResolvedValueOnce({
data: {
id: 5,
...teamData,
summary_fields: {
organization: {
id: 1,
name: 'Default',
},
},
},
});
const wrapper = mountWithContexts(<TeamAdd />, {
context: { router: { history } },
});
await waitForElement(wrapper, 'button[aria-label="Save"]');
await wrapper.find('TeamForm').prop('handleSubmit')(teamData);
expect(history.location.pathname).toEqual('/teams/5');
});
});

View File

@ -0,0 +1 @@
export { default } from './TeamAdd';

View File

@ -0,0 +1,57 @@
import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import { CardBody as PFCardBody, Button } from '@patternfly/react-core';
import styled from 'styled-components';
import { DetailList, Detail } from '@components/DetailList';
import { formatDateString } from '@util/dates';
const CardBody = styled(PFCardBody)`
padding-top: 20px;
`;
class TeamDetail extends Component {
render() {
const {
team: { name, description, created, modified, summary_fields },
match,
i18n,
} = this.props;
return (
<CardBody>
<DetailList>
<Detail label={i18n._(t`Name`)} value={name} />
<Detail label={i18n._(t`Description`)} value={description} />
<Detail
label={i18n._(t`Organization`)}
value={
<Link to={`/organizations/${summary_fields.organization.id}`}>
{summary_fields.organization.name}
</Link>
}
/>
<Detail
label={i18n._(t`Created`)}
value={formatDateString(created)}
/>
<Detail
label={i18n._(t`Last Modified`)}
value={formatDateString(modified)}
/>
</DetailList>
{summary_fields.user_capabilities.edit && (
<div css="margin-top: 10px; text-align: right;">
<Button component={Link} to={`/teams/${match.params.id}/edit`}>
{i18n._(t`Edit`)}
</Button>
</div>
)}
</CardBody>
);
}
}
export default withI18n()(withRouter(TeamDetail));

View File

@ -0,0 +1,64 @@
import React from 'react';
import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers';
import TeamDetail from './TeamDetail';
jest.mock('@api');
describe('<TeamDetail />', () => {
const mockTeam = {
name: 'Foo',
description: 'Bar',
created: '2015-07-07T17:21:26.429745Z',
modified: '2019-08-11T19:47:37.980466Z',
summary_fields: {
organization: {
id: 1,
name: 'Default',
},
user_capabilities: {
edit: true,
},
},
};
test('initially renders succesfully', () => {
mountWithContexts(<TeamDetail team={mockTeam} />);
});
test('should render Details', async done => {
const wrapper = mountWithContexts(<TeamDetail team={mockTeam} />);
const testParams = [
{ label: 'Name', value: 'Foo' },
{ label: 'Description', value: 'Bar' },
{ label: 'Organization', value: 'Default' },
{ label: 'Created', value: '7/7/2015, 5:21:26 PM' },
{ label: 'Last Modified', value: '8/11/2019, 7:47:37 PM' },
];
// eslint-disable-next-line no-restricted-syntax
for (const { label, value } of testParams) {
// eslint-disable-next-line no-await-in-loop
const detail = await waitForElement(wrapper, `Detail[label="${label}"]`);
expect(detail.find('dt').text()).toBe(label);
expect(detail.find('dd').text()).toBe(value);
}
done();
});
test('should show edit button for users with edit permission', async done => {
const wrapper = mountWithContexts(<TeamDetail team={mockTeam} />);
const editButton = await waitForElement(wrapper, 'TeamDetail Button');
expect(editButton.text()).toEqual('Edit');
expect(editButton.prop('to')).toBe('/teams/undefined/edit');
done();
});
test('should hide edit button for users without edit permission', async done => {
const readOnlyTeam = { ...mockTeam };
readOnlyTeam.summary_fields.user_capabilities.edit = false;
const wrapper = mountWithContexts(<TeamDetail team={readOnlyTeam} />);
await waitForElement(wrapper, 'TeamDetail');
expect(wrapper.find('TeamDetail Button').length).toBe(0);
done();
});
});

View File

@ -0,0 +1 @@
export { default } from './TeamDetail';

View File

@ -0,0 +1,81 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import { CardBody } from '@patternfly/react-core';
import { TeamsAPI } from '@api';
import { Config } from '@contexts/Config';
import TeamForm from '../shared/TeamForm';
class TeamEdit extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleCancel = this.handleCancel.bind(this);
this.handleSuccess = this.handleSuccess.bind(this);
this.state = {
error: '',
};
}
async handleSubmit(values) {
const { team } = this.props;
try {
await TeamsAPI.update(team.id, values);
this.handleSuccess();
} catch (err) {
this.setState({ error: err });
}
}
handleCancel() {
const {
team: { id },
history,
} = this.props;
history.push(`/teams/${id}/details`);
}
handleSuccess() {
const {
team: { id },
history,
} = this.props;
history.push(`/teams/${id}/details`);
}
render() {
const { team } = this.props;
const { error } = this.state;
return (
<CardBody>
<Config>
{({ me }) => (
<TeamForm
team={team}
handleSubmit={this.handleSubmit}
handleCancel={this.handleCancel}
me={me || {}}
/>
)}
</Config>
{error ? <div>error</div> : null}
</CardBody>
);
}
}
TeamEdit.propTypes = {
team: PropTypes.shape().isRequired,
};
TeamEdit.contextTypes = {
custom_virtualenvs: PropTypes.arrayOf(PropTypes.string),
};
export { TeamEdit as _TeamEdit };
export default withRouter(TeamEdit);

View File

@ -0,0 +1,44 @@
import React from 'react';
import { createMemoryHistory } from 'history';
import { TeamsAPI } from '@api';
import { mountWithContexts } from '@testUtils/enzymeHelpers';
import TeamEdit from './TeamEdit';
jest.mock('@api');
describe('<TeamEdit />', () => {
const mockData = {
name: 'Foo',
description: 'Bar',
id: 1,
summary_fields: {
organization: {
id: 1,
name: 'Default',
},
},
};
test('handleSubmit should call api update', () => {
const wrapper = mountWithContexts(<TeamEdit team={mockData} />);
const updatedTeamData = {
name: 'new name',
description: 'new description',
};
wrapper.find('TeamForm').prop('handleSubmit')(updatedTeamData);
expect(TeamsAPI.update).toHaveBeenCalledWith(1, updatedTeamData);
});
test('should navigate to team detail when cancel is clicked', () => {
const history = createMemoryHistory({});
const wrapper = mountWithContexts(<TeamEdit team={mockData} />, {
context: { router: { history } },
});
wrapper.find('button[aria-label="Cancel"]').prop('onClick')();
expect(history.location.pathname).toEqual('/teams/1/details');
});
});

View File

@ -0,0 +1 @@
export { default } from './TeamEdit';

View File

@ -0,0 +1,228 @@
import React, { Component, Fragment } from 'react';
import { withRouter } from 'react-router-dom';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import { Card, PageSection } from '@patternfly/react-core';
import { TeamsAPI } from '@api';
import AlertModal from '@components/AlertModal';
import DataListToolbar from '@components/DataListToolbar';
import ErrorDetail from '@components/ErrorDetail';
import PaginatedDataList, {
ToolbarAddButton,
ToolbarDeleteButton,
} from '@components/PaginatedDataList';
import { getQSConfig, parseQueryString } from '@util/qs';
import TeamListItem from './TeamListItem';
const QS_CONFIG = getQSConfig('team', {
page: 1,
page_size: 20,
order_by: 'name',
});
class TeamsList extends Component {
constructor(props) {
super(props);
this.state = {
hasContentLoading: true,
contentError: null,
deletionError: null,
teams: [],
selected: [],
itemCount: 0,
actions: null,
};
this.handleSelectAll = this.handleSelectAll.bind(this);
this.handleSelect = this.handleSelect.bind(this);
this.handleTeamDelete = this.handleTeamDelete.bind(this);
this.handleDeleteErrorClose = this.handleDeleteErrorClose.bind(this);
this.loadTeams = this.loadTeams.bind(this);
}
componentDidMount() {
this.loadTeams();
}
componentDidUpdate(prevProps) {
const { location } = this.props;
if (location !== prevProps.location) {
this.loadTeams();
}
}
handleSelectAll(isSelected) {
const { teams } = this.state;
const selected = isSelected ? [...teams] : [];
this.setState({ selected });
}
handleSelect(row) {
const { selected } = this.state;
if (selected.some(s => s.id === row.id)) {
this.setState({ selected: selected.filter(s => s.id !== row.id) });
} else {
this.setState({ selected: selected.concat(row) });
}
}
handleDeleteErrorClose() {
this.setState({ deletionError: null });
}
async handleTeamDelete() {
const { selected } = this.state;
this.setState({ hasContentLoading: true });
try {
await Promise.all(selected.map(team => TeamsAPI.destroy(team.id)));
} catch (err) {
this.setState({ deletionError: err });
} finally {
await this.loadTeams();
}
}
async loadTeams() {
const { location } = this.props;
const { actions: cachedActions } = this.state;
const params = parseQueryString(QS_CONFIG, location.search);
let optionsPromise;
if (cachedActions) {
optionsPromise = Promise.resolve({ data: { actions: cachedActions } });
} else {
optionsPromise = TeamsAPI.readOptions();
}
const promises = Promise.all([TeamsAPI.read(params), optionsPromise]);
this.setState({ contentError: null, hasContentLoading: true });
try {
const [
{
data: { count, results },
},
{
data: { actions },
},
] = await promises;
this.setState({
actions,
itemCount: count,
teams: results,
selected: [],
});
} catch (err) {
this.setState({ contentError: err });
} finally {
this.setState({ hasContentLoading: false });
}
}
render() {
const {
actions,
itemCount,
contentError,
hasContentLoading,
deletionError,
selected,
teams,
} = this.state;
const { match, i18n } = this.props;
const canAdd =
actions && Object.prototype.hasOwnProperty.call(actions, 'POST');
const isAllSelected =
selected.length > 0 && selected.length === teams.length;
return (
<Fragment>
<PageSection>
<Card>
<PaginatedDataList
contentError={contentError}
hasContentLoading={hasContentLoading}
items={teams}
itemCount={itemCount}
pluralizedItemName={i18n._(t`Teams`)}
qsConfig={QS_CONFIG}
toolbarColumns={[
{
name: i18n._(t`Name`),
key: 'name',
isSortable: true,
isSearchable: true,
},
{
name: i18n._(t`Modified`),
key: 'modified',
isSortable: true,
isNumeric: true,
},
{
name: i18n._(t`Created`),
key: 'created',
isSortable: true,
isNumeric: true,
},
]}
renderToolbar={props => (
<DataListToolbar
{...props}
showSelectAll
isAllSelected={isAllSelected}
onSelectAll={this.handleSelectAll}
qsConfig={QS_CONFIG}
additionalControls={[
<ToolbarDeleteButton
key="delete"
onDelete={this.handleTeamDelete}
itemsToDelete={selected}
pluralizedItemName={i18n._(t`Teams`)}
/>,
canAdd ? (
<ToolbarAddButton key="add" linkTo={`${match.url}/add`} />
) : null,
]}
/>
)}
renderItem={o => (
<TeamListItem
key={o.id}
team={o}
detailUrl={`${match.url}/${o.id}`}
isSelected={selected.some(row => row.id === o.id)}
onSelect={() => this.handleSelect(o)}
/>
)}
emptyStateControls={
canAdd ? (
<ToolbarAddButton key="add" linkTo={`${match.url}/add`} />
) : null
}
/>
</Card>
</PageSection>
<AlertModal
isOpen={deletionError}
variant="danger"
title={i18n._(t`Error!`)}
onClose={this.handleDeleteErrorClose}
>
{i18n._(t`Failed to delete one or more teams.`)}
<ErrorDetail error={deletionError} />
</AlertModal>
</Fragment>
);
}
}
export { TeamsList as _TeamsList };
export default withI18n()(withRouter(TeamsList));

View File

@ -0,0 +1,232 @@
import React from 'react';
import { TeamsAPI } from '@api';
import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers';
import TeamsList, { _TeamsList } from './TeamList';
jest.mock('@api');
const mockAPITeamsList = {
data: {
count: 3,
results: [
{
name: 'Team 0',
id: 1,
url: '/teams/1',
summary_fields: {
user_capabilities: {
delete: true,
},
},
},
{
name: 'Team 1',
id: 2,
url: '/teams/2',
summary_fields: {
user_capabilities: {
delete: true,
},
},
},
{
name: 'Team 2',
id: 3,
url: '/teams/3',
summary_fields: {
user_capabilities: {
delete: true,
},
},
},
],
},
isModalOpen: false,
warningTitle: 'title',
warningMsg: 'message',
};
describe('<TeamsList />', () => {
let wrapper;
beforeEach(() => {
TeamsAPI.read = () =>
Promise.resolve({
data: mockAPITeamsList.data,
});
TeamsAPI.readOptions = () =>
Promise.resolve({
data: {
actions: {
GET: {},
POST: {},
},
},
});
});
test('initially renders succesfully', () => {
mountWithContexts(<TeamsList />);
});
test('Selects one team when row is checked', async () => {
wrapper = mountWithContexts(<TeamsList />);
await waitForElement(
wrapper,
'TeamsList',
el => el.state('hasContentLoading') === false
);
expect(
wrapper
.find('input[type="checkbox"]')
.findWhere(n => n.prop('checked') === true).length
).toBe(0);
wrapper
.find('TeamListItem')
.at(0)
.find('DataListCheck')
.props()
.onChange(true);
wrapper.update();
expect(
wrapper
.find('input[type="checkbox"]')
.findWhere(n => n.prop('checked') === true).length
).toBe(1);
});
test('Select all checkbox selects and unselects all rows', async () => {
wrapper = mountWithContexts(<TeamsList />);
await waitForElement(
wrapper,
'TeamsList',
el => el.state('hasContentLoading') === false
);
expect(
wrapper
.find('input[type="checkbox"]')
.findWhere(n => n.prop('checked') === true).length
).toBe(0);
wrapper
.find('Checkbox#select-all')
.props()
.onChange(true);
wrapper.update();
expect(
wrapper
.find('input[type="checkbox"]')
.findWhere(n => n.prop('checked') === true).length
).toBe(4);
wrapper
.find('Checkbox#select-all')
.props()
.onChange(false);
wrapper.update();
expect(
wrapper
.find('input[type="checkbox"]')
.findWhere(n => n.prop('checked') === true).length
).toBe(0);
});
test('api is called to delete Teams for each team in selected.', () => {
wrapper = mountWithContexts(<TeamsList />);
const component = wrapper.find('TeamsList');
wrapper.find('TeamsList').setState({
teams: mockAPITeamsList.data.results,
itemCount: 3,
isInitialized: true,
isModalOpen: mockAPITeamsList.isModalOpen,
selected: mockAPITeamsList.data.results,
});
wrapper.find('ToolbarDeleteButton').prop('onDelete')();
expect(TeamsAPI.destroy).toHaveBeenCalledTimes(
component.state('selected').length
);
});
test('call loadTeams after team(s) have been deleted', () => {
const fetchTeams = jest.spyOn(_TeamsList.prototype, 'loadTeams');
const event = { preventDefault: () => {} };
wrapper = mountWithContexts(<TeamsList />);
wrapper.find('TeamsList').setState({
teams: mockAPITeamsList.data.results,
itemCount: 3,
isInitialized: true,
selected: mockAPITeamsList.data.results.slice(0, 1),
});
const component = wrapper.find('TeamsList');
component.instance().handleTeamDelete(event);
expect(fetchTeams).toBeCalled();
});
test('error is shown when team not successfully deleted from api', async done => {
TeamsAPI.destroy.mockRejectedValue(
new Error({
response: {
config: {
method: 'delete',
url: '/api/v2/teams/1',
},
data: 'An error occurred',
},
})
);
wrapper = mountWithContexts(<TeamsList />);
wrapper.find('TeamsList').setState({
teams: mockAPITeamsList.data.results,
itemCount: 3,
isInitialized: true,
selected: mockAPITeamsList.data.results.slice(0, 1),
});
wrapper.find('ToolbarDeleteButton').prop('onDelete')();
await waitForElement(
wrapper,
'Modal',
el => el.props().isOpen === true && el.props().title === 'Error!'
);
done();
});
test('Add button shown for users without ability to POST', async done => {
wrapper = mountWithContexts(<TeamsList />);
await waitForElement(
wrapper,
'TeamsList',
el => el.state('hasContentLoading') === true
);
await waitForElement(
wrapper,
'TeamsList',
el => el.state('hasContentLoading') === false
);
expect(wrapper.find('ToolbarAddButton').length).toBe(1);
done();
});
test('Add button hidden for users without ability to POST', async done => {
TeamsAPI.readOptions = () =>
Promise.resolve({
data: {
actions: {
GET: {},
},
},
});
wrapper = mountWithContexts(<TeamsList />);
await waitForElement(
wrapper,
'TeamsList',
el => el.state('hasContentLoading') === true
);
await waitForElement(
wrapper,
'TeamsList',
el => el.state('hasContentLoading') === false
);
expect(wrapper.find('ToolbarAddButton').length).toBe(0);
done();
});
});

View File

@ -0,0 +1,83 @@
import React, { Fragment } from 'react';
import { string, bool, func } from 'prop-types';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import {
DataListItem,
DataListItemRow,
DataListItemCells,
Tooltip,
} from '@patternfly/react-core';
import { Link } from 'react-router-dom';
import { PencilAltIcon } from '@patternfly/react-icons';
import ActionButtonCell from '@components/ActionButtonCell';
import DataListCell from '@components/DataListCell';
import DataListCheck from '@components/DataListCheck';
import ListActionButton from '@components/ListActionButton';
import VerticalSeparator from '@components/VerticalSeparator';
import { Team } from '@types';
class TeamListItem extends React.Component {
static propTypes = {
team: Team.isRequired,
detailUrl: string.isRequired,
isSelected: bool.isRequired,
onSelect: func.isRequired,
};
render() {
const { team, isSelected, onSelect, detailUrl, i18n } = this.props;
const labelId = `check-action-${team.id}`;
return (
<DataListItem key={team.id} aria-labelledby={labelId}>
<DataListItemRow>
<DataListCheck
id={`select-team-${team.id}`}
checked={isSelected}
onChange={onSelect}
aria-labelledby={labelId}
/>
<DataListItemCells
dataListCells={[
<DataListCell key="divider">
<VerticalSeparator />
<Link id={labelId} to={`${detailUrl}`}>
<b>{team.name}</b>
</Link>
</DataListCell>,
<DataListCell key="organization">
{team.summary_fields.organization && (
<Fragment>
<b style={{ marginRight: '20px' }}>
{i18n._(t`Organization`)}
</b>
<Link
to={`/organizations/${team.summary_fields.organization.id}/details`}
>
<b>{team.summary_fields.organization.name}</b>
</Link>
</Fragment>
)}
</DataListCell>,
<ActionButtonCell lastcolumn="true" key="action">
{team.summary_fields.user_capabilities.edit && (
<Tooltip content={i18n._(t`Edit Team`)} position="top">
<ListActionButton
variant="plain"
component={Link}
to={`/teams/${team.id}/edit`}
>
<PencilAltIcon />
</ListActionButton>
</Tooltip>
)}
</ActionButtonCell>,
]}
/>
</DataListItemRow>
</DataListItem>
);
}
}
export default withI18n()(TeamListItem);

View File

@ -0,0 +1,78 @@
import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import { I18nProvider } from '@lingui/react';
import { mountWithContexts } from '@testUtils/enzymeHelpers';
import TeamListItem from './TeamListItem';
describe('<TeamListItem />', () => {
test('initially renders succesfully', () => {
mountWithContexts(
<I18nProvider>
<MemoryRouter initialEntries={['/teams']} initialIndex={0}>
<TeamListItem
team={{
id: 1,
name: 'Team 1',
summary_fields: {
user_capabilities: {
edit: true,
},
},
}}
detailUrl="/team/1"
isSelected
onSelect={() => {}}
/>
</MemoryRouter>
</I18nProvider>
);
});
test('edit button shown to users with edit capabilities', () => {
const wrapper = mountWithContexts(
<I18nProvider>
<MemoryRouter initialEntries={['/teams']} initialIndex={0}>
<TeamListItem
team={{
id: 1,
name: 'Team',
summary_fields: {
user_capabilities: {
edit: true,
},
},
}}
detailUrl="/team/1"
isSelected
onSelect={() => {}}
/>
</MemoryRouter>
</I18nProvider>
);
expect(wrapper.find('PencilAltIcon').exists()).toBeTruthy();
});
test('edit button hidden from users without edit capabilities', () => {
const wrapper = mountWithContexts(
<I18nProvider>
<MemoryRouter initialEntries={['/teams']} initialIndex={0}>
<TeamListItem
team={{
id: 1,
name: 'Team',
summary_fields: {
user_capabilities: {
edit: false,
},
},
}}
detailUrl="/team/1"
isSelected
onSelect={() => {}}
/>
</MemoryRouter>
</I18nProvider>
);
expect(wrapper.find('PencilAltIcon').exists()).toBeFalsy();
});
});

View File

@ -0,0 +1,2 @@
export { default as TeamList } from './TeamList';
export { default as TeamListItem } from './TeamListItem';

View File

@ -1,26 +1,79 @@
import React, { Component, Fragment } from 'react';
import { Route, withRouter, Switch } from 'react-router-dom';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import {
PageSection,
PageSectionVariants,
Title,
} from '@patternfly/react-core';
import { Config } from '@contexts/Config';
import Breadcrumbs from '@components/Breadcrumbs/Breadcrumbs';
import TeamsList from './TeamList/TeamList';
import TeamAdd from './TeamAdd/TeamAdd';
import Team from './Team';
class Teams extends Component {
render() {
constructor(props) {
super(props);
const { i18n } = props;
this.state = {
breadcrumbConfig: {
'/teams': i18n._(t`Teams`),
'/teams/add': i18n._(t`Create New Team`),
},
};
}
setBreadcrumbConfig = team => {
const { i18n } = this.props;
const { light } = PageSectionVariants;
if (!team) {
return;
}
const breadcrumbConfig = {
'/teams': i18n._(t`Teams`),
'/teams/add': i18n._(t`Create New Team`),
[`/teams/${team.id}`]: `${team.name}`,
[`/teams/${team.id}/edit`]: i18n._(t`Edit Details`),
[`/teams/${team.id}/details`]: i18n._(t`Details`),
[`/teams/${team.id}/users`]: i18n._(t`Users`),
[`/teams/${team.id}/access`]: i18n._(t`Access`),
};
this.setState({ breadcrumbConfig });
};
render() {
const { match, history, location } = this.props;
const { breadcrumbConfig } = this.state;
return (
<Fragment>
<PageSection variant={light} className="pf-m-condensed">
<Title size="2xl">{i18n._(t`Teams`)}</Title>
</PageSection>
<PageSection />
<Breadcrumbs breadcrumbConfig={breadcrumbConfig} />
<Switch>
<Route path={`${match.path}/add`} render={() => <TeamAdd />} />
<Route
path={`${match.path}/:id`}
render={() => (
<Config>
{({ me }) => (
<Team
history={history}
location={location}
setBreadcrumb={this.setBreadcrumbConfig}
me={me || {}}
/>
)}
</Config>
)}
/>
<Route path={`${match.path}`} render={() => <TeamsList />} />
</Switch>
</Fragment>
);
}
}
export default withI18n()(Teams);
export { Teams as _Teams };
export default withI18n()(withRouter(Teams));

View File

@ -1,29 +1,16 @@
import React from 'react';
import { mountWithContexts } from '@testUtils/enzymeHelpers';
import Teams from './Teams';
jest.mock('@api');
describe('<Teams />', () => {
let pageWrapper;
let pageSections;
let title;
beforeEach(() => {
pageWrapper = mountWithContexts(<Teams />);
pageSections = pageWrapper.find('PageSection');
title = pageWrapper.find('Title');
});
afterEach(() => {
pageWrapper.unmount();
});
test('initially renders without crashing', () => {
expect(pageWrapper.length).toBe(1);
expect(pageSections.length).toBe(2);
expect(title.length).toBe(1);
expect(title.props().size).toBe('2xl');
expect(pageSections.first().props().variant).toBe('light');
test('initially renders succesfully', () => {
mountWithContexts(
<Teams
match={{ path: '/teams', url: '/teams' }}
location={{ search: '', pathname: '/teams' }}
/>
);
});
});

View File

@ -0,0 +1,91 @@
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import { Formik, Field } from 'formik';
import { Form } from '@patternfly/react-core';
import FormActionGroup from '@components/FormActionGroup/FormActionGroup';
import FormField from '@components/FormField';
import FormRow from '@components/FormRow';
import OrganizationLookup from '@components/Lookup/OrganizationLookup';
import { required } from '@util/validators';
function TeamForm(props) {
const { team, handleCancel, handleSubmit, i18n } = props;
const [organization, setOrganization] = useState(
team.summary_fields ? team.summary_fields.organization : null
);
return (
<Formik
initialValues={{
description: team.description || '',
name: team.name || '',
organization: team.organization || '',
}}
onSubmit={handleSubmit}
render={formik => (
<Form
autoComplete="off"
onSubmit={formik.handleSubmit}
css="padding: 0 24px"
>
<FormRow>
<FormField
id="team-name"
label={i18n._(t`Name`)}
name="name"
type="text"
validate={required(null, i18n)}
isRequired
/>
<FormField
id="team-description"
label={i18n._(t`Description`)}
name="description"
type="text"
/>
<Field
name="organization"
validate={required(
i18n._(t`Select a value for this field`),
i18n
)}
render={({ form }) => (
<OrganizationLookup
helperTextInvalid={form.errors.organization}
isValid={
!form.touched.organization || !form.errors.organization
}
onBlur={() => form.setFieldTouched('organization')}
onChange={value => {
form.setFieldValue('organization', value.id);
setOrganization(value);
}}
value={organization}
required
/>
)}
/>
</FormRow>
<FormActionGroup
onCancel={handleCancel}
onSubmit={formik.handleSubmit}
/>
</Form>
)}
/>
);
}
TeamForm.propTypes = {
handleCancel: PropTypes.func.isRequired,
handleSubmit: PropTypes.func.isRequired,
team: PropTypes.shape({}),
};
TeamForm.defaultProps = {
team: {},
};
export default withI18n()(TeamForm);

View File

@ -0,0 +1,96 @@
import React from 'react';
import { act } from 'react-dom/test-utils';
import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers';
import { sleep } from '@testUtils/testUtils';
import TeamForm from './TeamForm';
jest.mock('@api');
describe('<TeamForm />', () => {
let wrapper;
const meConfig = {
me: {
is_superuser: false,
},
};
const mockData = {
id: 1,
name: 'Foo',
description: 'Bar',
organization: 1,
summary_fields: {
id: 1,
name: 'Default',
},
};
afterEach(() => {
wrapper.unmount();
jest.clearAllMocks();
});
test('changing inputs should update form values', () => {
wrapper = mountWithContexts(
<TeamForm
team={mockData}
handleSubmit={jest.fn()}
handleCancel={jest.fn()}
me={meConfig.me}
/>
);
const form = wrapper.find('Formik');
wrapper.find('input#team-name').simulate('change', {
target: { value: 'new foo', name: 'name' },
});
expect(form.state('values').name).toEqual('new foo');
wrapper.find('input#team-description').simulate('change', {
target: { value: 'new bar', name: 'description' },
});
expect(form.state('values').description).toEqual('new bar');
act(() => {
wrapper.find('OrganizationLookup').invoke('onBlur')();
wrapper.find('OrganizationLookup').invoke('onChange')({
id: 2,
name: 'Other Org',
});
});
expect(form.state('values').organization).toEqual(2);
});
test('should call handleSubmit when Submit button is clicked', async () => {
const handleSubmit = jest.fn();
await act(async () => {
wrapper = mountWithContexts(
<TeamForm
team={mockData}
handleSubmit={handleSubmit}
handleCancel={jest.fn()}
me={meConfig.me}
/>
);
});
await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
expect(handleSubmit).not.toHaveBeenCalled();
wrapper.find('button[aria-label="Save"]').simulate('click');
await sleep(1);
expect(handleSubmit).toBeCalled();
});
test('calls handleCancel when Cancel button is clicked', () => {
const handleCancel = jest.fn();
wrapper = mountWithContexts(
<TeamForm
team={mockData}
handleSubmit={jest.fn()}
handleCancel={handleCancel}
me={meConfig.me}
/>
);
expect(handleCancel).not.toHaveBeenCalled();
wrapper.find('button[aria-label="Cancel"]').prop('onClick')();
expect(handleCancel).toBeCalled();
});
});

View File

@ -0,0 +1,2 @@
/* eslint-disable-next-line import/prefer-default-export */
export { default as TeamForm } from './TeamForm';

View File

@ -88,7 +88,7 @@ describe('<Template />', () => {
done();
});
test('should show content error when user attempts to navigate to erroneous route', async done => {
test('should show content error when user attempts to navigate to erroneous route', async () => {
const history = createMemoryHistory({
initialEntries: ['/templates/job_template/1/foobar'],
});
@ -111,6 +111,5 @@ describe('<Template />', () => {
}
);
await waitForElement(wrapper, 'ContentError', el => el.length === 1);
done();
});
});

View File

@ -204,3 +204,9 @@ export const Host = shape({
last_job: number,
last_job_host_summary: number,
});
export const Team = shape({
id: number.isRequired,
name: string.isRequired,
organization: number,
});