Merge pull request #5332 from AlexSCorey/InventoryAdd/EditForm

Adds Add/Edit Inventory and Inventory Form

Reviewed-by: https://github.com/apps/softwarefactory-project-zuul
This commit is contained in:
softwarefactory-project-zuul[bot] 2019-11-22 16:00:35 +00:00 committed by GitHub
commit b7efd5a9ab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 717 additions and 14 deletions

View File

@ -1,6 +1,7 @@
import Base from '../Base';
import InstanceGroupsMixin from '../mixins/InstanceGroups.mixin';
class Inventories extends Base {
class Inventories extends InstanceGroupsMixin(Base) {
constructor(http) {
super(http);
this.baseUrl = '/api/v2/inventories/';
@ -9,7 +10,9 @@ class Inventories extends Base {
}
readAccessList(id, params) {
return this.http.get(`${this.baseUrl}${id}/access_list/`, { params });
return this.http.get(`${this.baseUrl}${id}/access_list/`, {
params,
});
}
}

View File

@ -1,10 +1,110 @@
import React, { Component } from 'react';
import { PageSection } from '@patternfly/react-core';
import React, { useState, useEffect } from 'react';
import { withI18n } from '@lingui/react';
import { withRouter } from 'react-router-dom';
import { t } from '@lingui/macro';
import {
PageSection,
Card,
CardHeader,
CardBody,
Tooltip,
} from '@patternfly/react-core';
class InventoryAdd extends Component {
render() {
return <PageSection>Coming soon :)</PageSection>;
import ContentError from '@components/ContentError';
import ContentLoading from '@components/ContentLoading';
import CardCloseButton from '@components/CardCloseButton';
import { InventoriesAPI, CredentialTypesAPI } from '@api';
import InventoryForm from '../shared/InventoryForm';
function InventoryAdd({ history, i18n }) {
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [credentialTypeId, setCredentialTypeId] = useState(null);
useEffect(() => {
const loadData = async () => {
try {
const {
data: { results: loadedCredentialTypeId },
} = await CredentialTypesAPI.read({ kind: 'insights' });
setCredentialTypeId(loadedCredentialTypeId[0].id);
} catch (err) {
setError(err);
} finally {
setIsLoading(false);
}
};
loadData();
}, [isLoading, credentialTypeId]);
const handleCancel = () => {
history.push('/inventories');
};
const handleSubmit = async values => {
const {
instanceGroups,
organization,
insights_credential,
...remainingValues
} = values;
try {
const {
data: { id: inventoryId },
} = await InventoriesAPI.create({
organization: organization.id,
insights_credential: insights_credential.id,
...remainingValues,
});
if (instanceGroups) {
const associatePromises = instanceGroups.map(async ig =>
InventoriesAPI.associateInstanceGroup(inventoryId, ig.id)
);
await Promise.all(associatePromises);
}
const url = history.location.pathname.search('smart')
? `/inventories/smart_inventory/${inventoryId}/details`
: `/inventories/inventory/${inventoryId}/details`;
history.push(`${url}`);
} catch (err) {
setError(err);
}
};
if (error) {
return <ContentError />;
}
if (isLoading) {
return <ContentLoading />;
}
return (
<PageSection>
<Card>
<CardHeader
style={{
paddingRight: '10px',
paddingTop: '10px',
paddingBottom: '0',
textAlign: 'right',
}}
>
<Tooltip content={i18n._(t`Close`)} position="top">
<CardCloseButton onClick={handleCancel} />
</Tooltip>
</CardHeader>
<CardBody>
<InventoryForm
onCancel={handleCancel}
onSubmit={handleSubmit}
credentialTypeId={credentialTypeId}
/>
</CardBody>
</Card>
</PageSection>
);
}
export default InventoryAdd;
export { InventoryAdd as _InventoryAdd };
export default withI18n()(withRouter(InventoryAdd));

View File

@ -0,0 +1,71 @@
import React from 'react';
import { act } from 'react-dom/test-utils';
import { createMemoryHistory } from 'history';
import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers';
import { sleep } from '@testUtils/testUtils';
import { InventoriesAPI, CredentialTypesAPI } from '@api';
import InventoryAdd from './InventoryAdd';
jest.mock('@api');
CredentialTypesAPI.read.mockResolvedValue({
data: {
results: [
{
id: 14,
name: 'insights',
},
],
},
});
InventoriesAPI.create.mockResolvedValue({ data: { id: 13 } });
describe('<InventoryAdd />', () => {
let wrapper;
let history;
beforeEach(async () => {
history = createMemoryHistory({ initialEntries: ['/inventories'] });
await act(async () => {
wrapper = mountWithContexts(<InventoryAdd />, {
context: { router: { history } },
});
});
});
afterEach(() => {
wrapper.unmount();
});
test('Initially renders successfully', () => {
expect(wrapper.length).toBe(1);
});
test('handleSubmit should call the api', async () => {
const instanceGroups = [{ name: 'Bizz', id: 1 }, { name: 'Buzz', id: 2 }];
await waitForElement(wrapper, 'isLoading', el => el.length === 0);
wrapper.find('InventoryForm').prop('onSubmit')({
name: 'new Foo',
organization: { id: 2 },
insights_credential: { id: 47 },
instanceGroups,
});
await sleep(1);
expect(InventoriesAPI.create).toHaveBeenCalledWith({
name: 'new Foo',
organization: 2,
insights_credential: 47,
});
instanceGroups.map(IG =>
expect(InventoriesAPI.associateInstanceGroup).toHaveBeenCalledWith(
13,
IG.id
)
);
});
test('handleCancel should return the user back to the inventories list', async () => {
await waitForElement(wrapper, 'isLoading', el => el.length === 0);
wrapper.find('CardCloseButton').simulate('click');
expect(history.location.pathname).toEqual('/inventories');
});
});

View File

@ -1,10 +1,126 @@
import React, { Component } from 'react';
import { PageSection } from '@patternfly/react-core';
import React, { useState, useEffect } from 'react';
import { withI18n } from '@lingui/react';
import { withRouter } from 'react-router-dom';
import { t } from '@lingui/macro';
import { CardHeader, CardBody, Tooltip } from '@patternfly/react-core';
import { object } from 'prop-types';
class InventoryEdit extends Component {
render() {
return <PageSection>Coming soon :)</PageSection>;
import CardCloseButton from '@components/CardCloseButton';
import { InventoriesAPI, CredentialTypesAPI } from '@api';
import ContentLoading from '@components/ContentLoading';
import ContentError from '@components/ContentError';
import InventoryForm from '../shared/InventoryForm';
import { getAddedAndRemoved } from '../../../util/lists';
function InventoryEdit({ history, i18n, inventory }) {
const [error, setError] = useState(null);
const [associatedInstanceGroups, setInstanceGroups] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [credentialTypeId, setCredentialTypeId] = useState(null);
useEffect(() => {
const loadData = async () => {
try {
const [
{
data: { results: loadedInstanceGroups },
},
{
data: { results: loadedCredentialTypeId },
},
] = await Promise.all([
InventoriesAPI.readInstanceGroups(inventory.id),
CredentialTypesAPI.read({
kind: 'insights',
}),
]);
setInstanceGroups(loadedInstanceGroups);
setCredentialTypeId(loadedCredentialTypeId[0].id);
} catch (err) {
setError(err);
} finally {
setIsLoading(false);
}
};
loadData();
}, [inventory.id, isLoading, inventory, credentialTypeId]);
const handleCancel = () => {
history.push('/inventories');
};
const handleSubmit = async values => {
const {
instanceGroups,
insights_credential,
organization,
...remainingValues
} = values;
try {
await InventoriesAPI.update(inventory.id, {
insights_credential: insights_credential.id,
organization: organization.id,
...remainingValues,
});
if (instanceGroups) {
const { added, removed } = getAddedAndRemoved(
associatedInstanceGroups,
instanceGroups
);
const associatePromises = added.map(async ig =>
InventoriesAPI.associateInstanceGroup(inventory.id, ig.id)
);
const disassociatePromises = removed.map(async ig =>
InventoriesAPI.disassociateInstanceGroup(inventory.id, ig.id)
);
await Promise.all([...associatePromises, ...disassociatePromises]);
}
} catch (err) {
setError(err);
} finally {
const url = history.location.pathname.search('smart')
? `/inventories/smart_inventory/${inventory.id}/details`
: `/inventories/inventory/${inventory.id}/details`;
history.push(`${url}`);
}
};
if (isLoading) {
return <ContentLoading />;
}
if (error) {
return <ContentError />;
}
return (
<>
<CardHeader
style={{
paddingRight: '10px',
paddingTop: '10px',
paddingBottom: '0',
textAlign: 'right',
}}
>
<Tooltip content={i18n._(t`Close`)} position="top">
<CardCloseButton onClick={handleCancel} />
</Tooltip>
</CardHeader>
<CardBody>
<InventoryForm
onCancel={handleCancel}
onSubmit={handleSubmit}
inventory={inventory}
instanceGroups={associatedInstanceGroups}
credentialTypeId={credentialTypeId}
/>
</CardBody>
</>
);
}
export default InventoryEdit;
InventoryEdit.proptype = {
inventory: object.isRequired,
};
export { InventoryEdit as _InventoryEdit };
export default withI18n()(withRouter(InventoryEdit));

View File

@ -0,0 +1,128 @@
import React from 'react';
import { act } from 'react-dom/test-utils';
import { createMemoryHistory } from 'history';
import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers';
import { sleep } from '@testUtils/testUtils';
import { InventoriesAPI, CredentialTypesAPI } from '@api';
import InventoryEdit from './InventoryEdit';
jest.mock('@api');
const mockInventory = {
id: 1,
type: 'inventory',
url: '/api/v2/inventories/1/',
summary_fields: {
organization: {
id: 1,
name: 'Default',
description: '',
},
user_capabilities: {
edit: true,
delete: true,
copy: true,
adhoc: true,
},
insights_credential: {
id: 1,
name: 'Foo',
},
},
created: '2019-10-04T16:56:48.025455Z',
modified: '2019-10-04T16:56:48.025468Z',
name: 'Inv no hosts',
description: '',
organization: 1,
kind: '',
host_filter: null,
variables: '---',
has_active_failures: false,
total_hosts: 0,
hosts_with_active_failures: 0,
total_groups: 0,
groups_with_active_failures: 0,
has_inventory_sources: false,
total_inventory_sources: 0,
inventory_sources_with_failures: 0,
insights_credential: null,
pending_deletion: false,
};
CredentialTypesAPI.read.mockResolvedValue({
data: {
results: [
{
id: 14,
name: 'insights',
},
],
},
});
const associatedInstanceGroups = [
{
id: 1,
name: 'Foo',
},
];
InventoriesAPI.readInstanceGroups.mockResolvedValue({
data: {
results: associatedInstanceGroups,
},
});
describe('<InventoryEdit />', () => {
let wrapper;
let history;
beforeEach(async () => {
history = createMemoryHistory({ initialEntries: ['/inventories'] });
await act(async () => {
wrapper = mountWithContexts(<InventoryEdit inventory={mockInventory} />, {
context: { router: { history } },
});
});
});
afterEach(() => {
wrapper.unmount();
});
test('initially renders successfully', async () => {
expect(wrapper.find('InventoryEdit').length).toBe(1);
});
test('called InventoriesAPI.readInstanceGroups', async () => {
expect(InventoriesAPI.readInstanceGroups).toBeCalledWith(1);
});
test('handleCancel returns the user to the inventories list', async () => {
await waitForElement(wrapper, 'isLoading', el => el.length === 0);
wrapper.find('CardCloseButton').simulate('click');
expect(history.location.pathname).toEqual('/inventories');
});
test('handleSubmit should post to the api', async () => {
await waitForElement(wrapper, 'isLoading', el => el.length === 0);
const instanceGroups = [{ name: 'Bizz', id: 2 }, { name: 'Buzz', id: 3 }];
wrapper.find('InventoryForm').prop('onSubmit')({
name: 'Foo',
id: 13,
organization: { id: 1 },
insights_credential: { id: 13 },
instanceGroups,
});
await sleep(0);
instanceGroups.map(IG =>
expect(InventoriesAPI.associateInstanceGroup).toHaveBeenCalledWith(
1,
IG.id
)
);
associatedInstanceGroups.map(async aIG =>
expect(InventoriesAPI.disassociateInstanceGroup).toHaveBeenCalledWith(
1,
aIG.id
)
);
});
});

View File

@ -0,0 +1,155 @@
import React from 'react';
import { Formik, Field } from 'formik';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import { func, number, shape } from 'prop-types';
import { VariablesField } from '@components/CodeMirrorInput';
import { Form } from '@patternfly/react-core';
import FormField from '@components/FormField';
import FormActionGroup from '@components/FormActionGroup/FormActionGroup';
import FormRow from '@components/FormRow';
import { required } from '@util/validators';
import InstanceGroupsLookup from '@components/Lookup/InstanceGroupsLookup';
import OrganizationLookup from '@components/Lookup/OrganizationLookup';
import CredentialLookup from '@components/Lookup/CredentialLookup';
function InventoryForm({
inventory = {},
i18n,
onCancel,
onSubmit,
instanceGroups,
credentialTypeId,
}) {
const initialValues = {
name: inventory.name || '',
description: inventory.description || '',
variables: inventory.variables || '---',
organization:
(inventory.summary_fields && inventory.summary_fields.organization) ||
null,
instanceGroups: instanceGroups || [],
insights_credential:
(inventory.summary_fields &&
inventory.summary_fields.insights_credential) ||
null,
};
return (
<Formik
initialValues={initialValues}
onSubmit={values => {
onSubmit(values);
}}
render={formik => (
<Form autoComplete="off" onSubmit={formik.handleSubmit}>
<FormRow>
<FormField
id="inventory-name"
label={i18n._(t`Name`)}
name="name"
type="text"
validate={required(null, i18n)}
isRequired
/>
<FormField
id="inventory-description"
label={i18n._(t`Description`)}
name="description"
type="text"
/>
<Field
id="inventory-organization"
label={i18n._(t`Organization`)}
name="organization"
validate={required(
i18n._(t`Select a value for this field`),
i18n
)}
render={({ form, field }) => (
<OrganizationLookup
helperTextInvalid={form.errors.organization}
isValid={
!form.touched.organization || !form.errors.organization
}
onBlur={() => form.setFieldTouched('organization')}
onChange={value => {
form.setFieldValue('organization', value);
}}
value={field.value}
required
/>
)}
/>
<Field
id="inventory-insights_credential"
label={i18n._(t`Insights Credential`)}
name="insights_credential"
render={({ field, form }) => (
<CredentialLookup
label={i18n._(t`Insights Credential`)}
credentialTypeId={credentialTypeId}
onChange={value => {
// TODO: BELOW SHOULD BE REFACTORED AND REMOVED ONCE THE LOOKUP REFACTOR
// GOES INTO PLACE.
if (value[0] === field.value) {
return form.setFieldValue('insights_credential', null);
}
return form.setFieldValue('insights_credential', value);
}}
value={field.value}
/>
)}
/>
</FormRow>
<FormRow>
<Field
id="inventory-instanceGroups"
label={i18n._(t`Instance Groups`)}
name="instanceGroups"
render={({ field, form }) => (
<InstanceGroupsLookup
value={field.value}
onChange={value => {
form.setFieldValue('instanceGroups', value);
}}
/>
)}
/>
</FormRow>
<FormRow>
<VariablesField
tooltip={i18n._(
t`Enter inventory variables using either JSON or YAML syntax. Use the radio button to toggle between the two. Refer to the Ansible Tower documentation for example syntax`
)}
id="inventory-variables"
name="variables"
label={i18n._(t`Variables`)}
/>
</FormRow>
<FormRow>
<FormActionGroup
onCancel={onCancel}
onSubmit={formik.handleSubmit}
/>
</FormRow>
</Form>
)}
/>
);
}
InventoryForm.proptype = {
handleSubmit: func.isRequired,
handleCancel: func.isRequired,
instanceGroups: shape(),
inventory: shape(),
credentialTypeId: number.isRequired,
};
InventoryForm.defaultProps = {
inventory: {},
instanceGroups: [],
};
export default withI18n()(InventoryForm);

View File

@ -0,0 +1,129 @@
import React from 'react';
import { act } from 'react-dom/test-utils';
import { mountWithContexts } from '@testUtils/enzymeHelpers';
import { sleep } from '@testUtils/testUtils';
import InventoryForm from './InventoryForm';
const inventory = {
id: 1,
type: 'inventory',
url: '/api/v2/inventories/1/',
summary_fields: {
organization: {
id: 1,
name: 'Default',
description: '',
},
user_capabilities: {
edit: true,
delete: true,
copy: true,
adhoc: true,
},
insights_credential: {
id: 1,
name: 'Foo',
},
},
created: '2019-10-04T16:56:48.025455Z',
modified: '2019-10-04T16:56:48.025468Z',
name: 'Inv no hosts',
description: '',
organization: 1,
kind: '',
host_filter: null,
variables: '---',
has_active_failures: false,
total_hosts: 0,
hosts_with_active_failures: 0,
total_groups: 0,
groups_with_active_failures: 0,
has_inventory_sources: false,
total_inventory_sources: 0,
inventory_sources_with_failures: 0,
insights_credential: null,
pending_deletion: false,
};
const instanceGroups = [{ name: 'Foo', id: 1 }, { name: 'Bar', id: 2 }];
describe('<InventoryForm />', () => {
let wrapper;
let onCancel;
let onSubmit;
beforeEach(() => {
onCancel = jest.fn();
onSubmit = jest.fn();
wrapper = mountWithContexts(
<InventoryForm
onCancel={onCancel}
onSubmit={onSubmit}
inventory={inventory}
instanceGroups={instanceGroups}
credentialTypeId={14}
/>
);
});
afterEach(() => {
wrapper.unmount();
});
test('Initially renders successfully', () => {
expect(wrapper.length).toBe(1);
});
test('should display form fields properly', () => {
expect(wrapper.find('FormGroup[label="Name"]').length).toBe(1);
expect(wrapper.find('FormGroup[label="Description"]').length).toBe(1);
expect(wrapper.find('FormGroup[label="Organization"]').length).toBe(1);
expect(wrapper.find('FormGroup[label="Instance Groups"]').length).toBe(1);
expect(wrapper.find('FormGroup[label="Insights Credential"]').length).toBe(
1
);
expect(wrapper.find('VariablesField[label="Variables"]').length).toBe(1);
});
test('should update from values onChange', async () => {
const form = wrapper.find('Formik');
act(() => {
wrapper.find('OrganizationLookup').invoke('onBlur')();
wrapper.find('OrganizationLookup').invoke('onChange')({
id: 3,
name: 'organization',
});
});
expect(form.state('values').organization).toEqual({
id: 3,
name: 'organization',
});
wrapper.find('input#inventory-name').simulate('change', {
target: { value: 'new Foo', name: 'name' },
});
expect(form.state('values').name).toEqual('new Foo');
act(() => {
wrapper.find('CredentialLookup').invoke('onBlur')();
wrapper.find('CredentialLookup').invoke('onChange')({
id: 10,
name: 'credential',
});
});
expect(form.state('values').insights_credential).toEqual({
id: 10,
name: 'credential',
});
form.find('button[aria-label="Save"]').simulate('click');
await sleep(1);
expect(onSubmit).toHaveBeenCalledWith({
description: '',
insights_credential: { id: 10, name: 'credential' },
instanceGroups: [{ id: 1, name: 'Foo' }, { id: 2, name: 'Bar' }],
name: 'new Foo',
organization: { id: 3, name: 'organization' },
variables: '---',
});
});
test('should call handleCancel when Cancel button is clicked', async () => {
expect(onCancel).not.toHaveBeenCalled();
wrapper.find('button[aria-label="Cancel"]').invoke('onClick')();
expect(onCancel).toBeCalled();
});
});

View File

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