diff options
author | Liam Fallon <liam.fallon@est.tech> | 2021-11-15 11:53:18 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2021-11-15 11:53:18 +0000 |
commit | cb347e737f05d030fe781e15a9cf755cef42c80f (patch) | |
tree | 8919ef211d85b25b2e4edc94b40c678dabb87a85 /runtime/ui-react/src/components | |
parent | 496f58cf8f5ad6c65b417d2ae79a69ece480d049 (diff) | |
parent | 2022e5ce5a03788a6edc5761c495cfadc5ded485 (diff) |
Merge "Align ui-react file in policy-clamp and policy-gui"
Diffstat (limited to 'runtime/ui-react/src/components')
31 files changed, 3193 insertions, 3105 deletions
diff --git a/runtime/ui-react/src/components/dialogs/Loop/CreateLoopModal.js b/runtime/ui-react/src/components/dialogs/Loop/CreateLoopModal.js index 5663360a0..690dcbbdf 100644 --- a/runtime/ui-react/src/components/dialogs/Loop/CreateLoopModal.js +++ b/runtime/ui-react/src/components/dialogs/Loop/CreateLoopModal.js @@ -34,157 +34,160 @@ import LoopCache from '../../../api/LoopCache'; import SvgGenerator from '../../loop_viewer/svg/SvgGenerator'; const ModalStyled = styled(Modal)` - background-color: transparent; + background-color: transparent; ` const ErrMsgStyled = styled.div` - color: red; + color: red; ` export default class CreateLoopModal extends React.Component { - constructor(props, context) { - super(props, context); + constructor(props, context) { + super(props, context); - this.getAllLoopTemplates = this.getAllLoopTemplates.bind(this); - this.handleCreate = this.handleCreate.bind(this); - this.handleModelName = this.handleModelName.bind(this); - this.handleClose = this.handleClose.bind(this); - this.handleDropDownListChange = this.handleDropDownListChange.bind(this); - this.renderSvg = this.renderSvg.bind(this); - this.state = { - show: true, - chosenTemplateName: '', - modelInputErrMsg: '', - modelName: '', - templateNames: [], - fakeLoopCacheWithTemplate: new LoopCache({}) - }; - } + this.getAllLoopTemplates = this.getAllLoopTemplates.bind(this); + this.handleCreate = this.handleCreate.bind(this); + this.handleModelName = this.handleModelName.bind(this); + this.handleClose = this.handleClose.bind(this); + this.handleDropDownListChange = this.handleDropDownListChange.bind(this); + this.renderSvg = this.renderSvg.bind(this); + this.state = { + show: true, + chosenTemplateName: '', + modelInputErrMsg: '', + modelName: '', + templateNames: [], + fakeLoopCacheWithTemplate: new LoopCache({}) + }; + } - async componentDidMount() { - await this.getAllLoopTemplates(); - await this.getModelNames(); - } + async componentDidMount() { + await this.getAllLoopTemplates(); + await this.getModelNames(); + } - handleClose() { - this.setState({ show: false }); - this.props.history.push('/'); - } + handleClose() { + this.setState({ show: false }); + this.props.history.push('/'); + } - handleDropDownListChange(e) { - if (typeof e.value !== "undefined") { - this.setState({ - fakeLoopCacheWithTemplate: - new LoopCache({ - "loopTemplate":e.templateObject, - "name": "fakeLoop" - }), - chosenTemplateName: e.value - }) - } else { - this.setState({ fakeLoopCacheWithTemplate: new LoopCache({}) }) - } - } + handleDropDownListChange(e) { + if (typeof e.value !== "undefined") { + this.setState({ + fakeLoopCacheWithTemplate: + new LoopCache({ + "loopTemplate": e.templateObject, + "name": "fakeLoop" + }), + chosenTemplateName: e.value + }) + } else { + this.setState({ fakeLoopCacheWithTemplate: new LoopCache({}) }) + } + } - getAllLoopTemplates() { - TemplateService.getAllLoopTemplates().then(templatesData => { - const templateOptions = templatesData.map((templateData) => { return { label: templateData.name, value: templateData.name, templateObject: templateData } }); - this.setState({ - templateNames: templateOptions }) - }); - } + getAllLoopTemplates() { + TemplateService.getAllLoopTemplates().then(templatesData => { + const templateOptions = templatesData.map((templateData) => { + return { label: templateData.name, value: templateData.name, templateObject: templateData } + }); + this.setState({ + templateNames: templateOptions + }) + }); + } - getModelNames() { - TemplateService.getLoopNames().then(loopNames => { - if (!loopNames) { - loopNames = []; - } - // Remove LOOP_ prefix - let trimmedLoopNames = loopNames.map(str => str.replace('LOOP_', '')); - this.setState({ modelNames: trimmedLoopNames }); - }); - } + getModelNames() { + TemplateService.getLoopNames().then(loopNames => { + if (!loopNames) { + loopNames = []; + } + // Remove LOOP_ prefix + let trimmedLoopNames = loopNames.map(str => str.replace('LOOP_', '')); + this.setState({ modelNames: trimmedLoopNames }); + }); + } - handleCreate() { - if (!this.state.modelName) { - alert("A model name is required"); - return; - } - console.debug("Create Model " + this.state.modelName + ", Template " + this.state.chosenTemplateName + " is chosen"); - this.setState({ show: false }); - LoopService.createLoop("LOOP_" + this.state.modelName, this.state.chosenTemplateName).then(text => { - console.debug("CreateLoop response received: ", text); - try { - this.props.history.push('/'); - this.props.loadLoopFunction("LOOP_" + this.state.modelName); - } catch(err) { - alert(text); - this.props.history.push('/'); - } - }) - .catch(error => { - console.debug("Create Loop failed"); - }); - } + handleCreate() { + if (!this.state.modelName) { + alert("A model name is required"); + return; + } + console.debug("Create Model " + this.state.modelName + ", Template " + this.state.chosenTemplateName + " is chosen"); + this.setState({ show: false }); + LoopService.createLoop("LOOP_" + this.state.modelName, this.state.chosenTemplateName).then(text => { + console.debug("CreateLoop response received: ", text); + try { + this.props.history.push('/'); + this.props.loadLoopFunction("LOOP_" + this.state.modelName); + } catch (err) { + alert(text); + this.props.history.push('/'); + } + }) + .catch(error => { + console.debug("Create Loop failed"); + }); + } - handleModelName(event) { - if (this.state.modelNames.includes(event.target.value)) { - this.setState({ - modelInputErrMsg: 'A model named "' + event.target.value + '" already exists. Please pick another name.', - modelName: event.target.value - }); - return; - } else { - this.setState({ - modelInputErrMsg: '', - modelName: event.target.value - }); - } - } + handleModelName(event) { + if (this.state.modelNames.includes(event.target.value)) { + this.setState({ + modelInputErrMsg: 'A model named "' + event.target.value + '" already exists. Please pick another name.', + modelName: event.target.value + }); + return; + } else { + this.setState({ + modelInputErrMsg: '', + modelName: event.target.value + }); + } + } - renderSvg() { - return ( - <SvgGenerator loopCache={this.state.fakeLoopCacheWithTemplate} clickable={false} generatedFrom={SvgGenerator.GENERATED_FROM_TEMPLATE}/> - ); - } + renderSvg() { + return ( + <SvgGenerator loopCache={ this.state.fakeLoopCacheWithTemplate } clickable={ false } generatedFrom={ SvgGenerator.GENERATED_FROM_TEMPLATE }/> + ); + } - render() { - return ( - <ModalStyled size="xl" show={this.state.show} onHide={this.handleClose} backdrop="static" keyboard={false} > - <Modal.Header closeButton> - <Modal.Title>Create Model</Modal.Title> - </Modal.Header> - <Modal.Body> - <Form.Group as={Row} controlId="formPlaintextEmail"> - <Form.Label column sm="2">Template Name:</Form.Label> - <Col sm="10"> - <Select onChange={this.handleDropDownListChange} options={this.state.templateNames} /> - </Col> - </Form.Group> - <Form.Group as={Row} style={{alignItems: 'center'}} controlId="formSvgPreview"> - <Form.Label column sm="2">Model Preview:</Form.Label> - <Col sm="10"> - {this.renderSvg()} - </Col> - </Form.Group> - <Form.Group as={Row} controlId="formPlaintextEmail"> - <Form.Label column sm="2">Model Name:</Form.Label> - <input sm="5" type="text" style={{width: '50%', marginLeft: '1em' }} - value={this.state.modelName} - onChange={this.handleModelName} - /> - <span sm="5"/> - </Form.Group> - <Form.Group as={Row} controlId="formPlaintextEmail"> - <Form.Label column sm="2"> </Form.Label> - <ErrMsgStyled>{this.state.modelInputErrMsg}</ErrMsgStyled> - </Form.Group> - </Modal.Body> - <Modal.Footer> - <Button variant="secondary" type="null" onClick={this.handleClose}>Cancel</Button> - <Button variant="primary" type="submit" onClick={this.handleCreate}>Create</Button> - </Modal.Footer> - </ModalStyled> - ); - } + render() { + return ( + <ModalStyled size="xl" show={ this.state.show } onHide={ this.handleClose } backdrop="static" keyboard={ false }> + <Modal.Header closeButton> + <Modal.Title>Create Model</Modal.Title> + </Modal.Header> + <Modal.Body> + <Form.Group as={ Row } controlId="formPlaintextEmail"> + <Form.Label column sm="2">Template Name:</Form.Label> + <Col sm="10"> + <Select onChange={ this.handleDropDownListChange } options={ this.state.templateNames }/> + </Col> + </Form.Group> + <Form.Group as={ Row } style={ { alignItems: 'center' } } controlId="formSvgPreview"> + <Form.Label column sm="2">Model Preview:</Form.Label> + <Col sm="10"> + { this.renderSvg() } + </Col> + </Form.Group> + <Form.Group as={ Row } controlId="formPlaintextEmail"> + <Form.Label column sm="2">Model Name:</Form.Label> + <input sm="5" type="text" style={ { width: '50%', marginLeft: '1em' } } + value={ this.state.modelName } + onChange={ this.handleModelName } + /> + <span sm="5"/> + </Form.Group> + <Form.Group as={ Row } controlId="formPlaintextEmail"> + <Form.Label column sm="2"> </Form.Label> + <ErrMsgStyled>{ this.state.modelInputErrMsg }</ErrMsgStyled> + </Form.Group> + </Modal.Body> + <Modal.Footer> + <Button variant="secondary" type="null" onClick={ this.handleClose }>Cancel</Button> + <Button variant="primary" type="submit" onClick={ this.handleCreate }>Create</Button> + </Modal.Footer> + </ModalStyled> + ); + } } diff --git a/runtime/ui-react/src/components/dialogs/Loop/CreateLoopModal.test.js b/runtime/ui-react/src/components/dialogs/Loop/CreateLoopModal.test.js index 8ef53b412..3d9483334 100644 --- a/runtime/ui-react/src/components/dialogs/Loop/CreateLoopModal.test.js +++ b/runtime/ui-react/src/components/dialogs/Loop/CreateLoopModal.test.js @@ -27,7 +27,10 @@ import LoopService from '../../../api/LoopService'; import TemplateService from '../../../api/TemplateService'; let errorMessage = ''; -window.alert = jest.fn().mockImplementation((mesg) => { errorMessage = mesg ; return }); +window.alert = jest.fn().mockImplementation((mesg) => { + errorMessage = mesg; + return +}); describe('Verify CreateLoopModal', () => { @@ -35,7 +38,7 @@ describe('Verify CreateLoopModal', () => { it('Test the render method', async () => { const flushPromises = () => new Promise(setImmediate); TemplateService.getAllLoopTemplates = jest.fn().mockImplementation(() => { - return Promise.resolve([{"name":"template1"},{"name":"template2"}]); + return Promise.resolve([{ "name": "template1" }, { "name": "template2" }]); }); TemplateService.getLoopNames = jest.fn().mockImplementation(() => { return Promise.resolve([]); @@ -45,21 +48,25 @@ describe('Verify CreateLoopModal', () => { expect(component).toMatchSnapshot(); await flushPromises(); component.update(); - expect(component.state('templateNames')).toStrictEqual([{"label": "template1", "value": "template1", "templateObject": {"name": "template1"}}, {"label": "template2", "value": "template2","templateObject": {"name": "template2"}}]); + expect(component.state('templateNames')).toStrictEqual([{ "label": "template1", "value": "template1", "templateObject": { "name": "template1" } }, { + "label": "template2", + "value": "template2", + "templateObject": { "name": "template2" } + }]); }); it('handleDropdownListChange event', async () => { - const flushPromises = () => new Promise(setImmediate); + const flushPromises = () => new Promise(setImmediate); const component = shallow(<CreateLoopModal/>); - component.find('StateManager').simulate('change', {value: 'template1', templateObject: {"name":"template1"} }); + component.find('StateManager').simulate('change', { value: 'template1', templateObject: { "name": "template1" } }); await flushPromises(); component.update(); expect(component.state('chosenTemplateName')).toEqual("template1"); expect(component.state('fakeLoopCacheWithTemplate').getLoopTemplate()['name']).toEqual("template1"); expect(component.state('fakeLoopCacheWithTemplate').getLoopName()).toEqual("fakeLoop"); - component.find('StateManager').simulate('change',{value: 'template2', templateObject: {"name":"template2"} }); + component.find('StateManager').simulate('change', { value: 'template2', templateObject: { "name": "template2" } }); await flushPromises(); component.update(); expect(component.state('chosenTemplateName')).toEqual("template2"); @@ -70,12 +77,12 @@ describe('Verify CreateLoopModal', () => { it('handleModelName event', async () => { const flushPromises = () => new Promise(setImmediate); TemplateService.getAllLoopTemplates = jest.fn().mockImplementation(() => { - return Promise.resolve([{"name":"template1"},{"name":"template2"}]); + return Promise.resolve([{ "name": "template1" }, { "name": "template2" }]); }); TemplateService.getLoopNames = jest.fn().mockImplementation(() => { return Promise.resolve([]); }); - const event = {target: {value : "model1"} }; + const event = { target: { value: "model1" } }; const component = shallow(<CreateLoopModal/>); await flushPromises(); component.find('input').simulate('change', event); @@ -84,21 +91,21 @@ describe('Verify CreateLoopModal', () => { }); it('Test handleClose', () => { - const historyMock = { push: jest.fn() }; - const handleClose = jest.spyOn(CreateLoopModal.prototype,'handleClose'); - const component = shallow(<CreateLoopModal history={historyMock} />) + const historyMock = { push: jest.fn() }; + const handleClose = jest.spyOn(CreateLoopModal.prototype, 'handleClose'); + const component = shallow(<CreateLoopModal history={ historyMock }/>) component.find('[variant="secondary"]').prop('onClick')(); expect(handleClose).toHaveBeenCalledTimes(1); expect(component.state('show')).toEqual(false); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); - + expect(historyMock.push.mock.calls[0]).toEqual(['/']); + handleClose.mockClear(); }); it('Test handleCreate Fail', () => { - const handleCreate = jest.spyOn(CreateLoopModal.prototype,'handleCreate'); + const handleCreate = jest.spyOn(CreateLoopModal.prototype, 'handleCreate'); const component = shallow(<CreateLoopModal/>) component.find('[variant="primary"]').prop('onClick')(); @@ -110,32 +117,33 @@ describe('Verify CreateLoopModal', () => { }); it('Test handleCreate Suc', async () => { - const flushPromises = () => new Promise(setImmediate); + const flushPromises = () => new Promise(setImmediate); const historyMock = { push: jest.fn() }; - const loadLoopFunction = jest.fn(); - + const loadLoopFunction = jest.fn(); + LoopService.createLoop = jest.fn().mockImplementation(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => {} - }); - }); - - const handleCreate = jest.spyOn(CreateLoopModal.prototype,'handleCreate'); - const component = shallow(<CreateLoopModal history={historyMock} loadLoopFunction={loadLoopFunction}/>) + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + } + }); + }); + + const handleCreate = jest.spyOn(CreateLoopModal.prototype, 'handleCreate'); + const component = shallow(<CreateLoopModal history={ historyMock } loadLoopFunction={ loadLoopFunction }/>) component.setState({ - modelName: "modelNameTest", - chosenTemplateName: "template1" - }); + modelName: "modelNameTest", + chosenTemplateName: "template1" + }); component.find('[variant="primary"]').prop('onClick')(); - await flushPromises(); - component.update(); + await flushPromises(); + component.update(); expect(handleCreate).toHaveBeenCalledTimes(1); expect(component.state('show')).toEqual(false); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); + expect(historyMock.push.mock.calls[0]).toEqual(['/']); handleCreate.mockClear(); }); diff --git a/runtime/ui-react/src/components/dialogs/Loop/DeployLoopModal.js b/runtime/ui-react/src/components/dialogs/Loop/DeployLoopModal.js index 803cfa9cb..5fff58631 100644 --- a/runtime/ui-react/src/components/dialogs/Loop/DeployLoopModal.js +++ b/runtime/ui-react/src/components/dialogs/Loop/DeployLoopModal.js @@ -32,142 +32,147 @@ import styled from 'styled-components'; import Spinner from 'react-bootstrap/Spinner' const StyledSpinnerDiv = styled.div` - justify-content: center !important; - display: flex !important; + justify-content: center !important; + display: flex !important; `; const ModalStyled = styled(Modal)` - background-color: transparent; + background-color: transparent; ` const FormStyled = styled(Form.Group)` - padding: .25rem 1.5rem; + padding: .25rem 1.5rem; ` export default class DeployLoopModal extends React.Component { - - constructor(props, context) { - super(props, context); - - this.handleSave = this.handleSave.bind(this); - this.handleClose = this.handleClose.bind(this); - this.handleChange = this.handleChange.bind(this); - this.refreshStatus = this.refreshStatus.bind(this); - this.renderDeployParam = this.renderDeployParam.bind(this); - this.renderSpinner = this.renderSpinner.bind(this); - - const propertiesJson = JSON.parse(JSON.stringify(this.props.loopCache.getGlobalProperties())); - this.state = { - loopCache: this.props.loopCache, - temporaryPropertiesJson: propertiesJson, - show: true, - key: this.getInitialKeyValue(propertiesJson) - }; - } - getInitialKeyValue(temporaryPropertiesJson) { - const deployJsonList = temporaryPropertiesJson["dcaeDeployParameters"]; - return Object.keys(deployJsonList).find((obj) => Object.keys(deployJsonList).indexOf(obj) === 0); - } - componentWillReceiveProps(newProps) { - this.setState({ - loopName: newProps.loopCache.getLoopName(), - show: true - }); - } - - handleClose(){ - this.setState({ show: false }); - this.props.history.push('/'); - } - - renderSpinner() { - if (this.state.deploying) { - return ( - <StyledSpinnerDiv> - <Spinner animation="border" role="status"> - <span className="sr-only">Loading...</span> - </Spinner> - </StyledSpinnerDiv> - ); - } else { - return (<div></div>); - } - } - - handleSave() { - const loopName = this.props.loopCache.getLoopName(); - // save the global propserties - this.setState({ deploying: true }); - LoopService.updateGlobalProperties(loopName, this.state.temporaryPropertiesJson).then(resp => { - LoopActionService.performAction(loopName, "deploy").then(pars => { - this.props.showSucAlert("Action deploy successfully performed"); - // refresh status and update loop logs - this.refreshStatus(loopName); - }) - .catch(error => { - this.props.showFailAlert("Action deploy failed"); - // refresh status and update loop logs - this.refreshStatus(loopName); - }); - }); - } - - refreshStatus(loopName) { - LoopActionService.refreshStatus(loopName).then(data => { - this.props.updateLoopFunction(data); - this.setState({ show: false, deploying: false }); - this.props.history.push('/'); - }) - .catch(error => { - this.props.showFailAlert("Refresh status failed"); - this.setState({ show: false, deploying: false }); - this.props.history.push('/'); - }); - } - handleChange(event) { - let deploymentParam = this.state.temporaryPropertiesJson["dcaeDeployParameters"]; - deploymentParam[this.state.key][event.target.name] = event.target.value; - - this.setState({temporaryPropertiesJson:{dcaeDeployParameters: deploymentParam}}); - } - renderDeployParamTabs() { - if (typeof (this.state.temporaryPropertiesJson) === "undefined") { - return ""; - } - - const deployJsonList = this.state.temporaryPropertiesJson["dcaeDeployParameters"]; - var indents = []; - Object.keys(deployJsonList).forEach(item => - indents.push(<Tab key={item} eventKey={item} title={item}> - {this.renderDeployParam(deployJsonList[item])} - </Tab>) - ); - return indents; - } - renderDeployParam(deployJson) { - var indents = []; - Object.keys(deployJson).forEach(item => - indents.push(<FormStyled key={item}> - <Form.Label>{item}</Form.Label> - <Form.Control type="text" name={item} onChange={this.handleChange} defaultValue={deployJson[item]}></Form.Control> - </FormStyled>)); - return indents; - } - render() { - return ( - <ModalStyled size="lg" show={this.state.show} onHide={this.handleClose} backdrop="static" keyboard={false} > - <Modal.Header closeButton> - <Modal.Title>Deployment parameters</Modal.Title> - </Modal.Header> - <Tabs id="controlled-tab-example" activeKey={this.state.key} onSelect={key => this.setState({ key })}> - {this.renderDeployParamTabs()} - </Tabs> - {this.renderSpinner()} - <Modal.Footer> - <Button variant="secondary" type="null" onClick={this.handleClose}>Cancel</Button> - <Button variant="primary" type="submit" onClick={this.handleSave}>Deploy</Button> - </Modal.Footer> - </ModalStyled> - ); - } + constructor(props, context) { + super(props, context); + + this.handleSave = this.handleSave.bind(this); + this.handleClose = this.handleClose.bind(this); + this.handleChange = this.handleChange.bind(this); + this.refreshStatus = this.refreshStatus.bind(this); + this.renderDeployParam = this.renderDeployParam.bind(this); + this.renderSpinner = this.renderSpinner.bind(this); + + const propertiesJson = JSON.parse(JSON.stringify(this.props.loopCache.getGlobalProperties())); + this.state = { + loopCache: this.props.loopCache, + temporaryPropertiesJson: propertiesJson, + show: true, + key: this.getInitialKeyValue(propertiesJson) + }; + } + + getInitialKeyValue(temporaryPropertiesJson) { + const deployJsonList = temporaryPropertiesJson["dcaeDeployParameters"]; + return Object.keys(deployJsonList).find((obj) => Object.keys(deployJsonList).indexOf(obj) === 0); + } + + componentWillReceiveProps(newProps) { + this.setState({ + loopName: newProps.loopCache.getLoopName(), + show: true + }); + } + + handleClose() { + this.setState({ show: false }); + this.props.history.push('/'); + } + + renderSpinner() { + if (this.state.deploying) { + return ( + <StyledSpinnerDiv> + <Spinner animation="border" role="status"> + <span className="sr-only">Loading...</span> + </Spinner> + </StyledSpinnerDiv> + ); + } else { + return (<div></div>); + } + } + + handleSave() { + const loopName = this.props.loopCache.getLoopName(); + // save the global propserties + this.setState({ deploying: true }); + LoopService.updateGlobalProperties(loopName, this.state.temporaryPropertiesJson).then(resp => { + LoopActionService.performAction(loopName, "deploy").then(pars => { + this.props.showSucAlert("Action deploy successfully performed"); + // refresh status and update loop logs + this.refreshStatus(loopName); + }) + .catch(error => { + this.props.showFailAlert("Action deploy failed"); + // refresh status and update loop logs + this.refreshStatus(loopName); + }); + }); + } + + refreshStatus(loopName) { + LoopActionService.refreshStatus(loopName).then(data => { + this.props.updateLoopFunction(data); + this.setState({ show: false, deploying: false }); + this.props.history.push('/'); + }) + .catch(error => { + this.props.showFailAlert("Refresh status failed"); + this.setState({ show: false, deploying: false }); + this.props.history.push('/'); + }); + } + + handleChange(event) { + let deploymentParam = this.state.temporaryPropertiesJson["dcaeDeployParameters"]; + deploymentParam[this.state.key][event.target.name] = event.target.value; + + this.setState({ temporaryPropertiesJson: { dcaeDeployParameters: deploymentParam } }); + } + + renderDeployParamTabs() { + if (typeof (this.state.temporaryPropertiesJson) === "undefined") { + return ""; + } + + const deployJsonList = this.state.temporaryPropertiesJson["dcaeDeployParameters"]; + var indents = []; + Object.keys(deployJsonList).forEach(item => + indents.push(<Tab key={ item } eventKey={ item } title={ item }> + { this.renderDeployParam(deployJsonList[item]) } + </Tab>) + ); + return indents; + } + + renderDeployParam(deployJson) { + var indents = []; + Object.keys(deployJson).forEach(item => + indents.push(<FormStyled key={ item }> + <Form.Label>{ item }</Form.Label> + <Form.Control type="text" name={ item } onChange={ this.handleChange } defaultValue={ deployJson[item] }></Form.Control> + </FormStyled>)); + return indents; + } + + render() { + return ( + <ModalStyled size="lg" show={ this.state.show } onHide={ this.handleClose } backdrop="static" keyboard={ false }> + <Modal.Header closeButton> + <Modal.Title>Deployment parameters</Modal.Title> + </Modal.Header> + <Tabs id="controlled-tab-example" activeKey={ this.state.key } onSelect={ key => this.setState({ key }) }> + { this.renderDeployParamTabs() } + </Tabs> + { this.renderSpinner() } + <Modal.Footer> + <Button variant="secondary" type="null" onClick={ this.handleClose }>Cancel</Button> + <Button variant="primary" type="submit" onClick={ this.handleSave }>Deploy</Button> + </Modal.Footer> + </ModalStyled> + ); + } } diff --git a/runtime/ui-react/src/components/dialogs/Loop/DeployLoopModal.test.js b/runtime/ui-react/src/components/dialogs/Loop/DeployLoopModal.test.js index 84dbfd1f6..0c68f237c 100644 --- a/runtime/ui-react/src/components/dialogs/Loop/DeployLoopModal.test.js +++ b/runtime/ui-react/src/components/dialogs/Loop/DeployLoopModal.test.js @@ -28,85 +28,87 @@ import LoopActionService from '../../../api/LoopActionService'; import LoopService from '../../../api/LoopService'; describe('Verify DeployLoopModal', () => { - const loopCache = new LoopCache({ - "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca", - "globalPropertiesJson": { - "dcaeDeployParameters": { - "testMs": { - "location_id": "", - "policy_id": "TCA_h2NMX_v1_0_ResourceInstanceName1_tca" - } - } - } - }); + const loopCache = new LoopCache({ + "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca", + "globalPropertiesJson": { + "dcaeDeployParameters": { + "testMs": { + "location_id": "", + "policy_id": "TCA_h2NMX_v1_0_ResourceInstanceName1_tca" + } + } + } + }); - it('Test the render method', () => { - const component = shallow( - <DeployLoopModal loopCache={loopCache}/> - ) + it('Test the render method', () => { + const component = shallow( + <DeployLoopModal loopCache={ loopCache }/> + ) - expect(component).toMatchSnapshot(); - }); - - it('Test handleClose', () => { - const historyMock = { push: jest.fn() }; - const handleClose = jest.spyOn(DeployLoopModal.prototype,'handleClose'); - const component = shallow(<DeployLoopModal history={historyMock} loopCache={loopCache}/>) + expect(component).toMatchSnapshot(); + }); - component.find('[variant="secondary"]').prop('onClick')(); + it('Test handleClose', () => { + const historyMock = { push: jest.fn() }; + const handleClose = jest.spyOn(DeployLoopModal.prototype, 'handleClose'); + const component = shallow(<DeployLoopModal history={ historyMock } loopCache={ loopCache }/>) - expect(handleClose).toHaveBeenCalledTimes(1); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); - }); + component.find('[variant="secondary"]').prop('onClick')(); - it('Test handleSave successful', async () => { - const flushPromises = () => new Promise(setImmediate); - const historyMock = { push: jest.fn() }; - const updateLoopFunction = jest.fn(); - const showSucAlert = jest.fn(); - const showFailAlert = jest.fn(); - const handleSave = jest.spyOn(DeployLoopModal.prototype,'handleSave'); - LoopService.updateGlobalProperties = jest.fn().mockImplementation(() => { - return Promise.resolve({ - ok: true, - status: 200, - text: () => "OK" - }); - }); - LoopActionService.performAction = jest.fn().mockImplementation(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => {} - }); - }); - LoopActionService.refreshStatus = jest.fn().mockImplementation(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => {} - }); - }); + expect(handleClose).toHaveBeenCalledTimes(1); + expect(historyMock.push.mock.calls[0]).toEqual(['/']); + }); - const component = shallow(<DeployLoopModal history={historyMock} - loopCache={loopCache} updateLoopFunction={updateLoopFunction} showSucAlert={showSucAlert} showFailAlert={showFailAlert} />) + it('Test handleSave successful', async () => { + const flushPromises = () => new Promise(setImmediate); + const historyMock = { push: jest.fn() }; + const updateLoopFunction = jest.fn(); + const showSucAlert = jest.fn(); + const showFailAlert = jest.fn(); + const handleSave = jest.spyOn(DeployLoopModal.prototype, 'handleSave'); + LoopService.updateGlobalProperties = jest.fn().mockImplementation(() => { + return Promise.resolve({ + ok: true, + status: 200, + text: () => "OK" + }); + }); + LoopActionService.performAction = jest.fn().mockImplementation(() => { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + } + }); + }); + LoopActionService.refreshStatus = jest.fn().mockImplementation(() => { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + } + }); + }); - component.find('[variant="primary"]').prop('onClick')(); - await flushPromises(); - component.update(); + const component = shallow(<DeployLoopModal history={ historyMock } + loopCache={ loopCache } updateLoopFunction={ updateLoopFunction } showSucAlert={ showSucAlert } showFailAlert={ showFailAlert }/>) - expect(handleSave).toHaveBeenCalledTimes(1); - expect(component.state('show')).toEqual(false); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); - handleSave.mockClear(); - }); + component.find('[variant="primary"]').prop('onClick')(); + await flushPromises(); + component.update(); - it('Onchange event', () => { - const event = { target: { name: "location_id", value: "testLocation"} }; - const component = shallow(<DeployLoopModal loopCache={loopCache}/>); + expect(handleSave).toHaveBeenCalledTimes(1); + expect(component.state('show')).toEqual(false); + expect(historyMock.push.mock.calls[0]).toEqual(['/']); + handleSave.mockClear(); + }); - component.find('[name="location_id"]').simulate('change', event); - component.update(); - expect(component.state('temporaryPropertiesJson').dcaeDeployParameters.testMs.location_id).toEqual("testLocation"); - }); -});
\ No newline at end of file + it('Onchange event', () => { + const event = { target: { name: "location_id", value: "testLocation" } }; + const component = shallow(<DeployLoopModal loopCache={ loopCache }/>); + + component.find('[name="location_id"]').simulate('change', event); + component.update(); + expect(component.state('temporaryPropertiesJson').dcaeDeployParameters.testMs.location_id).toEqual("testLocation"); + }); +}); diff --git a/runtime/ui-react/src/components/dialogs/Loop/LoopPropertiesModal.js b/runtime/ui-react/src/components/dialogs/Loop/LoopPropertiesModal.js index acd0acade..69177134b 100644 --- a/runtime/ui-react/src/components/dialogs/Loop/LoopPropertiesModal.js +++ b/runtime/ui-react/src/components/dialogs/Loop/LoopPropertiesModal.js @@ -28,91 +28,91 @@ import styled from 'styled-components'; import LoopService from '../../../api/LoopService'; const ModalStyled = styled(Modal)` - background-color: transparent; + background-color: transparent; ` export default class LoopPropertiesModal extends React.Component { - state = { - show: true, - loopCache: this.props.loopCache, - temporaryPropertiesJson: JSON.parse(JSON.stringify(this.props.loopCache.getGlobalProperties())) - }; + state = { + show: true, + loopCache: this.props.loopCache, + temporaryPropertiesJson: JSON.parse(JSON.stringify(this.props.loopCache.getGlobalProperties())) + }; - constructor(props, context) { - super(props, context); + constructor(props, context) { + super(props, context); - this.handleClose = this.handleClose.bind(this); - this.handleSave = this.handleSave.bind(this); - this.handleChange = this.handleChange.bind(this); + this.handleClose = this.handleClose.bind(this); + this.handleSave = this.handleSave.bind(this); + this.handleChange = this.handleChange.bind(this); - this.renderDcaeParameters = this.renderDcaeParameters.bind(this); - this.renderAllParameters = this.renderAllParameters.bind(this); - this.getDcaeParameters = this.getDcaeParameters.bind(this); - this.readOnly = props.readOnly !== undefined ? props.readOnly : false; - } + this.renderDcaeParameters = this.renderDcaeParameters.bind(this); + this.renderAllParameters = this.renderAllParameters.bind(this); + this.getDcaeParameters = this.getDcaeParameters.bind(this); + this.readOnly = props.readOnly !== undefined ? props.readOnly : false; + } - componentWillReceiveProps(newProps) { - this.setState({ - loopCache: newProps.loopCache, - temporaryPropertiesJson: JSON.parse(JSON.stringify(newProps.loopCache.getGlobalProperties())) - }); - } + componentWillReceiveProps(newProps) { + this.setState({ + loopCache: newProps.loopCache, + temporaryPropertiesJson: JSON.parse(JSON.stringify(newProps.loopCache.getGlobalProperties())) + }); + } - handleClose() { - this.props.history.push('/'); - } + handleClose() { + this.props.history.push('/'); + } - handleSave(event) { - LoopService.updateGlobalProperties(this.state.loopCache.getLoopName(), this.state.temporaryPropertiesJson).then(resp => { - this.setState({ show: false }); - this.props.history.push('/'); - this.props.loadLoopFunction(this.state.loopCache.getLoopName()); - }); - } + handleSave(event) { + LoopService.updateGlobalProperties(this.state.loopCache.getLoopName(), this.state.temporaryPropertiesJson).then(resp => { + this.setState({ show: false }); + this.props.history.push('/'); + this.props.loadLoopFunction(this.state.loopCache.getLoopName()); + }); + } - handleChange(event) { - this.setState({temporaryPropertiesJson:{[event.target.name]: JSON.parse(event.target.value)}}); - } + handleChange(event) { + this.setState({ temporaryPropertiesJson: { [event.target.name]: JSON.parse(event.target.value) } }); + } - renderAllParameters() { - return (<Modal.Body> - <Form> - {this.renderDcaeParameters()} - </Form> - </Modal.Body> - ); - } + renderAllParameters() { + return (<Modal.Body> + <Form> + { this.renderDcaeParameters() } + </Form> + </Modal.Body> + ); + } - getDcaeParameters() { - if (typeof (this.state.temporaryPropertiesJson) !== "undefined") { - return JSON.stringify(this.state.temporaryPropertiesJson["dcaeDeployParameters"]); - } else { - return ""; - } + getDcaeParameters() { + if (typeof (this.state.temporaryPropertiesJson) !== "undefined") { + return JSON.stringify(this.state.temporaryPropertiesJson["dcaeDeployParameters"]); + } else { + return ""; + } - } + } - renderDcaeParameters() { - return ( - <Form.Group > - <Form.Label>Deploy Parameters</Form.Label> - <Form.Control as="textarea" rows="3" name="dcaeDeployParameters" onChange={this.handleChange} defaultValue={this.getDcaeParameters()}></Form.Control> - </Form.Group> - ); - } + renderDcaeParameters() { + return ( + <Form.Group> + <Form.Label>Deploy Parameters</Form.Label> + <Form.Control as="textarea" rows="3" name="dcaeDeployParameters" onChange={ this.handleChange } defaultValue={ this.getDcaeParameters() }></Form.Control> + </Form.Group> + ); + } - render() { - return ( - <ModalStyled size="lg" show={this.state.show} onHide={this.handleClose} backdrop="static" keyboard={false} > - <Modal.Header closeButton> - <Modal.Title>Model Properties</Modal.Title> - </Modal.Header> - {this.renderAllParameters()} - <Modal.Footer> - <Button variant="secondary" type="null" onClick={this.handleClose}>Cancel</Button> - <Button variant="primary" type="submit" disabled={this.readOnly} onClick={this.handleSave}>Save Changes</Button> - </Modal.Footer> - </ModalStyled> - ); - } + render() { + return ( + <ModalStyled size="lg" show={ this.state.show } onHide={ this.handleClose } backdrop="static" keyboard={ false }> + <Modal.Header closeButton> + <Modal.Title>Model Properties</Modal.Title> + </Modal.Header> + { this.renderAllParameters() } + <Modal.Footer> + <Button variant="secondary" type="null" onClick={ this.handleClose }>Cancel</Button> + <Button variant="primary" type="submit" disabled={ this.readOnly } onClick={ this.handleSave }>Save Changes</Button> + </Modal.Footer> + </ModalStyled> + ); + } } diff --git a/runtime/ui-react/src/components/dialogs/Loop/LoopPropertiesModal.test.js b/runtime/ui-react/src/components/dialogs/Loop/LoopPropertiesModal.test.js index 5bbefe228..a9c5903a4 100644 --- a/runtime/ui-react/src/components/dialogs/Loop/LoopPropertiesModal.test.js +++ b/runtime/ui-react/src/components/dialogs/Loop/LoopPropertiesModal.test.js @@ -27,82 +27,84 @@ import LoopCache from '../../../api/LoopCache'; import LoopService from '../../../api/LoopService'; describe('Verify LoopPropertiesModal', () => { - const loopCache = new LoopCache({ - "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca", - "globalPropertiesJson": { - "dcaeDeployParameters": { - "location_id": "", - "policy_id": "TCA_h2NMX_v1_0_ResourceInstanceName1_tca" - } - } - }); + const loopCache = new LoopCache({ + "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca", + "globalPropertiesJson": { + "dcaeDeployParameters": { + "location_id": "", + "policy_id": "TCA_h2NMX_v1_0_ResourceInstanceName1_tca" + } + } + }); - it('Test the render method', () => { - const component = shallow( - <LoopPropertiesModal loopCache={loopCache}/> - ) - component.setState({ show: true, - temporaryPropertiesJson: { - "dcaeDeployParameters": { - "location_id": "", - "policy_id": "TCA_h2NMX_v1_0_ResourceInstanceName1_tca" - } - } - }); + it('Test the render method', () => { + const component = shallow( + <LoopPropertiesModal loopCache={ loopCache }/> + ) + component.setState({ + show: true, + temporaryPropertiesJson: { + "dcaeDeployParameters": { + "location_id": "", + "policy_id": "TCA_h2NMX_v1_0_ResourceInstanceName1_tca" + } + } + }); - expect(component.state('temporaryPropertiesJson')).toEqual({ - "dcaeDeployParameters": { - "location_id": "", - "policy_id": "TCA_h2NMX_v1_0_ResourceInstanceName1_tca"} - }); - expect(component.state('show')).toEqual(true); + expect(component.state('temporaryPropertiesJson')).toEqual({ + "dcaeDeployParameters": { + "location_id": "", + "policy_id": "TCA_h2NMX_v1_0_ResourceInstanceName1_tca" + } + }); + expect(component.state('show')).toEqual(true); - expect(component).toMatchSnapshot(); - }); + expect(component).toMatchSnapshot(); + }); - it('Test handleClose', () => { - const historyMock = { push: jest.fn() }; - const handleClose = jest.spyOn(LoopPropertiesModal.prototype,'handleClose'); - const component = shallow(<LoopPropertiesModal history={historyMock} loopCache={loopCache}/>) + it('Test handleClose', () => { + const historyMock = { push: jest.fn() }; + const handleClose = jest.spyOn(LoopPropertiesModal.prototype, 'handleClose'); + const component = shallow(<LoopPropertiesModal history={ historyMock } loopCache={ loopCache }/>) - component.find('[variant="secondary"]').prop('onClick')(); + component.find('[variant="secondary"]').prop('onClick')(); - expect(handleClose).toHaveBeenCalledTimes(1); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); - }); + expect(handleClose).toHaveBeenCalledTimes(1); + expect(historyMock.push.mock.calls[0]).toEqual(['/']); + }); - it('Test handleSave successful', async () => { - const flushPromises = () => new Promise(setImmediate); - const historyMock = { push: jest.fn() }; - const loadLoopFunction = jest.fn(); - const handleSave = jest.spyOn(LoopPropertiesModal.prototype,'handleSave'); - LoopService.updateGlobalProperties = jest.fn().mockImplementation(() => { - return Promise.resolve({ - ok: true, - status: 200, - text: () => "OK" - }); - }); + it('Test handleSave successful', async () => { + const flushPromises = () => new Promise(setImmediate); + const historyMock = { push: jest.fn() }; + const loadLoopFunction = jest.fn(); + const handleSave = jest.spyOn(LoopPropertiesModal.prototype, 'handleSave'); + LoopService.updateGlobalProperties = jest.fn().mockImplementation(() => { + return Promise.resolve({ + ok: true, + status: 200, + text: () => "OK" + }); + }); - const component = shallow(<LoopPropertiesModal history={historyMock} - loopCache={loopCache} loadLoopFunction={loadLoopFunction} />) + const component = shallow(<LoopPropertiesModal history={ historyMock } + loopCache={ loopCache } loadLoopFunction={ loadLoopFunction }/>) - component.find('[variant="primary"]').prop('onClick')(); - await flushPromises(); - component.update(); + component.find('[variant="primary"]').prop('onClick')(); + await flushPromises(); + component.update(); - expect(handleSave).toHaveBeenCalledTimes(1); - expect(component.state('show')).toEqual(false); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); - }); + expect(handleSave).toHaveBeenCalledTimes(1); + expect(component.state('show')).toEqual(false); + expect(historyMock.push.mock.calls[0]).toEqual(['/']); + }); - it('Onchange event', () => { - const event = {target:{name:"dcaeDeployParameters", value:"{\"location_id\": \"testLocation\",\"policy_id\": \"TCA_h2NMX_v1_0_ResourceInstanceName1_tca\"}"}}; - const component = shallow(<LoopPropertiesModal loopCache={loopCache}/>); + it('Onchange event', () => { + const event = { target: { name: "dcaeDeployParameters", value: "{\"location_id\": \"testLocation\",\"policy_id\": \"TCA_h2NMX_v1_0_ResourceInstanceName1_tca\"}" } }; + const component = shallow(<LoopPropertiesModal loopCache={ loopCache }/>); - component.find('FormControl').simulate('change', event); - component.update(); + component.find('FormControl').simulate('change', event); + component.update(); - expect(component.state('temporaryPropertiesJson').dcaeDeployParameters.location_id).toEqual("testLocation"); - }); + expect(component.state('temporaryPropertiesJson').dcaeDeployParameters.location_id).toEqual("testLocation"); + }); }); diff --git a/runtime/ui-react/src/components/dialogs/Loop/ModifyLoopModal.js b/runtime/ui-react/src/components/dialogs/Loop/ModifyLoopModal.js index f6c0d2ede..0d203418b 100644 --- a/runtime/ui-react/src/components/dialogs/Loop/ModifyLoopModal.js +++ b/runtime/ui-react/src/components/dialogs/Loop/ModifyLoopModal.js @@ -40,208 +40,223 @@ import Tab from 'react-bootstrap/Tab'; import Alert from 'react-bootstrap/Alert'; const ModalStyled = styled(Modal)` - background-color: transparent; + background-color: transparent; ` const TextModal = styled.textarea` - margin-top: 20px; - white-space:pre; - background-color: ${props => props.theme.toscaTextareaBackgroundColor}; - text-align: justify; - font-size: ${props => props.theme.toscaTextareaFontSize}; - width: 100%; - height: 300px; + margin-top: 20px; + white-space: pre; + background-color: ${ props => props.theme.toscaTextareaBackgroundColor }; + text-align: justify; + font-size: ${ props => props.theme.toscaTextareaFontSize }; + width: 100%; + height: 300px; ` const cellStyle = { border: '1px solid black' }; -const headerStyle = { backgroundColor: '#ddd', border: '2px solid black' }; -const rowHeaderStyle = {backgroundColor:'#ddd', fontSize: '15pt', text: 'bold', border: '1px solid black'}; +const headerStyle = { backgroundColor: '#ddd', border: '2px solid black' }; +const rowHeaderStyle = { backgroundColor: '#ddd', fontSize: '15pt', text: 'bold', border: '1px solid black' }; export default class ModifyLoopModal extends React.Component { - state = { - show: true, - loopCache: this.props.loopCache, - content: 'Please select Tosca model to view the details', - selectedRowData: {}, - toscaPolicyModelsData: [], - selectedPolicyModelsData: [], - key: 'add', - showFailAlert: false, - toscaColumns: [ - { title: "#", field: "index", render: rowData => rowData.tableData.id + 1, - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { title: "Policy Model Type", field: "policyModelType", - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { title: "Policy Acronym", field: "policyAcronym", - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { title: "Policy Name", field: "policyName", - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { title: "Version", field: "version", - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { title: "Uploaded By", field: "updatedBy", - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { title: "Uploaded Date", field: "updatedDate", editable: 'never', - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { title: "Created Date", field: "createdDate", editable: 'never', - cellStyle: cellStyle, - headerStyle: headerStyle - } - ], - tableIcons: { - FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />), - LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />), - NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />), - PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />), - ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />), - Search: forwardRef((props, ref) => <Search {...props} ref={ref} />), - SortArrow: forwardRef((props, ref) => <ArrowUpward {...props} ref={ref} />) - } - }; + state = { + show: true, + loopCache: this.props.loopCache, + content: 'Please select Tosca model to view the details', + selectedRowData: {}, + toscaPolicyModelsData: [], + selectedPolicyModelsData: [], + key: 'add', + showFailAlert: false, + toscaColumns: [ + { + title: "#", field: "index", render: rowData => rowData.tableData.id + 1, + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Policy Model Type", field: "policyModelType", + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Policy Acronym", field: "policyAcronym", + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Policy Name", field: "policyName", + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Version", field: "version", + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Uploaded By", field: "updatedBy", + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Uploaded Date", field: "updatedDate", editable: 'never', + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Created Date", field: "createdDate", editable: 'never', + cellStyle: cellStyle, + headerStyle: headerStyle + } + ], + tableIcons: { + FirstPage: forwardRef((props, ref) => <FirstPage { ...props } ref={ ref }/>), + LastPage: forwardRef((props, ref) => <LastPage { ...props } ref={ ref }/>), + NextPage: forwardRef((props, ref) => <ChevronRight { ...props } ref={ ref }/>), + PreviousPage: forwardRef((props, ref) => <ChevronLeft { ...props } ref={ ref }/>), + ResetSearch: forwardRef((props, ref) => <Clear { ...props } ref={ ref }/>), + Search: forwardRef((props, ref) => <Search { ...props } ref={ ref }/>), + SortArrow: forwardRef((props, ref) => <ArrowUpward { ...props } ref={ ref }/>) + } + }; - constructor(props, context) { - super(props, context); - this.handleClose = this.handleClose.bind(this); - this.initializeToscaPolicyModelsInfo = this.initializeToscaPolicyModelsInfo.bind(this); - this.handleYamlContent = this.handleYamlContent.bind(this); - this.getToscaPolicyModelYaml = this.getToscaPolicyModelYaml.bind(this); - this.handleAdd = this.handleAdd.bind(this); - this.handleRemove = this.handleRemove.bind(this); - this.initializeToscaPolicyModelsInfo(); - } + constructor(props, context) { + super(props, context); + this.handleClose = this.handleClose.bind(this); + this.initializeToscaPolicyModelsInfo = this.initializeToscaPolicyModelsInfo.bind(this); + this.handleYamlContent = this.handleYamlContent.bind(this); + this.getToscaPolicyModelYaml = this.getToscaPolicyModelYaml.bind(this); + this.handleAdd = this.handleAdd.bind(this); + this.handleRemove = this.handleRemove.bind(this); + this.initializeToscaPolicyModelsInfo(); + } - initializeToscaPolicyModelsInfo() { - var operationalPolicies = this.state.loopCache.getOperationalPolicies(); - var selectedPolicyModels = []; - for (var policy in operationalPolicies) { - var newRow = operationalPolicies[policy]["policyModel"]; - newRow["policyName"] = operationalPolicies[policy].name; - selectedPolicyModels.push(newRow); - } + initializeToscaPolicyModelsInfo() { + var operationalPolicies = this.state.loopCache.getOperationalPolicies(); + var selectedPolicyModels = []; + for (var policy in operationalPolicies) { + var newRow = operationalPolicies[policy]["policyModel"]; + newRow["policyName"] = operationalPolicies[policy].name; + selectedPolicyModels.push(newRow); + } - PolicyToscaService.getToscaPolicyModels().then(allToscaModels => { - this.setState({ toscaPolicyModelsData: allToscaModels, - selectedPolicyModelsData: selectedPolicyModels}); - }); - } + PolicyToscaService.getToscaPolicyModels().then(allToscaModels => { + this.setState({ + toscaPolicyModelsData: allToscaModels, + selectedPolicyModelsData: selectedPolicyModels + }); + }); + } - getToscaPolicyModelYaml(policyModelType, policyModelVersion) { - if (typeof policyModelType !== "undefined") { - PolicyToscaService.getToscaPolicyModelYaml(policyModelType, policyModelVersion).then(toscaYaml => { - if (toscaYaml.length !== 0) { - this.setState({content: toscaYaml}) - } else { - this.setState({ content: 'No Tosca model Yaml available' }) - } - }); - } else { - this.setState({ content: 'Please select Tosca model to view the details' }) - } - } + getToscaPolicyModelYaml(policyModelType, policyModelVersion) { + if (typeof policyModelType !== "undefined") { + PolicyToscaService.getToscaPolicyModelYaml(policyModelType, policyModelVersion).then(toscaYaml => { + if (toscaYaml.length !== 0) { + this.setState({ content: toscaYaml }) + } else { + this.setState({ content: 'No Tosca model Yaml available' }) + } + }); + } else { + this.setState({ content: 'Please select Tosca model to view the details' }) + } + } - handleYamlContent(event) { - this.setState({ content: event.target.value }); - } + handleYamlContent(event) { + this.setState({ content: event.target.value }); + } - handleClose() { - this.setState({ show: false }); - this.props.history.push('/'); - } + handleClose() { + this.setState({ show: false }); + this.props.history.push('/'); + } - renderAlert() { - return ( - <div> - <Alert variant="danger" show={this.state.showFailAlert} onClose={this.disableAlert} dismissible> - {this.state.showMessage} - </Alert> - </div> - ); - } + renderAlert() { + return ( + <div> + <Alert variant="danger" show={ this.state.showFailAlert } onClose={ this.disableAlert } dismissible> + { this.state.showMessage } + </Alert> + </div> + ); + } - handleAdd() { - LoopService.addOperationalPolicyType(this.state.loopCache.getLoopName(),this.state.selectedRowData.policyModelType,this.state.selectedRowData.version) - .then(pars => { - this.props.loadLoopFunction(this.state.loopCache.getLoopName()); - this.handleClose(); - }) - .catch(error => { - this.setState({ showFailAlert: true, showMessage: "Adding failed with error: " + error.message}); - }); - } + handleAdd() { + LoopService.addOperationalPolicyType(this.state.loopCache.getLoopName(), this.state.selectedRowData.policyModelType, this.state.selectedRowData.version) + .then(pars => { + this.props.loadLoopFunction(this.state.loopCache.getLoopName()); + this.handleClose(); + }) + .catch(error => { + this.setState({ showFailAlert: true, showMessage: "Adding failed with error: " + error.message }); + }); + } - handleRemove() { - LoopService.removeOperationalPolicyType(this.state.loopCache.getLoopName(),this.state.selectedRowData.policyModelType,this.state.selectedRowData.version,this.state.selectedRowData.policyName); - this.props.loadLoopFunction(this.state.loopCache.getLoopName()); - this.handleClose(); - } + handleRemove() { + LoopService.removeOperationalPolicyType(this.state.loopCache.getLoopName(), this.state.selectedRowData.policyModelType, this.state.selectedRowData.version, this.state.selectedRowData.policyName); + this.props.loadLoopFunction(this.state.loopCache.getLoopName()); + this.handleClose(); + } - render() { - return ( - <ModalStyled size="xl" show={this.state.show} onHide={this.handleClose} backdrop="static" keyboard={false} > - <Modal.Header closeButton> - <Modal.Title>Modify Loop Operational Policies</Modal.Title> - </Modal.Header> - <Tabs id="controlled-tab-example" activeKey={this.state.key} onSelect={key => this.setState({ key, selectedRowData: {} })}> - <Tab eventKey="add" title="Add Operational Policies"> - <Modal.Body> - <MaterialTable - title={"View Tosca Policy Models"} - data={this.state.toscaPolicyModelsData} - columns={this.state.toscaColumns} - icons={this.state.tableIcons} - onRowClick={(event, rowData) => {this.getToscaPolicyModelYaml(rowData.policyModelType, rowData.version);this.setState({selectedRowData: rowData})}} - options={{ - headerStyle: rowHeaderStyle, - rowStyle: rowData => ({ - backgroundColor: (this.state.selectedRowData !== {} && this.state.selectedRowData.tableData !== undefined - && this.state.selectedRowData.tableData.id === rowData.tableData.id) ? '#EEE' : '#FFF' - }) - }} - /> - <div> - <TextModal value={this.state.content} onChange={this.handleYamlContent}/> - </div> - </Modal.Body> - {this.renderAlert()} - </Tab> - <Tab eventKey="remove" title="Remove Operational Policies"> - <Modal.Body> - <MaterialTable - title={"Tosca Policy Models already added"} - data={this.state.selectedPolicyModelsData} - columns={this.state.toscaColumns} - icons={this.state.tableIcons} - onRowClick={(event, rowData) => {this.setState({selectedRowData: rowData})}} - options={{ - headerStyle: rowHeaderStyle, - rowStyle: rowData => ({ - backgroundColor: (this.state.selectedRowData !== {} && this.state.selectedRowData.tableData !== undefined - && this.state.selectedRowData.tableData.id === rowData.tableData.id) ? '#EEE' : '#FFF' - }) - }} - /> - </Modal.Body> - </Tab> - </Tabs> - <Modal.Footer> - <Button variant="secondary" type="null" onClick={this.handleClose}>Cancel</Button> - <Button variant="primary" disabled={(this.state.key === "remove")} type="submit" onClick={this.handleAdd}>Add</Button> - <Button variant="primary" disabled={(this.state.key === "add")} type="submit" onClick={this.handleRemove}>Remove</Button> - </Modal.Footer> + render() { + return ( + <ModalStyled size="xl" show={ this.state.show } onHide={ this.handleClose } backdrop="static" keyboard={ false }> + <Modal.Header closeButton> + <Modal.Title>Modify Loop Operational Policies</Modal.Title> + </Modal.Header> + <Tabs id="controlled-tab-example" activeKey={ this.state.key } onSelect={ key => this.setState({ key, selectedRowData: {} }) }> + <Tab eventKey="add" title="Add Operational Policies"> + <Modal.Body> + <MaterialTable + title={ "View Tosca Policy Models" } + data={ this.state.toscaPolicyModelsData } + columns={ this.state.toscaColumns } + icons={ this.state.tableIcons } + onRowClick={ (event, rowData) => { + this.getToscaPolicyModelYaml(rowData.policyModelType, rowData.version); + this.setState({ selectedRowData: rowData }) + } } + options={ { + headerStyle: rowHeaderStyle, + rowStyle: rowData => ({ + backgroundColor: (this.state.selectedRowData !== {} && this.state.selectedRowData.tableData !== undefined + && this.state.selectedRowData.tableData.id === rowData.tableData.id) ? '#EEE' : '#FFF' + }) + } } + /> + <div> + <TextModal value={ this.state.content } onChange={ this.handleYamlContent }/> + </div> + </Modal.Body> + { this.renderAlert() } + </Tab> + <Tab eventKey="remove" title="Remove Operational Policies"> + <Modal.Body> + <MaterialTable + title={ "Tosca Policy Models already added" } + data={ this.state.selectedPolicyModelsData } + columns={ this.state.toscaColumns } + icons={ this.state.tableIcons } + onRowClick={ (event, rowData) => { + this.setState({ selectedRowData: rowData }) + } } + options={ { + headerStyle: rowHeaderStyle, + rowStyle: rowData => ({ + backgroundColor: (this.state.selectedRowData !== {} && this.state.selectedRowData.tableData !== undefined + && this.state.selectedRowData.tableData.id === rowData.tableData.id) ? '#EEE' : '#FFF' + }) + } } + /> + </Modal.Body> + </Tab> + </Tabs> + <Modal.Footer> + <Button variant="secondary" type="null" onClick={ this.handleClose }>Cancel</Button> + <Button variant="primary" disabled={ (this.state.key === "remove") } type="submit" onClick={ this.handleAdd }>Add</Button> + <Button variant="primary" disabled={ (this.state.key === "add") } type="submit" onClick={ this.handleRemove }>Remove</Button> + </Modal.Footer> - </ModalStyled> - ); - } + </ModalStyled> + ); + } } diff --git a/runtime/ui-react/src/components/dialogs/Loop/ModifyLoopModal.test.js b/runtime/ui-react/src/components/dialogs/Loop/ModifyLoopModal.test.js index 055ad0e68..79267af4f 100644 --- a/runtime/ui-react/src/components/dialogs/Loop/ModifyLoopModal.test.js +++ b/runtime/ui-react/src/components/dialogs/Loop/ModifyLoopModal.test.js @@ -28,82 +28,82 @@ import LoopService from '../../../api/LoopService'; import PolicyToscaService from '../../../api/PolicyToscaService'; describe('Verify ModifyLoopModal', () => { - beforeEach(() => { - PolicyToscaService.getToscaPolicyModels = jest.fn().mockImplementation(() => { - return Promise.resolve([{ - "policyModelType":"test", - "policyAcronym":"test", - "version":"1.0.0", - "updatedBy":"", - "updatedDate":"" - }]); - }); - PolicyToscaService.getToscaPolicyModelYaml = jest.fn().mockImplementation(() => { - return Promise.resolve("OK"); - }); - }) + beforeEach(() => { + PolicyToscaService.getToscaPolicyModels = jest.fn().mockImplementation(() => { + return Promise.resolve([{ + "policyModelType": "test", + "policyAcronym": "test", + "version": "1.0.0", + "updatedBy": "", + "updatedDate": "" + }]); + }); + PolicyToscaService.getToscaPolicyModelYaml = jest.fn().mockImplementation(() => { + return Promise.resolve("OK"); + }); + }) - const loopCache = new LoopCache({ - "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca", - "microServicePolicies": [{ - "name": "TCA_h2NMX_v1_0_ResourceInstanceName1_tca", - "modelType": "onap.policies.monitoring.cdap.tca.hi.lo.app", - "properties": {"domain": "measurementsForVfScaling"}, - "shared": false, - "jsonRepresentation": {"schema": {}} - }], - "globalPropertiesJson": { - "dcaeDeployParameters": { - "testMs": { - "location_id": "", - "policy_id": "TCA_h2NMX_v1_0_ResourceInstanceName1_tca" - } - } + const loopCache = new LoopCache({ + "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca", + "microServicePolicies": [{ + "name": "TCA_h2NMX_v1_0_ResourceInstanceName1_tca", + "modelType": "onap.policies.monitoring.cdap.tca.hi.lo.app", + "properties": { "domain": "measurementsForVfScaling" }, + "shared": false, + "jsonRepresentation": { "schema": {} } + }], + "globalPropertiesJson": { + "dcaeDeployParameters": { + "testMs": { + "location_id": "", + "policy_id": "TCA_h2NMX_v1_0_ResourceInstanceName1_tca" } - }); - const historyMock = { push: jest.fn() }; - const flushPromises = () => new Promise(setImmediate); + } + } + }); + const historyMock = { push: jest.fn() }; + const flushPromises = () => new Promise(setImmediate); - it('Test handleClose', () => { - const handleClose = jest.spyOn(ModifyLoopModal.prototype,'handleClose'); - const component = mount(<ModifyLoopModal history={historyMock} loopCache={loopCache}/>) + it('Test handleClose', () => { + const handleClose = jest.spyOn(ModifyLoopModal.prototype, 'handleClose'); + const component = mount(<ModifyLoopModal history={ historyMock } loopCache={ loopCache }/>) - component.find('[variant="secondary"]').get(0).props.onClick(); + component.find('[variant="secondary"]').get(0).props.onClick(); - expect(handleClose).toHaveBeenCalledTimes(1); - expect(component.state('show')).toEqual(false); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); - }); + expect(handleClose).toHaveBeenCalledTimes(1); + expect(component.state('show')).toEqual(false); + expect(historyMock.push.mock.calls[0]).toEqual(['/']); + }); - it('Test getToscaPolicyModelYaml', async () => { - const flushPromises = () => new Promise(setImmediate); - const component = mount(<ModifyLoopModal history={historyMock} loopCache={loopCache}/>) - component.setState({ - "selectedRowData": {"tableData":{"id":0}} - }); - const instance = component.instance(); + it('Test getToscaPolicyModelYaml', async () => { + const flushPromises = () => new Promise(setImmediate); + const component = mount(<ModifyLoopModal history={ historyMock } loopCache={ loopCache }/>) + component.setState({ + "selectedRowData": { "tableData": { "id": 0 } } + }); + const instance = component.instance(); - instance.getToscaPolicyModelYaml("","1.0.0"); - expect(component.state('content')).toEqual("Please select Tosca model to view the details"); + instance.getToscaPolicyModelYaml("", "1.0.0"); + expect(component.state('content')).toEqual("Please select Tosca model to view the details"); - instance.getToscaPolicyModelYaml("test","1.0.0"); - await flushPromises(); - expect(component.state('content')).toEqual("OK"); + instance.getToscaPolicyModelYaml("test", "1.0.0"); + await flushPromises(); + expect(component.state('content')).toEqual("OK"); - PolicyToscaService.getToscaPolicyModelYaml = jest.fn().mockImplementation(() => { - return Promise.resolve(""); - }); - instance.getToscaPolicyModelYaml("test","1.0.0"); - await flushPromises(); - expect(component.state('content')).toEqual("No Tosca model Yaml available"); + PolicyToscaService.getToscaPolicyModelYaml = jest.fn().mockImplementation(() => { + return Promise.resolve(""); }); + instance.getToscaPolicyModelYaml("test", "1.0.0"); + await flushPromises(); + expect(component.state('content')).toEqual("No Tosca model Yaml available"); + }); - it('Test handleYamlContent', async () => { - const component = mount(<ModifyLoopModal loopCache={loopCache}/>) - const instance = component.instance(); + it('Test handleYamlContent', async () => { + const component = mount(<ModifyLoopModal loopCache={ loopCache }/>) + const instance = component.instance(); - const event = {"target":{"value":"testValue"}} - instance.handleYamlContent(event); - expect(component.state('content')).toEqual("testValue"); - }); -});
\ No newline at end of file + const event = { "target": { "value": "testValue" } } + instance.handleYamlContent(event); + expect(component.state('content')).toEqual("testValue"); + }); +}); diff --git a/runtime/ui-react/src/components/dialogs/Loop/OpenLoopModal.js b/runtime/ui-react/src/components/dialogs/Loop/OpenLoopModal.js index b45df6502..b6407fbbb 100644 --- a/runtime/ui-react/src/components/dialogs/Loop/OpenLoopModal.js +++ b/runtime/ui-react/src/components/dialogs/Loop/OpenLoopModal.js @@ -34,104 +34,106 @@ import SvgGenerator from '../../loop_viewer/svg/SvgGenerator'; import LoopCache from '../../../api/LoopCache'; const ModalStyled = styled(Modal)` - background-color: transparent; + background-color: transparent; ` const CheckBoxStyled = styled(FormCheck.Input)` - margin-left:3rem; + margin-left: 3rem; ` export default class OpenLoopModal extends React.Component { - constructor(props, context) { - super(props, context); + constructor(props, context) { + super(props, context); - this.getLoopNames = this.getLoopNames.bind(this); - this.handleOpen = this.handleOpen.bind(this); - this.handleClose = this.handleClose.bind(this); - this.handleDropDownListChange = this.handleDropDownListChange.bind(this); - this.renderSvg = this.renderSvg.bind(this); - this.showReadOnly = props.showReadOnly !== undefined ? props.showReadOnly : true; - this.state = { - show: true, - chosenLoopName: '', - loopNames: [], - loopCacheOpened: new LoopCache({}) - }; - } + this.getLoopNames = this.getLoopNames.bind(this); + this.handleOpen = this.handleOpen.bind(this); + this.handleClose = this.handleClose.bind(this); + this.handleDropDownListChange = this.handleDropDownListChange.bind(this); + this.renderSvg = this.renderSvg.bind(this); + this.showReadOnly = props.showReadOnly !== undefined ? props.showReadOnly : true; + this.state = { + show: true, + chosenLoopName: '', + loopNames: [], + loopCacheOpened: new LoopCache({}) + }; + } - componentWillMount() { - this.getLoopNames(); - } + componentWillMount() { + this.getLoopNames(); + } - handleClose() { - this.setState({ show: false }); - this.props.history.push('/'); - } + handleClose() { + this.setState({ show: false }); + this.props.history.push('/'); + } - handleDropDownListChange(e) { - LoopService.getLoop(e.value).then(loop => { - this.setState({ - chosenLoopName: e.value, - loopCacheOpened: new LoopCache(loop) - }); - }); - } + handleDropDownListChange(e) { + LoopService.getLoop(e.value).then(loop => { + this.setState({ + chosenLoopName: e.value, + loopCacheOpened: new LoopCache(loop) + }); + }); + } - getLoopNames() { - LoopService.getLoopNames().then(loopNames => { - if (Object.entries(loopNames).length !== 0) { - const loopOptions = loopNames.filter(loopName => loopName!=='undefined').map((loopName) => { return { label: loopName, value: loopName } }); - this.setState({ loopNames: loopOptions }) - } - }); - } + getLoopNames() { + LoopService.getLoopNames().then(loopNames => { + if (Object.entries(loopNames).length !== 0) { + const loopOptions = loopNames.filter(loopName => loopName !== 'undefined').map((loopName) => { + return { label: loopName, value: loopName } + }); + this.setState({ loopNames: loopOptions }) + } + }); + } - handleOpen() { - console.info("Loop " + this.state.chosenLoopName + " is chosen"); - this.handleClose(); - this.props.loadLoopFunction(this.state.chosenLoopName); - } + handleOpen() { + console.info("Loop " + this.state.chosenLoopName + " is chosen"); + this.handleClose(); + this.props.loadLoopFunction(this.state.chosenLoopName); + } - renderSvg() { - return( - <SvgGenerator loopCache={this.state.loopCacheOpened} clickable={false} generatedFrom={SvgGenerator.GENERATED_FROM_INSTANCE}/> - ); - } + renderSvg() { + return ( + <SvgGenerator loopCache={ this.state.loopCacheOpened } clickable={ false } generatedFrom={ SvgGenerator.GENERATED_FROM_INSTANCE }/> + ); + } - render() { - return ( - <ModalStyled size="xl" show={this.state.show} onHide={this.handleClose} backdrop="static" keyboard={false} > - <Modal.Header closeButton> - <Modal.Title>Open Model</Modal.Title> - </Modal.Header> - <Modal.Body> - <Form.Group as={Row} controlId="formPlaintextEmail"> - <Form.Label column sm="2">Model Name:</Form.Label> - <Col sm="10"> - <Select onChange={this.handleDropDownListChange} - options={this.state.loopNames} /> - </Col> - </Form.Group> - <Form.Group as={Row} style={{alignItems: 'center'}} controlId="formSvgPreview"> - <Form.Label column sm="2">Model Preview:</Form.Label> - <Col sm="10"> - {this.renderSvg()} - </Col> - </Form.Group> - {this.showReadOnly === true ? - <Form.Group as={Row} controlId="formBasicCheckbox"> - <Form.Check> - <FormCheck.Label>Read Only Mode:</FormCheck.Label> - <CheckBoxStyled style={{marginLeft: '3.5em'}} type="checkbox" /> - </Form.Check> - </Form.Group> - : null} - </Modal.Body> - <Modal.Footer> - <Button variant="secondary" type="null" onClick={this.handleClose}>Cancel</Button> - <Button variant="primary" type="submit" onClick={this.handleOpen}>Open</Button> - </Modal.Footer> - </ModalStyled> + render() { + return ( + <ModalStyled size="xl" show={ this.state.show } onHide={ this.handleClose } backdrop="static" keyboard={ false }> + <Modal.Header closeButton> + <Modal.Title>Open Model</Modal.Title> + </Modal.Header> + <Modal.Body> + <Form.Group as={ Row } controlId="formPlaintextEmail"> + <Form.Label column sm="2">Model Name:</Form.Label> + <Col sm="10"> + <Select onChange={ this.handleDropDownListChange } + options={ this.state.loopNames }/> + </Col> + </Form.Group> + <Form.Group as={ Row } style={ { alignItems: 'center' } } controlId="formSvgPreview"> + <Form.Label column sm="2">Model Preview:</Form.Label> + <Col sm="10"> + { this.renderSvg() } + </Col> + </Form.Group> + { this.showReadOnly === true ? + <Form.Group as={ Row } controlId="formBasicCheckbox"> + <Form.Check> + <FormCheck.Label>Read Only Mode:</FormCheck.Label> + <CheckBoxStyled style={ { marginLeft: '3.5em' } } type="checkbox"/> + </Form.Check> + </Form.Group> + : null } + </Modal.Body> + <Modal.Footer> + <Button variant="secondary" type="null" onClick={ this.handleClose }>Cancel</Button> + <Button variant="primary" type="submit" onClick={ this.handleOpen }>Open</Button> + </Modal.Footer> + </ModalStyled> - ); - } + ); + } } diff --git a/runtime/ui-react/src/components/dialogs/Loop/OpenLoopModal.test.js b/runtime/ui-react/src/components/dialogs/Loop/OpenLoopModal.test.js index 1865869df..6b2dc4afb 100644 --- a/runtime/ui-react/src/components/dialogs/Loop/OpenLoopModal.test.js +++ b/runtime/ui-react/src/components/dialogs/Loop/OpenLoopModal.test.js @@ -28,15 +28,15 @@ import LoopService from '../../../api/LoopService'; describe('Verify OpenLoopModal', () => { beforeEach(() => { - fetch.resetMocks(); - fetch.mockResponse(JSON.stringify([ - "LOOP_gmtAS_v1_0_ResourceInstanceName1_tca", - "LOOP_gmtAS_v1_0_ResourceInstanceName1_tca_3", - "LOOP_gmtAS_v1_0_ResourceInstanceName2_tca_2" - ])); + fetch.resetMocks(); + fetch.mockResponse(JSON.stringify([ + "LOOP_gmtAS_v1_0_ResourceInstanceName1_tca", + "LOOP_gmtAS_v1_0_ResourceInstanceName1_tca_3", + "LOOP_gmtAS_v1_0_ResourceInstanceName2_tca_2" + ])); }); - it('Test the render method', () => { + it('Test the render method', () => { const component = shallow(<OpenLoopModal/>); expect(component).toMatchSnapshot(); @@ -45,13 +45,14 @@ describe('Verify OpenLoopModal', () => { it('Onchange event', async () => { const flushPromises = () => new Promise(setImmediate); LoopService.getLoop = jest.fn().mockImplementation(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => {} - }); - }); - const event = {value: 'LOOP_gmtAS_v1_0_ResourceInstanceName1_tca_3'}; + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + } + }); + }); + const event = { value: 'LOOP_gmtAS_v1_0_ResourceInstanceName1_tca_3' }; const component = shallow(<OpenLoopModal/>); component.find('StateManager').simulate('change', event); await flushPromises(); @@ -61,30 +62,30 @@ describe('Verify OpenLoopModal', () => { it('Test handleClose', () => { - const historyMock = { push: jest.fn() }; - const handleClose = jest.spyOn(OpenLoopModal.prototype,'handleClose'); - const component = shallow(<OpenLoopModal history={historyMock} />) + const historyMock = { push: jest.fn() }; + const handleClose = jest.spyOn(OpenLoopModal.prototype, 'handleClose'); + const component = shallow(<OpenLoopModal history={ historyMock }/>) component.find('[variant="secondary"]').prop('onClick')(); expect(handleClose).toHaveBeenCalledTimes(1); expect(component.state('show')).toEqual(false); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); - + expect(historyMock.push.mock.calls[0]).toEqual(['/']); + handleClose.mockClear(); }); - it('Test handleSubmit', () => { + it('Test handleSubmit', () => { const historyMock = { push: jest.fn() }; - const loadLoopFunction = jest.fn(); - const handleOpen = jest.spyOn(OpenLoopModal.prototype,'handleOpen'); - const component = shallow(<OpenLoopModal history={historyMock} loadLoopFunction={loadLoopFunction}/>) + const loadLoopFunction = jest.fn(); + const handleOpen = jest.spyOn(OpenLoopModal.prototype, 'handleOpen'); + const component = shallow(<OpenLoopModal history={ historyMock } loadLoopFunction={ loadLoopFunction }/>) component.find('[variant="primary"]').prop('onClick')(); expect(handleOpen).toHaveBeenCalledTimes(1); expect(component.state('show')).toEqual(false); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); + expect(historyMock.push.mock.calls[0]).toEqual(['/']); handleOpen.mockClear(); }); diff --git a/runtime/ui-react/src/components/dialogs/ManageDictionaries/ManageDictionaries.js b/runtime/ui-react/src/components/dialogs/ManageDictionaries/ManageDictionaries.js index 90bbc887c..d7ba8d1c6 100644 --- a/runtime/ui-react/src/components/dialogs/ManageDictionaries/ManageDictionaries.js +++ b/runtime/ui-react/src/components/dialogs/ManageDictionaries/ManageDictionaries.js @@ -29,7 +29,7 @@ import Col from 'react-bootstrap/Col'; import styled from 'styled-components'; import TemplateMenuService from '../../../api/TemplateService'; import CsvToJson from '../../../utils/CsvToJson'; -import MaterialTable, {MTableToolbar} from "material-table"; +import MaterialTable, { MTableToolbar } from "material-table"; import IconButton from '@material-ui/core/IconButton'; import Tooltip from '@material-ui/core/Tooltip'; import AddBox from '@material-ui/icons/AddBox'; @@ -51,581 +51,587 @@ import ViewColumn from '@material-ui/icons/ViewColumn'; const ModalStyled = styled(Modal)` - @media (min-width: 1200px) { - .modal-xl { - max-width: 96%; - } - } - background-color: transparent; + @media (min-width: 1200px) { + .modal-xl { + max-width: 96%; + } + } + background-color: transparent; ` const MTableToolbarStyled = styled(MTableToolbar)` - display: flex; - flex-direction: row; - align-items: center; + display: flex; + flex-direction: row; + align-items: center; ` const ColPullLeftStyled = styled(Col)` - display: flex; - flex-direction: row; - align-items: center; - margin-left: -40px; + display: flex; + flex-direction: row; + align-items: center; + margin-left: -40px; ` const cellStyle = { border: '1px solid black' }; -const headerStyle = { backgroundColor: '#ddd', border: '2px solid black' }; -const rowHeaderStyle = {backgroundColor:'#ddd', fontSize: '15pt', text: 'bold', border: '1px solid black'}; +const headerStyle = { backgroundColor: '#ddd', border: '2px solid black' }; +const rowHeaderStyle = { backgroundColor: '#ddd', fontSize: '15pt', text: 'bold', border: '1px solid black' }; let dictList = []; let subDictFlag = false; function SelectSubDictType(props) { - const {onChange} = props; - const selectedValues = (e) => { - let options = e.target.options; - let SelectedDictTypes = ''; - for (let dictType = 0, values = options.length; dictType < values; dictType++) { - if (options[dictType].selected) { - SelectedDictTypes = SelectedDictTypes.concat(options[dictType].value); - SelectedDictTypes = SelectedDictTypes.concat('|'); - } - } - SelectedDictTypes = SelectedDictTypes.slice(0,-1); - onChange(SelectedDictTypes); - } - // When the subDictFlag is true, we need to disable selection of element "type" - return( - <div> - <select disabled={subDictFlag} multiple={true} onChange={selectedValues}> - <option value="string">string</option> - <option value="number">number</option> - <option value="datetime">datetime</option> - <option value="map">map</option> - <option value="json">json</option> - </select> - </div> - ); + const { onChange } = props; + const selectedValues = (e) => { + let options = e.target.options; + let SelectedDictTypes = ''; + for (let dictType = 0, values = options.length; dictType < values; dictType++) { + if (options[dictType].selected) { + SelectedDictTypes = SelectedDictTypes.concat(options[dictType].value); + SelectedDictTypes = SelectedDictTypes.concat('|'); + } + } + SelectedDictTypes = SelectedDictTypes.slice(0, -1); + onChange(SelectedDictTypes); + } + // When the subDictFlag is true, we need to disable selection of element "type" + return ( + <div> + <select disabled={ subDictFlag } multiple={ true } onChange={ selectedValues }> + <option value="string">string</option> + <option value="number">number</option> + <option value="datetime">datetime</option> + <option value="map">map</option> + <option value="json">json</option> + </select> + </div> + ); } function SubDict(props) { - const {onChange} = props; - const subDicts = []; - subDicts.push('none'); - if (dictList !== undefined && dictList.length > 0) { - let item; - for(item in dictList) { - if(dictList[item].secondLevelDictionary === 1) { - subDicts.push(dictList[item].name); - } - } - } - let optionItems = []; - for (let i=0; i<subDicts.length; ++i) { - if (i === 0) { - optionItems.push(<option selected key={subDicts[i]}>{subDicts[i]}</option>); - } else { - optionItems.push(<option key={subDicts[i]}>{subDicts[i]}</option>); - } - } - - function selectedValue (e) { - onChange(e.target.value); - } - // When the subDictFlag is true, we need to disable selection of - // the sub-dictionary flag - return( - <select disabled={subDictFlag} onChange={selectedValue} > - {optionItems} - </select> - ); + const { onChange } = props; + const subDicts = []; + subDicts.push('none'); + if (dictList !== undefined && dictList.length > 0) { + let item; + for (item in dictList) { + if (dictList[item].secondLevelDictionary === 1) { + subDicts.push(dictList[item].name); + } + } + } + let optionItems = []; + for (let i = 0; i < subDicts.length; ++i) { + if (i === 0) { + optionItems.push(<option selected key={ subDicts[i] }>{ subDicts[i] }</option>); + } else { + optionItems.push(<option key={ subDicts[i] }>{ subDicts[i] }</option>); + } + } + + function selectedValue(e) { + onChange(e.target.value); + } + + // When the subDictFlag is true, we need to disable selection of + // the sub-dictionary flag + return ( + <select disabled={ subDictFlag } onChange={ selectedValue }> + { optionItems } + </select> + ); } export default class ManageDictionaries extends React.Component { - constructor(props, context) { - super(props, context); - this.addDictionaryElementRow = this.addDictionaryElementRow.bind(this); - this.addDictionaryRow = this.addDictionaryRow.bind(this); - this.addReplaceDictionaryRequest = this.addReplaceDictionaryRequest.bind(this); - this.clickHandler = this.clickHandler.bind(this); - this.deleteDictionaryElementRow = this.deleteDictionaryElementRow.bind(this); - this.deleteDictionaryRequest = this.deleteDictionaryRequest.bind(this); - this.deleteDictionaryRow = this.deleteDictionaryRow.bind(this); - this.fileSelectedHandler = this.fileSelectedHandler.bind(this); - this.getDictionaries = this.getDictionaries.bind(this); - this.getDictionaryElements = this.getDictionaryElements.bind(this); - this.handleClose = this.handleClose.bind(this); - this.handleDictionaryRowClick = this.handleDictionaryRowClick.bind(this); - this.importCsvData = this.importCsvData.bind(this); - this.updateDictionaryElementRow = this.updateDictionaryElementRow.bind(this); - this.updateDictionaryElementsRequest = this.updateDictionaryElementsRequest.bind(this); - this.updateDictionaryRow = this.updateDictionaryRow.bind(this); - this.readOnly = props.readOnly !== undefined ? props.readOnly : false; - this.state = { - show: true, - currentSelectedDictionary: null, - exportFilename: '', - content: null, - dictionaryElements: [], - tableIcons: { - Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />), - Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />), - DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />), - Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />), - Check: forwardRef((props, ref) => <Check {...props} ref={ref} />), - Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />), - Export: forwardRef((props, ref) => <VerticalAlignBottomIcon {...props} ref={ref} />), - Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />), - FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />), - LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />), - NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />), - PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />), - ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />), - Search: forwardRef((props, ref) => <Search {...props} ref={ref} />), - SortArrow: forwardRef((props, ref) => <ArrowUpward {...props} ref={ref} />), - ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />), - ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />) - }, - dictColumns: [ - { - title: "Dictionary Name", field: "name",editable: 'onAdd', - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { - title: "Sub Dictionary ?", field: "secondLevelDictionary", lookup: {0: 'No', 1: 'Yes'}, - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { - title: "Dictionary Type", field: "subDictionaryType",lookup: {string: 'string', number: 'number'}, - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { - title: "Updated By", field: "updatedBy", editable: 'never', - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { - title: "Last Updated Date", field: "updatedDate", editable: 'never', - cellStyle: cellStyle, - headerStyle: headerStyle - } - ], - dictElementColumns: [ - { - title: "Element Short Name", field: "shortName",editable: 'onAdd', - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { - title: "Element Name", field: "name", - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { - title: "Element Description", field: "description", - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { - title: "Element Type", field: "type", - editComponent: props => ( - <div> - <SelectSubDictType value={props.value} onChange={props.onChange} /> - </div> - ), - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { - title: "Sub-Dictionary", field: "subDictionary", - editComponent: props => ( - <div> - <SubDict value={props.value} onChange={props.onChange} /> - </div> - ), - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { - title: "Updated By", field: "updatedBy", editable: 'never', - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { - title: "Updated Date", field: "updatedDate", editable: 'never', - cellStyle: cellStyle, - headerStyle: headerStyle - } - ] - } - } - - componentDidMount() { - this.getDictionaries(); - } - - getDictionaries() { - TemplateMenuService.getDictionary().then(arrayOfdictionaries => { - this.setState({ dictionaries: arrayOfdictionaries, currentSelectedDictionary: null }) - // global variable setting used functional components in this file - dictList = arrayOfdictionaries; - }).catch(() => { - console.error('Failed to retrieve dictionaries'); - this.setState({ dictionaries: [], currentSelectedDictionary: null }) - }); - } - - getDictionaryElements(dictionaryName) { - TemplateMenuService.getDictionaryElements(dictionaryName).then(dictionaryElements => { - this.setState({ dictionaryElements: dictionaryElements.dictionaryElements} ); - this.setState({ currentSelectDictionary: dictionaryName }); - }).catch(() => console.error('Failed to retrieve dictionary elements')) - } - - clickHandler(rowData) { - this.getDictionaries(); - } - - handleClose() { - this.setState({ show: false }); - this.props.history.push('/'); - } - - addReplaceDictionaryRequest(dictionaryEntry) { - TemplateMenuService.insDictionary(dictionaryEntry) - .then(resp => { - this.getDictionaries(); - }) - .catch(() => console.error('Failed to insert new dictionary elements')); - } - - updateDictionaryElementsRequest(dictElements) { - let reqData = { "name": this.state.currentSelectedDictionary, 'dictionaryElements': dictElements }; - TemplateMenuService.insDictionaryElements(reqData) - .then(resp => { this.getDictionaryElements(this.state.currentSelectedDictionary) }) - .catch(() => console.error('Failed to update dictionary elements')); - } - - deleteDictionaryRequest(dictionaryName) { - TemplateMenuService.deleteDictionary(dictionaryName) - .then(resp => { - this.getDictionaries(); - }) - .catch(() => console.error('Failed to delete dictionary')); - } - - deleteDictionaryElementRequest(dictionaryName, elemenetShortName) { - TemplateMenuService.deleteDictionaryElements({ 'name': dictionaryName, 'shortName': elemenetShortName }) - .then(resp => { - this.getDictionaryElements(dictionaryName); - }) - .catch(() => console.error('Failed to delete dictionary elements')); - } - - fileSelectedHandler = (event) => { - - if (event.target.files[0].type === 'text/csv' || event.target.files[0].type === 'application/vnd.ms-excel') { - if (event.target.files && event.target.files[0]) { - const reader = new FileReader(); - reader.onload = (e) => { - let errorMessages = this.importCsvData(reader.result); - if (errorMessages !== '') { - alert(errorMessages); - } - } - reader.readAsText(event.target.files[0]); - } - } else { - alert('Please upload .csv extention files only.'); - } - } - - importCsvData(rawCsvData) { - - const jsonKeyNames = [ 'shortName', 'name', 'description', 'type', 'subDictionary' ]; - const userHeaderNames = [ 'Element Short Name', 'Element Name', 'Element Description', 'Element Type', 'Sub-Dictionary' ]; - const validTypes = ['string','number','datetime','json','map']; - - let mandatory; - - if (subDictFlag) { - mandatory = [ true, true, true, false, false ]; - } else { - mandatory = [ true, true, true, true, false ]; - } - - let result = CsvToJson(rawCsvData, ',', '||||', userHeaderNames, jsonKeyNames, mandatory); - - let errorMessages = result.errorMessages; - let jsonObjArray = result.jsonObjArray; - - let validTypesErrorMesg = ''; - - for (let i=0; i < validTypes.length; ++i) { - if (i === 0) { - validTypesErrorMesg = validTypes[i]; - } else { - validTypesErrorMesg += ',' + validTypes[i]; - } - } - - if (errorMessages !== '') { - return errorMessages; - } - - // Perform further checks on data that is now in JSON form - let subDictionaries = []; - - // NOTE: dictList is a global variable maintained faithfully - // by the getDictionaries() method outside this import - // functionality. - let item; - for (item in dictList) { - if (dictList[item].secondLevelDictionary === 1) { - subDictionaries.push(dictList[item].name); - } - }; - - // Check for valid Sub-Dictionary and Element Type values - subDictionaries = subDictionaries.toString(); - let row = 2; - let dictElem; - for (dictElem of jsonObjArray) { - let itemKey; - for (itemKey in dictElem){ - let value = dictElem[itemKey].trim(); - let keyIndex = jsonKeyNames.indexOf(itemKey); - if (itemKey === 'shortName' && /[^a-zA-Z0-9-_.]/.test(value)) { - errorMessages += '\n' + userHeaderNames[keyIndex] + - ' at row #' + row + - ' can only contain alphanumeric characters and periods, hyphens or underscores'; - } - if (itemKey === 'type' && validTypes.indexOf(value) < 0) { - errorMessages += '\nInvalid value of "' + value + '" for "' + userHeaderNames[keyIndex] + '" at row #' + row; - errorMessages += '\nValid types are: ' + validTypesErrorMesg; - } - if (value !== "" && itemKey === 'subDictionary' && subDictionaries.indexOf(value) < 0) { - errorMessages += '\nInvalid Sub-Dictionary value of "' + value + '" at row #' + row; - } - } - ++row; - } - if (errorMessages === '') { - // We made it through all the checks. Send it to back end - this.updateDictionaryElementsRequest(jsonObjArray); - } - - return errorMessages; - } - - addDictionaryRow(newData) { - let validData = true; - return new Promise((resolve, reject) => { - setTimeout(() => { - if (/[^a-zA-Z0-9-_.]/.test(newData.name)) { - validData = false; - alert('Please enter alphanumeric input. Only allowed special characters are:(period, hyphen, underscore)'); - reject(); - } - for (let i = 0; i < this.state.dictionaries.length; i++) { - if (this.state.dictionaries[i].name === newData.name) { - validData = false; - alert(newData.name + ' dictionary name already exists') - reject(); - } - } - if (validData) { - this.addReplaceDictionaryRequest(newData); - } - resolve(); - }, 1000); - }); - } - - - updateDictionaryRow(newData, oldData) { - let validData = true; - return new Promise((resolve, reject) => { - setTimeout(() => { - if (/[^a-zA-Z0-9-_.]/.test(newData.name)) { - validData = false; - alert('Please enter alphanumberic input. Only allowed special characters are:(period, hyphen, underscore)'); - reject(); - } - if (validData) { - this.addReplaceDictionaryRequest(newData); - } - resolve(); - }, 1000); - }); - } - - deleteDictionaryRow(oldData) { - return new Promise((resolve, reject) => { - setTimeout(() => { - this.deleteDictionaryRequest(oldData.name); - resolve(); - }, 1000); - }); - } - - addDictionaryElementRow(newData) { - return new Promise((resolve, reject) => { - setTimeout(() => { - let dictionaryElements = this.state.dictionaryElements; - let errorMessages = ''; - for (let i = 0; i < this.state.dictionaryElements.length; i++) { - if (this.state.dictionaryElements[i].shortName === newData.shortName) { - alert('Short Name "' + newData.shortName + '" already exists'); - reject(""); - } - } - // MaterialTable returns no property at all if the user has not touched a - // new column, so we want to add the property with an emptry string - // for several cases if that is the case to simplify other checks. - if (newData.description === undefined) { - newData.description = ""; - } - if (newData.subDictionary === undefined) { - newData.subDictionary = null; - } - if (newData.type === undefined) { - newData.type = ""; - } - if (!newData.shortName && /[^a-zA-Z0-9-_.]/.test(newData.shortName)) { - errorMessages += '\nShort Name is limited to alphanumeric characters and also period, hyphen, and underscore'; - } - if (!newData.shortName){ - errorMessages += '\nShort Name must be specified'; - } - if (!newData.name){ - errorMessages += '\nElement Name must be specified'; - } - if (!newData.type && !subDictFlag){ - errorMessages += '\nElement Type must be specified'; - } - if (errorMessages === '') { - dictionaryElements.push(newData); - this.updateDictionaryElementsRequest([newData]); - resolve(); - } else { - alert(errorMessages); - reject(""); - } - }, 1000); - }); - } - - updateDictionaryElementRow(newData, oldData) { - return new Promise((resolve, reject) => { - setTimeout(() => { - let dictionaryElements = this.state.dictionaryElements; - let validData = true; - if (!newData.type) { - validData = false; - alert('Element Type cannot be null'); - reject(); - } - if (validData) { - const index = dictionaryElements.indexOf(oldData); - dictionaryElements[index] = newData; - this.updateDictionaryElementsRequest([newData]); - } - resolve(); - }, 1000); - }); - } - - - deleteDictionaryElementRow(oldData) { - return new Promise((resolve) => { - setTimeout(() => { - this.deleteDictionaryElementRequest(this.state.currentSelectedDictionary, oldData.shortName); - resolve(); - }, 1000); - }); - } - - handleDictionaryRowClick(event, rowData) { - subDictFlag = rowData.secondLevelDictionary === 1 ? true : false; - this.setState({ - currentSelectedDictionary : rowData.name, - exportFilename: rowData.name - }) - this.getDictionaryElements(rowData.name); - } - - render() { - return ( - <ModalStyled size="xl" show={this.state.show} onHide={this.handleClose} backdrop="static" keyboard={false} > - <Modal.Header closeButton> - <Modal.Title>Manage Dictionaries</Modal.Title> - </Modal.Header> - <Modal.Body> - {this.state.currentSelectedDictionary === null ? - <MaterialTable - title={"Dictionary List"} - data={this.state.dictionaries} - columns={this.state.dictColumns} - icons={this.state.tableIcons} - onRowClick={this.handleDictionaryRowClick} - options={{ - headerStyle: rowHeaderStyle, - }} - editable={!this.readOnly ? - { - onRowAdd: this.addDictionaryRow, - onRowUpdate: this.updateDictionaryRow, - onRowDelete: this.deleteDictionaryRow - } : undefined } - /> : null - } - {this.state.currentSelectedDictionary !== null ? - <MaterialTable - title={'Dictionary Elements List for ' + (subDictFlag ? 'Sub-Dictionary "' : '"') + this.state.currentSelectedDictionary + '"'} - data={this.state.dictionaryElements} - columns={this.state.dictElementColumns} - icons={this.state.tableIcons} - options={{ - exportAllData: true, - exportButton: true, - exportFileName: this.state.exportFilename, - headerStyle:{backgroundColor:'white', fontSize: '15pt', text: 'bold', border: '1px solid black'} - }} - components={{ - Toolbar: props => ( - <Row> - <Col sm="11"> - <MTableToolbarStyled {...props} /> - </Col> - <ColPullLeftStyled sm="1"> - <Tooltip title="Import" placement = "bottom"> - <IconButton aria-label="import" disabled={this.readOnly} onClick={() => this.fileUpload.click()}> - <VerticalAlignTopIcon /> - </IconButton> - </Tooltip> - <input type="file" ref={(fileUpload) => {this.fileUpload = fileUpload;}} - style={{ visibility: 'hidden', width: '1px' }} onChange={this.fileSelectedHandler} /> - </ColPullLeftStyled> - </Row> - ) - }} - editable={!this.readOnly ? - { - onRowAdd: this.addDictionaryElementRow, - onRowUpdate: this.updateDictionaryElementRow, - onRowDelete: this.deleteDictionaryElementRow - } : undefined - } - /> : null - } - {this.state.currentSelectedDictionary !== null ? <button onClick={this.clickHandler} style={{marginTop: '25px'}}>Go Back to Dictionaries List</button>:""} - </Modal.Body> - <Modal.Footer> - <Button variant="secondary" type="null" onClick={this.handleClose}>Close</Button> - </Modal.Footer> - </ModalStyled> - ); - } + constructor(props, context) { + super(props, context); + this.addDictionaryElementRow = this.addDictionaryElementRow.bind(this); + this.addDictionaryRow = this.addDictionaryRow.bind(this); + this.addReplaceDictionaryRequest = this.addReplaceDictionaryRequest.bind(this); + this.clickHandler = this.clickHandler.bind(this); + this.deleteDictionaryElementRow = this.deleteDictionaryElementRow.bind(this); + this.deleteDictionaryRequest = this.deleteDictionaryRequest.bind(this); + this.deleteDictionaryRow = this.deleteDictionaryRow.bind(this); + this.fileSelectedHandler = this.fileSelectedHandler.bind(this); + this.getDictionaries = this.getDictionaries.bind(this); + this.getDictionaryElements = this.getDictionaryElements.bind(this); + this.handleClose = this.handleClose.bind(this); + this.handleDictionaryRowClick = this.handleDictionaryRowClick.bind(this); + this.importCsvData = this.importCsvData.bind(this); + this.updateDictionaryElementRow = this.updateDictionaryElementRow.bind(this); + this.updateDictionaryElementsRequest = this.updateDictionaryElementsRequest.bind(this); + this.updateDictionaryRow = this.updateDictionaryRow.bind(this); + this.readOnly = props.readOnly !== undefined ? props.readOnly : false; + this.state = { + show: true, + currentSelectedDictionary: null, + exportFilename: '', + content: null, + dictionaryElements: [], + tableIcons: { + Add: forwardRef((props, ref) => <AddBox { ...props } ref={ ref }/>), + Delete: forwardRef((props, ref) => <DeleteOutline { ...props } ref={ ref }/>), + DetailPanel: forwardRef((props, ref) => <ChevronRight { ...props } ref={ ref }/>), + Edit: forwardRef((props, ref) => <Edit { ...props } ref={ ref }/>), + Check: forwardRef((props, ref) => <Check { ...props } ref={ ref }/>), + Clear: forwardRef((props, ref) => <Clear { ...props } ref={ ref }/>), + Export: forwardRef((props, ref) => <VerticalAlignBottomIcon { ...props } ref={ ref }/>), + Filter: forwardRef((props, ref) => <FilterList { ...props } ref={ ref }/>), + FirstPage: forwardRef((props, ref) => <FirstPage { ...props } ref={ ref }/>), + LastPage: forwardRef((props, ref) => <LastPage { ...props } ref={ ref }/>), + NextPage: forwardRef((props, ref) => <ChevronRight { ...props } ref={ ref }/>), + PreviousPage: forwardRef((props, ref) => <ChevronLeft { ...props } ref={ ref }/>), + ResetSearch: forwardRef((props, ref) => <Clear { ...props } ref={ ref }/>), + Search: forwardRef((props, ref) => <Search { ...props } ref={ ref }/>), + SortArrow: forwardRef((props, ref) => <ArrowUpward { ...props } ref={ ref }/>), + ThirdStateCheck: forwardRef((props, ref) => <Remove { ...props } ref={ ref }/>), + ViewColumn: forwardRef((props, ref) => <ViewColumn { ...props } ref={ ref }/>) + }, + dictColumns: [ + { + title: "Dictionary Name", field: "name", editable: 'onAdd', + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Sub Dictionary ?", field: "secondLevelDictionary", lookup: { 0: 'No', 1: 'Yes' }, + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Dictionary Type", field: "subDictionaryType", lookup: { string: 'string', number: 'number' }, + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Updated By", field: "updatedBy", editable: 'never', + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Last Updated Date", field: "updatedDate", editable: 'never', + cellStyle: cellStyle, + headerStyle: headerStyle + } + ], + dictElementColumns: [ + { + title: "Element Short Name", field: "shortName", editable: 'onAdd', + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Element Name", field: "name", + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Element Description", field: "description", + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Element Type", field: "type", + editComponent: props => ( + <div> + <SelectSubDictType value={ props.value } onChange={ props.onChange }/> + </div> + ), + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Sub-Dictionary", field: "subDictionary", + editComponent: props => ( + <div> + <SubDict value={ props.value } onChange={ props.onChange }/> + </div> + ), + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Updated By", field: "updatedBy", editable: 'never', + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Updated Date", field: "updatedDate", editable: 'never', + cellStyle: cellStyle, + headerStyle: headerStyle + } + ] + } + } + + componentDidMount() { + this.getDictionaries(); + } + + getDictionaries() { + TemplateMenuService.getDictionary().then(arrayOfdictionaries => { + this.setState({ dictionaries: arrayOfdictionaries, currentSelectedDictionary: null }) + // global variable setting used functional components in this file + dictList = arrayOfdictionaries; + }).catch(() => { + console.error('Failed to retrieve dictionaries'); + this.setState({ dictionaries: [], currentSelectedDictionary: null }) + }); + } + + getDictionaryElements(dictionaryName) { + TemplateMenuService.getDictionaryElements(dictionaryName).then(dictionaryElements => { + this.setState({ dictionaryElements: dictionaryElements.dictionaryElements }); + this.setState({ currentSelectDictionary: dictionaryName }); + }).catch(() => console.error('Failed to retrieve dictionary elements')) + } + + clickHandler(rowData) { + this.getDictionaries(); + } + + handleClose() { + this.setState({ show: false }); + this.props.history.push('/'); + } + + addReplaceDictionaryRequest(dictionaryEntry) { + TemplateMenuService.insDictionary(dictionaryEntry) + .then(resp => { + this.getDictionaries(); + }) + .catch(() => console.error('Failed to insert new dictionary elements')); + } + + updateDictionaryElementsRequest(dictElements) { + let reqData = { "name": this.state.currentSelectedDictionary, 'dictionaryElements': dictElements }; + TemplateMenuService.insDictionaryElements(reqData) + .then(resp => { + this.getDictionaryElements(this.state.currentSelectedDictionary) + }) + .catch(() => console.error('Failed to update dictionary elements')); + } + + deleteDictionaryRequest(dictionaryName) { + TemplateMenuService.deleteDictionary(dictionaryName) + .then(resp => { + this.getDictionaries(); + }) + .catch(() => console.error('Failed to delete dictionary')); + } + + deleteDictionaryElementRequest(dictionaryName, elemenetShortName) { + TemplateMenuService.deleteDictionaryElements({ 'name': dictionaryName, 'shortName': elemenetShortName }) + .then(resp => { + this.getDictionaryElements(dictionaryName); + }) + .catch(() => console.error('Failed to delete dictionary elements')); + } + + fileSelectedHandler = (event) => { + + if (event.target.files[0].type === 'text/csv' || event.target.files[0].type === 'application/vnd.ms-excel') { + if (event.target.files && event.target.files[0]) { + const reader = new FileReader(); + reader.onload = (e) => { + let errorMessages = this.importCsvData(reader.result); + if (errorMessages !== '') { + alert(errorMessages); + } + } + reader.readAsText(event.target.files[0]); + } + } else { + alert('Please upload .csv extention files only.'); + } + } + + importCsvData(rawCsvData) { + + const jsonKeyNames = ['shortName', 'name', 'description', 'type', 'subDictionary']; + const userHeaderNames = ['Element Short Name', 'Element Name', 'Element Description', 'Element Type', 'Sub-Dictionary']; + const validTypes = ['string', 'number', 'datetime', 'json', 'map']; + + let mandatory; + + if (subDictFlag) { + mandatory = [true, true, true, false, false]; + } else { + mandatory = [true, true, true, true, false]; + } + + let result = CsvToJson(rawCsvData, ',', '||||', userHeaderNames, jsonKeyNames, mandatory); + + let errorMessages = result.errorMessages; + let jsonObjArray = result.jsonObjArray; + + let validTypesErrorMesg = ''; + + for (let i = 0; i < validTypes.length; ++i) { + if (i === 0) { + validTypesErrorMesg = validTypes[i]; + } else { + validTypesErrorMesg += ',' + validTypes[i]; + } + } + + if (errorMessages !== '') { + return errorMessages; + } + + // Perform further checks on data that is now in JSON form + let subDictionaries = []; + + // NOTE: dictList is a global variable maintained faithfully + // by the getDictionaries() method outside this import + // functionality. + let item; + for (item in dictList) { + if (dictList[item].secondLevelDictionary === 1) { + subDictionaries.push(dictList[item].name); + } + } + ; + + // Check for valid Sub-Dictionary and Element Type values + subDictionaries = subDictionaries.toString(); + let row = 2; + let dictElem; + for (dictElem of jsonObjArray) { + let itemKey; + for (itemKey in dictElem) { + let value = dictElem[itemKey].trim(); + let keyIndex = jsonKeyNames.indexOf(itemKey); + if (itemKey === 'shortName' && /[^a-zA-Z0-9-_.]/.test(value)) { + errorMessages += '\n' + userHeaderNames[keyIndex] + + ' at row #' + row + + ' can only contain alphanumeric characters and periods, hyphens or underscores'; + } + if (itemKey === 'type' && validTypes.indexOf(value) < 0) { + errorMessages += '\nInvalid value of "' + value + '" for "' + userHeaderNames[keyIndex] + '" at row #' + row; + errorMessages += '\nValid types are: ' + validTypesErrorMesg; + } + if (value !== "" && itemKey === 'subDictionary' && subDictionaries.indexOf(value) < 0) { + errorMessages += '\nInvalid Sub-Dictionary value of "' + value + '" at row #' + row; + } + } + ++row; + } + if (errorMessages === '') { + // We made it through all the checks. Send it to back end + this.updateDictionaryElementsRequest(jsonObjArray); + } + + return errorMessages; + } + + addDictionaryRow(newData) { + let validData = true; + return new Promise((resolve, reject) => { + setTimeout(() => { + if (/[^a-zA-Z0-9-_.]/.test(newData.name)) { + validData = false; + alert('Please enter alphanumeric input. Only allowed special characters are:(period, hyphen, underscore)'); + reject(); + } + for (let i = 0; i < this.state.dictionaries.length; i++) { + if (this.state.dictionaries[i].name === newData.name) { + validData = false; + alert(newData.name + ' dictionary name already exists') + reject(); + } + } + if (validData) { + this.addReplaceDictionaryRequest(newData); + } + resolve(); + }, 1000); + }); + } + + + updateDictionaryRow(newData, oldData) { + let validData = true; + return new Promise((resolve, reject) => { + setTimeout(() => { + if (/[^a-zA-Z0-9-_.]/.test(newData.name)) { + validData = false; + alert('Please enter alphanumberic input. Only allowed special characters are:(period, hyphen, underscore)'); + reject(); + } + if (validData) { + this.addReplaceDictionaryRequest(newData); + } + resolve(); + }, 1000); + }); + } + + deleteDictionaryRow(oldData) { + return new Promise((resolve, reject) => { + setTimeout(() => { + this.deleteDictionaryRequest(oldData.name); + resolve(); + }, 1000); + }); + } + + addDictionaryElementRow(newData) { + return new Promise((resolve, reject) => { + setTimeout(() => { + let dictionaryElements = this.state.dictionaryElements; + let errorMessages = ''; + for (let i = 0; i < this.state.dictionaryElements.length; i++) { + if (this.state.dictionaryElements[i].shortName === newData.shortName) { + alert('Short Name "' + newData.shortName + '" already exists'); + reject(""); + } + } + // MaterialTable returns no property at all if the user has not touched a + // new column, so we want to add the property with an emptry string + // for several cases if that is the case to simplify other checks. + if (newData.description === undefined) { + newData.description = ""; + } + if (newData.subDictionary === undefined) { + newData.subDictionary = null; + } + if (newData.type === undefined) { + newData.type = ""; + } + if (!newData.shortName && /[^a-zA-Z0-9-_.]/.test(newData.shortName)) { + errorMessages += '\nShort Name is limited to alphanumeric characters and also period, hyphen, and underscore'; + } + if (!newData.shortName) { + errorMessages += '\nShort Name must be specified'; + } + if (!newData.name) { + errorMessages += '\nElement Name must be specified'; + } + if (!newData.type && !subDictFlag) { + errorMessages += '\nElement Type must be specified'; + } + if (errorMessages === '') { + dictionaryElements.push(newData); + this.updateDictionaryElementsRequest([newData]); + resolve(); + } else { + alert(errorMessages); + reject(""); + } + }, 1000); + }); + } + + updateDictionaryElementRow(newData, oldData) { + return new Promise((resolve, reject) => { + setTimeout(() => { + let dictionaryElements = this.state.dictionaryElements; + let validData = true; + if (!newData.type) { + validData = false; + alert('Element Type cannot be null'); + reject(); + } + if (validData) { + const index = dictionaryElements.indexOf(oldData); + dictionaryElements[index] = newData; + this.updateDictionaryElementsRequest([newData]); + } + resolve(); + }, 1000); + }); + } + + + deleteDictionaryElementRow(oldData) { + return new Promise((resolve) => { + setTimeout(() => { + this.deleteDictionaryElementRequest(this.state.currentSelectedDictionary, oldData.shortName); + resolve(); + }, 1000); + }); + } + + handleDictionaryRowClick(event, rowData) { + subDictFlag = rowData.secondLevelDictionary === 1 ? true : false; + this.setState({ + currentSelectedDictionary: rowData.name, + exportFilename: rowData.name + }) + this.getDictionaryElements(rowData.name); + } + + render() { + return ( + <ModalStyled size="xl" show={ this.state.show } onHide={ this.handleClose } backdrop="static" keyboard={ false }> + <Modal.Header closeButton> + <Modal.Title>Manage Dictionaries</Modal.Title> + </Modal.Header> + <Modal.Body> + { this.state.currentSelectedDictionary === null ? + <MaterialTable + title={ "Dictionary List" } + data={ this.state.dictionaries } + columns={ this.state.dictColumns } + icons={ this.state.tableIcons } + onRowClick={ this.handleDictionaryRowClick } + options={ { + headerStyle: rowHeaderStyle, + } } + editable={ !this.readOnly ? + { + onRowAdd: this.addDictionaryRow, + onRowUpdate: this.updateDictionaryRow, + onRowDelete: this.deleteDictionaryRow + } : undefined } + /> : null + } + { this.state.currentSelectedDictionary !== null ? + <MaterialTable + title={ 'Dictionary Elements List for ' + (subDictFlag ? 'Sub-Dictionary "' : '"') + this.state.currentSelectedDictionary + '"' } + data={ this.state.dictionaryElements } + columns={ this.state.dictElementColumns } + icons={ this.state.tableIcons } + options={ { + exportAllData: true, + exportButton: true, + exportFileName: this.state.exportFilename, + headerStyle: { backgroundColor: 'white', fontSize: '15pt', text: 'bold', border: '1px solid black' } + } } + components={ { + Toolbar: props => ( + <Row> + <Col sm="11"> + <MTableToolbarStyled { ...props } /> + </Col> + <ColPullLeftStyled sm="1"> + <Tooltip title="Import" placement="bottom"> + <IconButton aria-label="import" disabled={ this.readOnly } onClick={ () => this.fileUpload.click() }> + <VerticalAlignTopIcon/> + </IconButton> + </Tooltip> + <input type="file" ref={ (fileUpload) => { + this.fileUpload = fileUpload; + } } + style={ { visibility: 'hidden', width: '1px' } } onChange={ this.fileSelectedHandler }/> + </ColPullLeftStyled> + </Row> + ) + } } + editable={ !this.readOnly ? + { + onRowAdd: this.addDictionaryElementRow, + onRowUpdate: this.updateDictionaryElementRow, + onRowDelete: this.deleteDictionaryElementRow + } : undefined + } + /> : null + } + { this.state.currentSelectedDictionary !== null ? <button onClick={ this.clickHandler } style={ { marginTop: '25px' } }>Go Back to Dictionaries List</button> : "" } + </Modal.Body> + <Modal.Footer> + <Button variant="secondary" type="null" onClick={ this.handleClose }>Close</Button> + </Modal.Footer> + </ModalStyled> + ); + } } diff --git a/runtime/ui-react/src/components/dialogs/ManageDictionaries/ManageDictionaries.test.js b/runtime/ui-react/src/components/dialogs/ManageDictionaries/ManageDictionaries.test.js index a4c1335d8..2552d7a3d 100644 --- a/runtime/ui-react/src/components/dialogs/ManageDictionaries/ManageDictionaries.test.js +++ b/runtime/ui-react/src/components/dialogs/ManageDictionaries/ManageDictionaries.test.js @@ -28,435 +28,438 @@ import ManageDictionaries from './ManageDictionaries'; import TemplateMenuService from '../../../api/TemplateService' const TestDictionaryElements = { - name: "test", - secondLevelDictionary: 0, - subDictionaryType: "", - dictionaryElements: [ - { - shortName: "alertType", - name: "Alert Type", - description: "Type of Alert", - type: "string", - subDictionary: "", - createdDate: "2020-06-12T13:58:51.443931Z", - updatedDate: "2020-06-13T16:27:57.084870Z", - updatedBy: "admin", - createdBy: "admin" - } - ] + name: "test", + secondLevelDictionary: 0, + subDictionaryType: "", + dictionaryElements: [ + { + shortName: "alertType", + name: "Alert Type", + description: "Type of Alert", + type: "string", + subDictionary: "", + createdDate: "2020-06-12T13:58:51.443931Z", + updatedDate: "2020-06-13T16:27:57.084870Z", + updatedBy: "admin", + createdBy: "admin" + } + ] }; const TestDictionaries = -[ - { - name: "test", - secondLevelDictionary: 0, - subDictionaryType: "string", - dictionaryElements: [ TestDictionaryElements ], - createdDate: "2020-06-14T21:00:33.231166Z", - updatedDate: "2020-06-14T21:00:33.231166Z", - updatedBy: "admin", - createdBy: "admin" - }, - { - name: "testSub1", - secondLevelDictionary: 1, - subDictionaryType: "string", - dictionaryElements: [ - { - shortName: "subElem", - name: "Sub Element", - description: "Sub Element Description", - type: "string", - createdDate: "2020-06-14T21:04:44.402287Z", - updatedDate: "2020-06-14T21:04:44.402287Z", - updatedBy: "admin", - createdBy: "admin" - } - ], - createdDate: "2020-06-14T21:01:16.390250Z", - updatedDate: "2020-06-14T21:01:16.390250Z", - updatedBy: "admin", - createdBy: "admin" - } -]; + [ + { + name: "test", + secondLevelDictionary: 0, + subDictionaryType: "string", + dictionaryElements: [TestDictionaryElements], + createdDate: "2020-06-14T21:00:33.231166Z", + updatedDate: "2020-06-14T21:00:33.231166Z", + updatedBy: "admin", + createdBy: "admin" + }, + { + name: "testSub1", + secondLevelDictionary: 1, + subDictionaryType: "string", + dictionaryElements: [ + { + shortName: "subElem", + name: "Sub Element", + description: "Sub Element Description", + type: "string", + createdDate: "2020-06-14T21:04:44.402287Z", + updatedDate: "2020-06-14T21:04:44.402287Z", + updatedBy: "admin", + createdBy: "admin" + } + ], + createdDate: "2020-06-14T21:01:16.390250Z", + updatedDate: "2020-06-14T21:01:16.390250Z", + updatedBy: "admin", + createdBy: "admin" + } + ]; const historyMock = { push: jest.fn() }; let errorMessage = ''; -window.alert = jest.fn().mockImplementation((mesg) => { errorMessage = mesg ; return }); +window.alert = jest.fn().mockImplementation((mesg) => { + errorMessage = mesg; + return +}); TemplateMenuService.getDictionary = jest.fn().mockImplementation(() => { - return Promise.resolve(TestDictionaries); + return Promise.resolve(TestDictionaries); }); TemplateMenuService.insDictionary = jest.fn().mockImplementation(() => { - return Promise.resolve({ ok: true, status: 200 }); + return Promise.resolve({ ok: true, status: 200 }); }); TemplateMenuService.deleteDictionary = jest.fn().mockImplementation(() => { - return Promise.resolve("200"); + return Promise.resolve("200"); }); TemplateMenuService.getDictionaryElements = jest.fn().mockImplementation(() => { - return Promise.resolve(TestDictionaryElements); + return Promise.resolve(TestDictionaryElements); }); TemplateMenuService.deleteDictionaryElements = jest.fn().mockImplementation(() => { - return Promise.resolve("200"); + return Promise.resolve("200"); }); TemplateMenuService.insDictionaryElements = jest.fn().mockImplementation(() => { - return Promise.resolve("200"); + return Promise.resolve("200"); }); describe('Verify ManageDictionaries', () => { - beforeEach(() => { - fetch.resetMocks(); - }); + beforeEach(() => { + fetch.resetMocks(); + }); + + it('Test API Successful', () => { + fetch.mockImplementationOnce(() => { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + return Promise.resolve({ + "name": "vtest", + "secondLevelDictionary": 1, + "subDictionaryType": "string", + "updatedBy": "test", + "updatedDate": "05-07-2019 19:09:42" + }); + } + }); + }); + const component = shallow(<ManageDictionaries/>); + expect(component).toMatchSnapshot(); + }); + + it('Test API Exception', () => { + fetch.mockImplementationOnce(() => { + return Promise.resolve({ + ok: false, + status: 500, + json: () => { + return Promise.resolve({ + "name": "vtest", + "secondLevelDictionary": 1, + "subDictionaryType": "string", + "updatedBy": "test", + "updatedDate": "05-07-2019 19:09:42" + }); + } + }); + }); + const component = shallow(<ManageDictionaries/>); + }); + + it('Test Table icons', () => { + + const component = mount(<ManageDictionaries/>); + expect(component.find('[className="MuiSelect-icon MuiTablePagination-selectIcon"]')).toBeTruthy(); + }); + + test('Test add/replace and delete dictionary requests', async () => { + + const component = shallow(<ManageDictionaries history={ historyMock }/>) + const instance = component.instance(); + + const flushPromises = () => new Promise(setImmediate); + + instance.addReplaceDictionaryRequest({ name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string" }); + instance.deleteDictionaryRequest("test"); + + await flushPromises(); + + expect(component.state('currentSelectedDictionary')).toEqual(null); + expect(component.state('dictionaries')).toEqual(TestDictionaries); + }); - it('Test API Successful', () => { - fetch.mockImplementationOnce(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => { - return Promise.resolve({ - "name": "vtest", - "secondLevelDictionary": 1, - "subDictionaryType": "string", - "updatedBy": "test", - "updatedDate": "05-07-2019 19:09:42" - }); - } - }); - }); - const component = shallow(<ManageDictionaries />); - expect(component).toMatchSnapshot(); - }); + test('Test update dictionary row', async () => { - it('Test API Exception', () => { - fetch.mockImplementationOnce(() => { - return Promise.resolve({ - ok: false, - status: 500, - json: () => { - return Promise.resolve({ - "name": "vtest", - "secondLevelDictionary": 1, - "subDictionaryType": "string", - "updatedBy": "test", - "updatedDate": "05-07-2019 19:09:42" - }); - } - }); - }); - const component = shallow(<ManageDictionaries />); - }); + const component = shallow(<ManageDictionaries history={ historyMock }/>) + const instance = component.instance(); + const rowData = { name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string" }; - it('Test Table icons', () => { + await expect(instance.updateDictionaryRow(rowData, rowData)).resolves.toEqual(undefined); - const component = mount(<ManageDictionaries />); - expect(component.find('[className="MuiSelect-icon MuiTablePagination-selectIcon"]')).toBeTruthy(); - }); + }, 2000); - test('Test add/replace and delete dictionary requests', async () => { + test('Test add dictionary row', async () => { - const component = shallow(<ManageDictionaries history={historyMock}/>) - const instance = component.instance(); + const addReplaceRequest = jest.spyOn(ManageDictionaries.prototype, 'addReplaceDictionaryRequest'); + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); + const rowData = { name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string" }; - const flushPromises = () => new Promise(setImmediate); + await instance.addDictionaryRow(rowData); + expect(addReplaceRequest).toHaveBeenCalledWith(rowData); - instance.addReplaceDictionaryRequest({name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string"}); - instance.deleteDictionaryRequest("test"); + }, 2000); - await flushPromises(); + test('Test add dictionary row with errors name already exists', async () => { - expect(component.state('currentSelectedDictionary')).toEqual(null); - expect(component.state('dictionaries')).toEqual(TestDictionaries); - }); + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); + let rowData = { name: "test", secondLevelDictionary: 0, subDictionaryType: "" }; - test('Test update dictionary row', async () => { + await expect(instance.addDictionaryRow(rowData)).rejects.toEqual(undefined); - const component = shallow(<ManageDictionaries history={historyMock}/>) - const instance = component.instance(); - const rowData = { name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string" }; + }, 2000); - await expect(instance.updateDictionaryRow(rowData, rowData)).resolves.toEqual(undefined); + test('Test add dictionary row with errors illegal chars in name', async () => { - }, 2000); + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); + let rowData = { name: "test@@", secondLevelDictionary: 0, subDictionaryType: "" }; - test('Test add dictionary row', async () => { + await expect(instance.addDictionaryRow(rowData)).rejects.toEqual(undefined); - const addReplaceRequest = jest.spyOn(ManageDictionaries.prototype,'addReplaceDictionaryRequest'); - const component = shallow(<ManageDictionaries />) - const instance = component.instance(); - const rowData = { name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string" }; + }, 2000); - await instance.addDictionaryRow(rowData); - expect(addReplaceRequest).toHaveBeenCalledWith(rowData); + test('Test update dictionary row with errors illegal chars in name', async () => { - }, 2000); + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); + let rowData = { name: "test@@", secondLevelDictionary: 0, subDictionaryType: "" }; - test('Test add dictionary row with errors name already exists', async () => { + await expect(instance.updateDictionaryRow(rowData)).rejects.toEqual(undefined); + }); - const component = shallow(<ManageDictionaries />) - const instance = component.instance(); - let rowData = { name: "test", secondLevelDictionary: 0, subDictionaryType: "" }; - await expect(instance.addDictionaryRow(rowData)).rejects.toEqual(undefined); + test('Test add dictionary row with errors (illegal chars)', async () => { - }, 2000); + const addReplaceRequest = jest.spyOn(ManageDictionaries.prototype, 'addReplaceDictionaryRequest'); + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); + let rowData = { name: "test@@", secondLevelDictionary: 0, subDictionaryType: "" }; - test('Test add dictionary row with errors illegal chars in name', async () => { + await expect(instance.addDictionaryRow(rowData)).rejects.toEqual(undefined); - const component = shallow(<ManageDictionaries />) - const instance = component.instance(); - let rowData = { name: "test@@", secondLevelDictionary: 0, subDictionaryType: "" }; + }, 2000); - await expect(instance.addDictionaryRow(rowData)).rejects.toEqual(undefined); - }, 2000); + test('Test delete dictionary row', async () => { - test('Test update dictionary row with errors illegal chars in name', async () => { + const deleteRequest = jest.spyOn(ManageDictionaries.prototype, 'deleteDictionaryRequest'); + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); + const rowData = { name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string" }; - const component = shallow(<ManageDictionaries />) - const instance = component.instance(); - let rowData = { name: "test@@", secondLevelDictionary: 0, subDictionaryType: "" }; + await instance.deleteDictionaryRow(rowData); + expect(deleteRequest).toHaveBeenCalledWith("newdict"); - await expect(instance.updateDictionaryRow(rowData)).rejects.toEqual(undefined); - }); + }, 2000); + test('Test handle select dictionary row click', async () => { - test('Test add dictionary row with errors (illegal chars)', async () => { + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); + const rowData = { name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string" }; - const addReplaceRequest = jest.spyOn(ManageDictionaries.prototype,'addReplaceDictionaryRequest'); - const component = shallow(<ManageDictionaries />) - const instance = component.instance(); - let rowData = { name: "test@@", secondLevelDictionary: 0, subDictionaryType: "" }; + instance.handleDictionaryRowClick("event", rowData); + expect(component.state('currentSelectedDictionary')).toEqual("newdict"); + }, 2000); - await expect(instance.addDictionaryRow(rowData)).rejects.toEqual(undefined); + test('Test dictionary element row add, update, delete', async () => { - }, 2000); + const rowData = { + createdBy: "admin", + createdDate: "2020-06-15T13:59:20.467381Z", + description: "Description", + name: "Some Elem", + shortName: "someElem", + type: "string", + updatedBy: "admin", + updatedDate: "2020-06-15T13:59:20.467381Z" + }; + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); - test('Test delete dictionary row', async () => { + const badRowData = { + description: "Description", + name: "Some Elem", + shortName: "someElem", + type: "string" + }; - const deleteRequest = jest.spyOn(ManageDictionaries.prototype,'deleteDictionaryRequest'); - const component = shallow(<ManageDictionaries />) - const instance = component.instance(); - const rowData = { name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string" }; + await instance.clickHandler(); + await instance.getDictionaryElements("test"); - await instance.deleteDictionaryRow(rowData); - expect(deleteRequest).toHaveBeenCalledWith("newdict"); + await expect(instance.addDictionaryElementRow(rowData)).resolves.toEqual(undefined); + await expect(instance.updateDictionaryElementRow(rowData, rowData)).resolves.toEqual(undefined); + await expect(instance.deleteDictionaryElementRow(rowData)).resolves.toEqual(undefined); + }); - }, 2000); + test('Test dictionary element row add with errors', async () => { - test('Test handle select dictionary row click', async () => { + const badRowData = { + description: "", + name: "", + shortName: "some#Elem", + type: "" + }; - const component = shallow(<ManageDictionaries />) - const instance = component.instance(); - const rowData = { name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string" }; + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); - instance.handleDictionaryRowClick("event", rowData); - expect(component.state('currentSelectedDictionary')).toEqual("newdict"); - }, 2000); + await expect(instance.addDictionaryElementRow(badRowData)).rejects.toEqual(""); + }); - test('Test dictionary element row add, update, delete', async () => { + test('Test dictionary element update with error illegal name', async () => { - const rowData = { - createdBy: "admin", - createdDate: "2020-06-15T13:59:20.467381Z", - description: "Description", - name: "Some Elem", - shortName: "someElem", - type: "string", - updatedBy: "admin", - updatedDate: "2020-06-15T13:59:20.467381Z" - }; + const badRowData = { + description: "", + name: "test@@", + shortName: "some#Elem", + type: "" + }; - const component = shallow(<ManageDictionaries/>) - const instance = component.instance(); + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); - const badRowData = { - description: "Description", - name: "Some Elem", - shortName: "someElem", - type: "string" - }; + await expect(instance.updateDictionaryElementRow(badRowData)).rejects.toEqual(undefined); + }); - await instance.clickHandler(); - await instance.getDictionaryElements("test"); + test('Test dictionary element addition with duplicate name error', async () => { - await expect(instance.addDictionaryElementRow(rowData)).resolves.toEqual(undefined); - await expect(instance.updateDictionaryElementRow(rowData, rowData)).resolves.toEqual(undefined); - await expect(instance.deleteDictionaryElementRow(rowData)).resolves.toEqual(undefined); - }); + const badRowData = { + description: "description", + name: "Alert Type", + shortName: "alertType", + type: "string" + }; - test('Test dictionary element row add with errors', async () => { + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); - const badRowData = { - description: "", - name: "", - shortName: "some#Elem", - type: "" - }; + component.setState({ currentSelectedDictionary: 'test' }); - const component = shallow(<ManageDictionaries/>) - const instance = component.instance(); + await instance.getDictionaryElements(); + await expect(instance.addDictionaryElementRow(badRowData)).rejects.toEqual(""); + }); - await expect(instance.addDictionaryElementRow(badRowData)).rejects.toEqual(""); - }); + test('Test dictionary element addition with empty name error', async () => { - test('Test dictionary element update with error illegal name', async () => { + const badRowData = { + description: "description", + name: "Alert Type", + shortName: "", + type: "string" + }; - const badRowData = { - description: "", - name: "test@@", - shortName: "some#Elem", - type: "" - }; + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); - const component = shallow(<ManageDictionaries/>) - const instance = component.instance(); + component.setState({ currentSelectedDictionary: 'test' }); - await expect(instance.updateDictionaryElementRow(badRowData)).rejects.toEqual(undefined); - }); + await instance.getDictionaryElements(); + await expect(instance.addDictionaryElementRow(badRowData)).rejects.toEqual(""); + }); - test('Test dictionary element addition with duplicate name error', async () => { - const badRowData = { - description: "description", - name: "Alert Type", - shortName: "alertType", - type: "string" - }; + it('Test Import CSV Sunny Day', async () => { - const component = shallow(<ManageDictionaries/>) - const instance = component.instance(); + TemplateMenuService.insDictionaryElements = jest.fn().mockImplementation(() => { + return Promise.resolve({ ok: true, status: 200 }); + }); - component.setState({ currentSelectedDictionary: 'test' }); + let rawCsvData = '"Element Short Name","Element Name","Element Description","Element Type","Sub-Dictionary"\n'; + rawCsvData += '"alertType","Alert Type","Alert Type Description","string","","admin","2020-06-11T13:56:14.927437Z"'; - await instance.getDictionaryElements(); - await expect(instance.addDictionaryElementRow(badRowData)).rejects.toEqual(""); - }); + let expectedResult = [ + { + description: "Alert Type Description", + name: "Alert Type", + shortName: "alertType", + subDictionary: "", + type: "string" + } + ]; + + const updateDictionaryElementsRequest = jest.spyOn(ManageDictionaries.prototype, 'updateDictionaryElementsRequest'); + + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); + + await expect(instance.importCsvData(rawCsvData)).toEqual(''); + expect(updateDictionaryElementsRequest).toHaveBeenCalledWith(expectedResult); + }); + + it('Test Import CSV Mandatory Field Check Errors', () => { + + let rawCsvData = '"Element Short Name","Element Name","Element Description","Element Type","Sub-Dictionary"\n'; + rawCsvData += '"","","","","","",""'; - test('Test dictionary element addition with empty name error', async () => { + // The empty values for all the fields in row 1 of the rawCsvData will trigger a bunch of errors. + // Getting Enzyme to properly match them with embedded newlines turned out to be impossible + // and maybe not desirable anyway; so our test for "success" here is simply that the + // routine returns a non-empty error string. - const badRowData = { - description: "description", - name: "Alert Type", - shortName: "", - type: "string" - }; - - const component = shallow(<ManageDictionaries/>) - const instance = component.instance(); - - component.setState({ currentSelectedDictionary: 'test' }); - - await instance.getDictionaryElements(); - await expect(instance.addDictionaryElementRow(badRowData)).rejects.toEqual(""); - }); - - - it('Test Import CSV Sunny Day', async () => { - - TemplateMenuService.insDictionaryElements = jest.fn().mockImplementation(() => { - return Promise.resolve({ ok: true, status: 200 }); - }); - - let rawCsvData = '"Element Short Name","Element Name","Element Description","Element Type","Sub-Dictionary"\n'; - rawCsvData += '"alertType","Alert Type","Alert Type Description","string","","admin","2020-06-11T13:56:14.927437Z"'; - - let expectedResult = [ - { - description: "Alert Type Description", - name: "Alert Type", - shortName: "alertType", - subDictionary: "", - type: "string" - } - ]; - - const updateDictionaryElementsRequest = jest.spyOn(ManageDictionaries.prototype,'updateDictionaryElementsRequest'); - - const component = shallow(<ManageDictionaries />) - const instance = component.instance(); - - await expect(instance.importCsvData(rawCsvData)).toEqual(''); - expect(updateDictionaryElementsRequest).toHaveBeenCalledWith(expectedResult); - }); - - it('Test Import CSV Mandatory Field Check Errors', () => { - - let rawCsvData = '"Element Short Name","Element Name","Element Description","Element Type","Sub-Dictionary"\n'; - rawCsvData += '"","","","","","",""'; - - // The empty values for all the fields in row 1 of the rawCsvData will trigger a bunch of errors. - // Getting Enzyme to properly match them with embedded newlines turned out to be impossible - // and maybe not desirable anyway; so our test for "success" here is simply that the - // routine returns a non-empty error string. - - const component = shallow(<ManageDictionaries />) - const instance = component.instance(); - expect(instance.importCsvData(rawCsvData)).not.toEqual(''); - }); - - it('Test Import CSV Errors in Row Data', async () => { - - TemplateMenuService.insDictionaryElements = jest.fn().mockImplementation(() => { - return Promise.resolve({ ok: true, status: 200 }); - }); - - let rawCsvData = '"Element Short Name","Element Name","Element Description","Element Type","Sub-Dictionary"\n'; - rawCsvData += '"alert@Type","Alert Type","Alert Type Description","strin","subby","admin","2020-06-11T13:56:14.927437Z"'; - - let expectedResult = [ - { - description: "Alert Type Description", - name: "Alert Type", - shortName: "alertType", - subDictionary: "", - type: "string" - } - ]; - - const updateDictionaryElementsRequest = jest.spyOn(ManageDictionaries.prototype,'updateDictionaryElementsRequest'); - - const component = shallow(<ManageDictionaries />) - const instance = component.instance(); - - await expect(instance.importCsvData(rawCsvData)).not.toEqual(''); - }); - - - it('Test handleClose', () => { - fetch.mockImplementationOnce(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => { - return Promise.resolve({ - "name": "vtest", - "secondLevelDictionary": 1, - "subDictionaryType": "string", - "updatedBy": "test", - "updatedDate": "05-07-2019 19:09:42" - }); - } - }); - }); - const handleClose = jest.spyOn(ManageDictionaries.prototype,'handleClose'); - const component = shallow(<ManageDictionaries history={historyMock} />) - component.find('[variant="secondary"]').prop('onClick')(); - expect(handleClose).toHaveBeenCalledTimes(1); - expect(component.state('show')).toEqual(false); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); - handleClose.mockClear(); - }); + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); + expect(instance.importCsvData(rawCsvData)).not.toEqual(''); + }); + + it('Test Import CSV Errors in Row Data', async () => { + + TemplateMenuService.insDictionaryElements = jest.fn().mockImplementation(() => { + return Promise.resolve({ ok: true, status: 200 }); + }); + + let rawCsvData = '"Element Short Name","Element Name","Element Description","Element Type","Sub-Dictionary"\n'; + rawCsvData += '"alert@Type","Alert Type","Alert Type Description","strin","subby","admin","2020-06-11T13:56:14.927437Z"'; + + let expectedResult = [ + { + description: "Alert Type Description", + name: "Alert Type", + shortName: "alertType", + subDictionary: "", + type: "string" + } + ]; + + const updateDictionaryElementsRequest = jest.spyOn(ManageDictionaries.prototype, 'updateDictionaryElementsRequest'); + + const component = shallow(<ManageDictionaries/>) + const instance = component.instance(); + + await expect(instance.importCsvData(rawCsvData)).not.toEqual(''); + }); + + + it('Test handleClose', () => { + fetch.mockImplementationOnce(() => { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + return Promise.resolve({ + "name": "vtest", + "secondLevelDictionary": 1, + "subDictionaryType": "string", + "updatedBy": "test", + "updatedDate": "05-07-2019 19:09:42" + }); + } + }); + }); + const handleClose = jest.spyOn(ManageDictionaries.prototype, 'handleClose'); + const component = shallow(<ManageDictionaries history={ historyMock }/>) + component.find('[variant="secondary"]').prop('onClick')(); + expect(handleClose).toHaveBeenCalledTimes(1); + expect(component.state('show')).toEqual(false); + expect(historyMock.push.mock.calls[0]).toEqual(['/']); + handleClose.mockClear(); + }); }); diff --git a/runtime/ui-react/src/components/dialogs/PerformActions.js b/runtime/ui-react/src/components/dialogs/PerformActions.js index f6001e21f..ba7c99d7f 100644 --- a/runtime/ui-react/src/components/dialogs/PerformActions.js +++ b/runtime/ui-react/src/components/dialogs/PerformActions.js @@ -25,71 +25,71 @@ import LoopActionService from '../../api/LoopActionService'; export default class PerformActions extends React.Component { - state = { - loopName: this.props.loopCache.getLoopName(), - loopAction: this.props.loopAction - }; + state = { + loopName: this.props.loopCache.getLoopName(), + loopAction: this.props.loopAction + }; - constructor(props, context) { - super(props, context); - this.refreshStatus = this.refreshStatus.bind(this); - } + constructor(props, context) { + super(props, context); + this.refreshStatus = this.refreshStatus.bind(this); + } - componentWillReceiveProps(newProps) { - this.setState({ - loopName: newProps.loopCache.getLoopName(), - loopAction: newProps.loopAction - }); - } + componentWillReceiveProps(newProps) { + this.setState({ + loopName: newProps.loopCache.getLoopName(), + loopAction: newProps.loopAction + }); + } - componentDidMount() { - const action = this.state.loopAction; - const loopName = this.state.loopName; + componentDidMount() { + const action = this.state.loopAction; + const loopName = this.state.loopName; - if (action === 'delete') { - if (window.confirm('You are about to remove Control Loop Model "' + loopName + - '". Select OK to continue with deletion or Cancel to keep the model.') === false) { - return; - } - } + if (action === 'delete') { + if (window.confirm('You are about to remove Control Loop Model "' + loopName + + '". Select OK to continue with deletion or Cancel to keep the model.') === false) { + return; + } + } - this.props.setBusyLoading(); // Alert top level to start block user clicks + this.props.setBusyLoading(); // Alert top level to start block user clicks - LoopActionService.performAction(loopName, action) - .then(pars => { - this.props.showSucAlert("Action " + action + " successfully performed"); - if (action === 'delete') { - this.props.updateLoopFunction(null); - this.props.history.push('/'); - } else { - // refresh status and update loop logs - this.refreshStatus(loopName); - } - }) - .catch(error => { - this.props.showFailAlert("Action " + action + " failed"); - // refresh status and update loop logs - this.refreshStatus(loopName); - }) - .finally(() => this.props.clearBusyLoading()); - } + LoopActionService.performAction(loopName, action) + .then(pars => { + this.props.showSucAlert("Action " + action + " successfully performed"); + if (action === 'delete') { + this.props.updateLoopFunction(null); + this.props.history.push('/'); + } else { + // refresh status and update loop logs + this.refreshStatus(loopName); + } + }) + .catch(error => { + this.props.showFailAlert("Action " + action + " failed"); + // refresh status and update loop logs + this.refreshStatus(loopName); + }) + .finally(() => this.props.clearBusyLoading()); + } - refreshStatus(loopName) { + refreshStatus(loopName) { - this.props.setBusyLoading(); + this.props.setBusyLoading(); - LoopActionService.refreshStatus(loopName) - .then(data => { - this.props.updateLoopFunction(data); - this.props.history.push('/'); - }) - .catch(error => { - this.props.history.push('/'); - }) - .finally(() => this.props.clearBusyLoading()); - } + LoopActionService.refreshStatus(loopName) + .then(data => { + this.props.updateLoopFunction(data); + this.props.history.push('/'); + }) + .catch(error => { + this.props.history.push('/'); + }) + .finally(() => this.props.clearBusyLoading()); + } - render() { - return null; - } + render() { + return null; + } } diff --git a/runtime/ui-react/src/components/dialogs/PerformActions.test.js b/runtime/ui-react/src/components/dialogs/PerformActions.test.js index c91c2f675..74c914584 100644 --- a/runtime/ui-react/src/components/dialogs/PerformActions.test.js +++ b/runtime/ui-react/src/components/dialogs/PerformActions.test.js @@ -28,63 +28,68 @@ import LoopActionService from '../../api/LoopActionService'; describe('Verify PerformActions', () => { - const loopCache = new LoopCache({ - "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca" - }); + const loopCache = new LoopCache({ + "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca" + }); - it('Test the render method action failed', async () => { - const flushPromises = () => new Promise(setImmediate); - const historyMock = { push: jest.fn() }; - const updateLoopFunction = jest.fn(); - const showSucAlert = jest.fn(); - const showFailAlert = jest.fn(); - const setBusyLoading = jest.fn(); - const clearBusyLoading = jest.fn(); - - LoopActionService.refreshStatus = jest.fn().mockImplementation(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => {} - }); - }); - const component = shallow(<PerformActions loopCache={loopCache} - loopAction="submit" history={historyMock} updateLoopFunction={updateLoopFunction} showSucAlert={showSucAlert} showFailAlert={showFailAlert} setBusyLoading={setBusyLoading} clearBusyLoading={clearBusyLoading}/>) - await flushPromises(); - component.update(); + it('Test the render method action failed', async () => { + const flushPromises = () => new Promise(setImmediate); + const historyMock = { push: jest.fn() }; + const updateLoopFunction = jest.fn(); + const showSucAlert = jest.fn(); + const showFailAlert = jest.fn(); + const setBusyLoading = jest.fn(); + const clearBusyLoading = jest.fn(); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); - }); + LoopActionService.refreshStatus = jest.fn().mockImplementation(() => { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + } + }); + }); + const component = shallow(<PerformActions loopCache={ loopCache } + loopAction="submit" history={ historyMock } updateLoopFunction={ updateLoopFunction } showSucAlert={ showSucAlert } showFailAlert={ showFailAlert } + setBusyLoading={ setBusyLoading } clearBusyLoading={ clearBusyLoading }/>) + await flushPromises(); + component.update(); - it('Test the render method action successful', async () => { - const flushPromises = () => new Promise(setImmediate); - const historyMock = { push: jest.fn() }; - const updateLoopFunction = jest.fn(); - const showSucAlert = jest.fn(); - const showFailAlert = jest.fn(); - const setBusyLoading = jest.fn(); - const clearBusyLoading = jest.fn(); + expect(historyMock.push.mock.calls[0]).toEqual(['/']); + }); - LoopActionService.performAction = jest.fn().mockImplementation(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => {} - }); - }); - LoopActionService.refreshStatus = jest.fn().mockImplementation(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => {} - }); - }); - const component = shallow(<PerformActions loopCache={loopCache} - loopAction="submit" history={historyMock} updateLoopFunction={updateLoopFunction} showSucAlert={showSucAlert} showFailAlert={showFailAlert} setBusyLoading={setBusyLoading} clearBusyLoading={clearBusyLoading}/>) - await flushPromises(); - component.update(); + it('Test the render method action successful', async () => { + const flushPromises = () => new Promise(setImmediate); + const historyMock = { push: jest.fn() }; + const updateLoopFunction = jest.fn(); + const showSucAlert = jest.fn(); + const showFailAlert = jest.fn(); + const setBusyLoading = jest.fn(); + const clearBusyLoading = jest.fn(); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); - }); + LoopActionService.performAction = jest.fn().mockImplementation(() => { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + } + }); + }); + LoopActionService.refreshStatus = jest.fn().mockImplementation(() => { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + } + }); + }); + const component = shallow(<PerformActions loopCache={ loopCache } + loopAction="submit" history={ historyMock } updateLoopFunction={ updateLoopFunction } showSucAlert={ showSucAlert } showFailAlert={ showFailAlert } + setBusyLoading={ setBusyLoading } clearBusyLoading={ clearBusyLoading }/>) + await flushPromises(); + component.update(); + + expect(historyMock.push.mock.calls[0]).toEqual(['/']); + }); }); diff --git a/runtime/ui-react/src/components/dialogs/Policy/PoliciesTreeViewer.js b/runtime/ui-react/src/components/dialogs/Policy/PoliciesTreeViewer.js index 9c2f102b4..5bca4e6e1 100644 --- a/runtime/ui-react/src/components/dialogs/Policy/PoliciesTreeViewer.js +++ b/runtime/ui-react/src/components/dialogs/Policy/PoliciesTreeViewer.js @@ -31,79 +31,79 @@ import DescriptionIcon from '@material-ui/icons/Description'; export default class PoliciesTreeViewer extends React.Component { - separator = "."; + separator = "."; - nodesList = new Map(); + nodesList = new Map(); - constructor(props, context) { - super(props, context); - this.createPoliciesTree = this.createPoliciesTree.bind(this); - this.handleTreeItemClick = this.handleTreeItemClick.bind(this); - this.buildNameWithParent = this.buildNameWithParent.bind(this); + constructor(props, context) { + super(props, context); + this.createPoliciesTree = this.createPoliciesTree.bind(this); + this.handleTreeItemClick = this.handleTreeItemClick.bind(this); + this.buildNameWithParent = this.buildNameWithParent.bind(this); - } + } - state = { - policiesTreeData: this.createPoliciesTree(this.props.policiesData), - } + state = { + policiesTreeData: this.createPoliciesTree(this.props.policiesData), + } - componentDidUpdate(prevProps) { - if (prevProps.policiesData !== this.props.policiesData) { - this.setState({policiesTreeData: this.createPoliciesTree(this.props.policiesData)}) - } + componentDidUpdate(prevProps) { + if (prevProps.policiesData !== this.props.policiesData) { + this.setState({ policiesTreeData: this.createPoliciesTree(this.props.policiesData) }) } + } - createPoliciesTree(policiesArray) { - // put my policies array in a Json - let nodeId = 1; - let root = {id:nodeId, policyCount:0, name:"ROOT", children:[], parent: undefined}; - this.nodesList.set(nodeId++, root); - - policiesArray.forEach(policy => { - let currentTreeNode = root; - policy[this.props.valueForTreeCreation].split(this.separator).forEach((policyNamePart, index, policyNamePartsArray) => { - let node = currentTreeNode["children"].find(element => element.name === policyNamePart); - if (typeof(node) === "undefined") { - node = {id:nodeId, policyCount:0, children:[], name:policyNamePart, parent:currentTreeNode}; - this.nodesList.set(nodeId++, node); - currentTreeNode["children"].push(node); - } - if ((index+1) === policyNamePartsArray.length) { - ++currentTreeNode["policyCount"]; - } - currentTreeNode = node; - }) - }) - return root; - } + createPoliciesTree(policiesArray) { + // put my policies array in a Json + let nodeId = 1; + let root = { id: nodeId, policyCount: 0, name: "ROOT", children: [], parent: undefined }; + this.nodesList.set(nodeId++, root); - buildNameWithParent(node) { - let nameToBuild = node.name; - if (node.parent !== undefined) { - nameToBuild = this.buildNameWithParent(node.parent) + this.separator + node.name; + policiesArray.forEach(policy => { + let currentTreeNode = root; + policy[this.props.valueForTreeCreation].split(this.separator).forEach((policyNamePart, index, policyNamePartsArray) => { + let node = currentTreeNode["children"].find(element => element.name === policyNamePart); + if (typeof (node) === "undefined") { + node = { id: nodeId, policyCount: 0, children: [], name: policyNamePart, parent: currentTreeNode }; + this.nodesList.set(nodeId++, node); + currentTreeNode["children"].push(node); } - return nameToBuild; - } + if ((index + 1) === policyNamePartsArray.length) { + ++currentTreeNode["policyCount"]; + } + currentTreeNode = node; + }) + }) + return root; + } - handleTreeItemClick(event, value) { - let fullName = this.buildNameWithParent(this.nodesList.get(value[0])).substring(5); - this.props.policiesFilterFunction(fullName); + buildNameWithParent(node) { + let nameToBuild = node.name; + if (node.parent !== undefined) { + nameToBuild = this.buildNameWithParent(node.parent) + this.separator + node.name; } + return nameToBuild; + } - renderTreeItems(nodes) { - return (<TreeItem key={nodes.id} nodeId={nodes.id} label={nodes.name + "("+ nodes.policyCount + ")"} onNodeSelect={this.handleTreeItemClick}> - { - Array.isArray(nodes.children) ? nodes.children.map((node) => this.renderTreeItems(node)) : null - } - </TreeItem>); - }; + handleTreeItemClick(event, value) { + let fullName = this.buildNameWithParent(this.nodesList.get(value[0])).substring(5); + this.props.policiesFilterFunction(fullName); + } - render() { - return ( - <TreeView defaultExpanded={['root']} defaultCollapseIcon={<FolderOpenIcon />} - defaultExpandIcon={<FolderIcon />} defaultEndIcon={<DescriptionIcon />} onNodeSelect={this.handleTreeItemClick} multiSelect> - {this.renderTreeItems(this.state.policiesTreeData)} - </TreeView> - ); - } -}
\ No newline at end of file + renderTreeItems(nodes) { + return (<TreeItem key={ nodes.id } nodeId={ nodes.id } label={ nodes.name + "(" + nodes.policyCount + ")" } onNodeSelect={ this.handleTreeItemClick }> + { + Array.isArray(nodes.children) ? nodes.children.map((node) => this.renderTreeItems(node)) : null + } + </TreeItem>); + }; + + render() { + return ( + <TreeView defaultExpanded={ ['root'] } defaultCollapseIcon={ <FolderOpenIcon/> } + defaultExpandIcon={ <FolderIcon/> } defaultEndIcon={ <DescriptionIcon/> } onNodeSelect={ this.handleTreeItemClick } multiSelect> + { this.renderTreeItems(this.state.policiesTreeData) } + </TreeView> + ); + } +} diff --git a/runtime/ui-react/src/components/dialogs/Policy/PolicyEditor.test.js b/runtime/ui-react/src/components/dialogs/Policy/PolicyEditor.test.js index 0b734430a..111f2c6bf 100644 --- a/runtime/ui-react/src/components/dialogs/Policy/PolicyEditor.test.js +++ b/runtime/ui-react/src/components/dialogs/Policy/PolicyEditor.test.js @@ -26,46 +26,47 @@ import { shallow, mount } from 'enzyme'; import PolicyToscaService from '../../../api/PolicyToscaService'; describe('Verify PolicyEditor', () => { - const fs = require('fs'); + const fs = require('fs'); - let toscaJson = fs.readFileSync('src/components/dialogs/Policy/toscaData.test.json', {encoding:'utf8', flag:'r'}) + let toscaJson = fs.readFileSync('src/components/dialogs/Policy/toscaData.test.json', { encoding: 'utf8', flag: 'r' }) - const policyProperties = { - "tca.policy": { - "domain": "measurementsForVfScaling", - "metricsPerEventName": [ - { - "policyScope": "DCAE", - "thresholds": [ - { - "version": "1.0.2", - "severity": "MAJOR", - "thresholdValue": 200, - "closedLoopEventStatus": "ONSET", - "closedLoopControlName": "LOOP_test", - "direction": "LESS_OR_EQUAL", - "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsDelta" - } - ], - "eventName": "vLoadBalancer", - "policyVersion": "v0.0.1", - "controlLoopSchemaType": "VM", - "policyName": "DCAE.Config_tca-hi-lo" - } - ] - } - }; + const policyProperties = { + "tca.policy": { + "domain": "measurementsForVfScaling", + "metricsPerEventName": [ + { + "policyScope": "DCAE", + "thresholds": [ + { + "version": "1.0.2", + "severity": "MAJOR", + "thresholdValue": 200, + "closedLoopEventStatus": "ONSET", + "closedLoopControlName": "LOOP_test", + "direction": "LESS_OR_EQUAL", + "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsDelta" + } + ], + "eventName": "vLoadBalancer", + "policyVersion": "v0.0.1", + "controlLoopSchemaType": "VM", + "policyName": "DCAE.Config_tca-hi-lo" + } + ] + } + }; - it('Test the render method',async () => { - PolicyToscaService.getToscaPolicyModel = jest.fn().mockImplementation(() => { - return Promise.resolve(toscaJson); - }); - - const component = mount(<PolicyEditor policyModelType="onap.policies.monitoring.tcagen2" policyModelTypeVersion="1.0.0" - policyName="org.onap.new" policyVersion="1.0.0" policyProperties={policyProperties} - policiesTableUpdateFunction={() => {}} />); - await PolicyToscaService.getToscaPolicyModel(); - expect(component).toMatchSnapshot(); + it('Test the render method', async () => { + PolicyToscaService.getToscaPolicyModel = jest.fn().mockImplementation(() => { + return Promise.resolve(toscaJson); }); -});
\ No newline at end of file + + const component = mount(<PolicyEditor policyModelType="onap.policies.monitoring.tcagen2" policyModelTypeVersion="1.0.0" + policyName="org.onap.new" policyVersion="1.0.0" policyProperties={ policyProperties } + policiesTableUpdateFunction={ () => { + } }/>); + await PolicyToscaService.getToscaPolicyModel(); + expect(component).toMatchSnapshot(); + }); +}); diff --git a/runtime/ui-react/src/components/dialogs/Policy/PolicyToscaFileSelector.js b/runtime/ui-react/src/components/dialogs/Policy/PolicyToscaFileSelector.js index 9cd3d4172..8093b7e4e 100644 --- a/runtime/ui-react/src/components/dialogs/Policy/PolicyToscaFileSelector.js +++ b/runtime/ui-react/src/components/dialogs/Policy/PolicyToscaFileSelector.js @@ -27,102 +27,107 @@ import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import styled from 'styled-components'; import Alert from 'react-bootstrap/Alert'; -import { Input, InputLabel, Button , SvgIcon} from "@material-ui/core"; +import { Input, InputLabel, Button, SvgIcon } from "@material-ui/core"; import PublishIcon from '@material-ui/icons/Publish'; import PolicyService from '../../../api/PolicyService'; const ModalStyled = styled(Modal)` - background-color: transparent; + background-color: transparent; ` const StyledMessagesDiv = styled.div` - overflow: auto; - max-height: 300px; + overflow: auto; + max-height: 300px; ` export default class PolicyToscaFileSelector extends React.Component { - state = { - show: this.props.show, - alertMessages: [], - } - constructor(props, context) { - super(props, context); - this.handleClose = this.handleClose.bind(this); - this.onFileChange = this.onFileChange.bind(this); - } + state = { + show: this.props.show, + alertMessages: [], + } - componentDidUpdate(prevProps) { - if (this.props.show !== this.state.show) { - this.setState({show: this.props.show}); - } - } + constructor(props, context) { + super(props, context); + this.handleClose = this.handleClose.bind(this); + this.onFileChange = this.onFileChange.bind(this); + } - handleClose() { - this.props.disableFunction(); - this.setState({alertMessages:[]}); + componentDidUpdate(prevProps) { + if (this.props.show !== this.state.show) { + this.setState({ show: this.props.show }); } + } - onFileChange(target) { - this.setState({alertMessages:[]}); - target.currentTarget.files.forEach(file => { - const fileReader = new FileReader(); - fileReader.readAsDataURL(file); - fileReader.onload = (content) => { - PolicyService.sendNewPolicyModel(atob(content.target.result.split(",")[1])).then(respModelCreate => { - if (typeof(respModelCreate) === "undefined") { - //it indicates a failure - this.setState(state => { - return { - alertMessages: [...state.alertMessages,(<Alert variant="danger"><Alert.Heading>{file.name}</Alert.Heading><p>Policy Tosca Model Creation Failure</p><hr/><p>Type: {file.type}</p><p>Size: {file.size}</p></Alert>)] - }; - }); - } else { - this.props.toscaTableUpdateFunction(); - this.setState(state => { - return { - alertMessages: [...state.alertMessages,(<Alert variant="success"><Alert.Heading>{file.name}</Alert.Heading><p>Policy Tosca Model Created Successfully</p><hr/><p>Type: {file.type}</p><p>Size: {file.size}</p></Alert>)] - }; - }); - } - }); - }; + handleClose() { + this.props.disableFunction(); + this.setState({ alertMessages: [] }); + } + + onFileChange(target) { + this.setState({ alertMessages: [] }); + target.currentTarget.files.forEach(file => { + const fileReader = new FileReader(); + fileReader.readAsDataURL(file); + fileReader.onload = (content) => { + PolicyService.sendNewPolicyModel(atob(content.target.result.split(",")[1])).then(respModelCreate => { + if (typeof (respModelCreate) === "undefined") { + //it indicates a failure + this.setState(state => { + return { + alertMessages: [...state.alertMessages, (<Alert variant="danger"><Alert.Heading>{ file.name }</Alert.Heading><p>Policy Tosca Model Creation Failure</p> + <hr/> + <p>Type: { file.type }</p><p>Size: { file.size }</p></Alert>)] + }; + }); + } else { + this.props.toscaTableUpdateFunction(); + this.setState(state => { + return { + alertMessages: [...state.alertMessages, (<Alert variant="success"><Alert.Heading>{ file.name }</Alert.Heading><p>Policy Tosca Model Created Successfully</p> + <hr/> + <p>Type: { file.type }</p><p>Size: { file.size }</p></Alert>)] + }; + }); + } }); + }; + }); - } + } - render() { - return ( - <ModalStyled size="lg" show={this.state.show} onHide={this.handleClose} backdrop="static" keyboard={false} > - <Modal.Header closeButton> - <Modal.Title>Create New Policy Tosca Model</Modal.Title> - </Modal.Header> - <Modal.Body> - <Form.Group as={Row} controlId="formPlaintextEmail"> - <Col sm="10"> - <input type="file" multiple accept=".yaml,.yml" id="fileUploadButton" style={{ display: 'none' }} onChange={this.onFileChange} /> - <label htmlFor={'fileUploadButton'}> - <Button color="primary" variant="contained" component="span" - startIcon={ - <SvgIcon fontSize="small"> - <PublishIcon /> - </SvgIcon> - }> - Upload Files - </Button> - <p>(Only YAML files are supported)</p> - </label> - <StyledMessagesDiv> - {this.state.alertMessages} - </StyledMessagesDiv> - </Col> - </Form.Group> - </Modal.Body> - <Modal.Footer> - <Button variant="secondary" onClick={this.handleClose}>Close</Button> - </Modal.Footer> - </ModalStyled> - ); - } -}
\ No newline at end of file + render() { + return ( + <ModalStyled size="lg" show={ this.state.show } onHide={ this.handleClose } backdrop="static" keyboard={ false }> + <Modal.Header closeButton> + <Modal.Title>Create New Policy Tosca Model</Modal.Title> + </Modal.Header> + <Modal.Body> + <Form.Group as={ Row } controlId="formPlaintextEmail"> + <Col sm="10"> + <input type="file" multiple accept=".yaml,.yml" id="fileUploadButton" style={ { display: 'none' } } onChange={ this.onFileChange }/> + <label htmlFor={ 'fileUploadButton' }> + <Button color="primary" variant="contained" component="span" + startIcon={ + <SvgIcon fontSize="small"> + <PublishIcon/> + </SvgIcon> + }> + Upload Files + </Button> + <p>(Only YAML files are supported)</p> + </label> + <StyledMessagesDiv> + { this.state.alertMessages } + </StyledMessagesDiv> + </Col> + </Form.Group> + </Modal.Body> + <Modal.Footer> + <Button variant="secondary" onClick={ this.handleClose }>Close</Button> + </Modal.Footer> + </ModalStyled> + ); + } +} diff --git a/runtime/ui-react/src/components/dialogs/Policy/ToscaViewer.js b/runtime/ui-react/src/components/dialogs/Policy/ToscaViewer.js index fa83aa245..fc69a637a 100644 --- a/runtime/ui-react/src/components/dialogs/Policy/ToscaViewer.js +++ b/runtime/ui-react/src/components/dialogs/Policy/ToscaViewer.js @@ -27,40 +27,40 @@ import styled from 'styled-components'; import Button from 'react-bootstrap/Button'; const ToscaDiv = styled.div` - background-color: ${props => props.theme.toscaTextareaBackgroundColor}; - text-align: justify; - font-size: ${props => props.theme.toscaTextareaFontSize}; - width: 100%; - height: 30%; + background-color: ${ props => props.theme.toscaTextareaBackgroundColor }; + text-align: justify; + font-size: ${ props => props.theme.toscaTextareaFontSize }; + width: 100%; + height: 30%; ` export default class ToscaViewer extends React.Component { - state = { - toscaData: this.props.toscaData, - yamlPolicyTosca: this.getToscaModelYamlFor(this.props.toscaData), - } + state = { + toscaData: this.props.toscaData, + yamlPolicyTosca: this.getToscaModelYamlFor(this.props.toscaData), + } - constructor(props, context) { - super(props, context); - this.getToscaModelYamlFor = this.getToscaModelYamlFor.bind(this); - } + constructor(props, context) { + super(props, context); + this.getToscaModelYamlFor = this.getToscaModelYamlFor.bind(this); + } - getToscaModelYamlFor(toscaData) { - PolicyToscaService.getToscaPolicyModelYaml(toscaData["policyModelType"], toscaData["version"]).then(respYamlPolicyTosca => { - this.setState({ - yamlPolicyTosca: respYamlPolicyTosca, - }) - }); - } + getToscaModelYamlFor(toscaData) { + PolicyToscaService.getToscaPolicyModelYaml(toscaData["policyModelType"], toscaData["version"]).then(respYamlPolicyTosca => { + this.setState({ + yamlPolicyTosca: respYamlPolicyTosca, + }) + }); + } - render() { - return ( - <ToscaDiv> - <pre>{this.state.yamlPolicyTosca}</pre> - <Button variant="secondary" title="Create a new policy version from the defined parameters" - onClick={this.handleCreateNewVersion}>Create New Version</Button> - </ToscaDiv> - ); - } + render() { + return ( + <ToscaDiv> + <pre>{ this.state.yamlPolicyTosca }</pre> + <Button variant="secondary" title="Create a new policy version from the defined parameters" + onClick={ this.handleCreateNewVersion }>Create New Version</Button> + </ToscaDiv> + ); + } } diff --git a/runtime/ui-react/src/components/dialogs/Policy/ToscaViewer.test.js b/runtime/ui-react/src/components/dialogs/Policy/ToscaViewer.test.js index cc8c59a03..5b5976046 100644 --- a/runtime/ui-react/src/components/dialogs/Policy/ToscaViewer.test.js +++ b/runtime/ui-react/src/components/dialogs/Policy/ToscaViewer.test.js @@ -26,29 +26,29 @@ import { shallow, mount } from 'enzyme'; import PolicyToscaService from '../../../api/PolicyToscaService'; describe('Verify ToscaViewer', () => { - const fs = require('fs'); + const fs = require('fs'); - let toscaYaml = fs.readFileSync('src/components/dialogs/Policy/toscaData.test.yaml', {encoding:'utf8', flag:'r'}) + let toscaYaml = fs.readFileSync('src/components/dialogs/Policy/toscaData.test.yaml', { encoding: 'utf8', flag: 'r' }) - const toscaData = { - "policyModelType": "onap.policies.controlloop.Guard", - "version": "1.0.0", - "policyAcronym": "Guard", - "createdDate": "2021-04-09T02:29:31.407356Z", - "updatedDate": "2021-04-09T02:29:31.407356Z", - "updatedBy": "Not found", - "createdBy": "Not found", - "tableData": { - "id": 0 - } - }; + const toscaData = { + "policyModelType": "onap.policies.controlloop.Guard", + "version": "1.0.0", + "policyAcronym": "Guard", + "createdDate": "2021-04-09T02:29:31.407356Z", + "updatedDate": "2021-04-09T02:29:31.407356Z", + "updatedBy": "Not found", + "createdBy": "Not found", + "tableData": { + "id": 0 + } + }; - it('Test the render method',async () => { - PolicyToscaService.getToscaPolicyModelYaml = jest.fn().mockImplementation(() => { - return Promise.resolve(toscaYaml); - }); - const component = shallow(<ToscaViewer toscaData={toscaData}/>); - await PolicyToscaService.getToscaPolicyModelYaml(); - expect(component).toMatchSnapshot(); - }); + it('Test the render method', async () => { + PolicyToscaService.getToscaPolicyModelYaml = jest.fn().mockImplementation(() => { + return Promise.resolve(toscaYaml); + }); + const component = shallow(<ToscaViewer toscaData={ toscaData }/>); + await PolicyToscaService.getToscaPolicyModelYaml(); + expect(component).toMatchSnapshot(); + }); }); diff --git a/runtime/ui-react/src/components/dialogs/Policy/ViewAllPolicies.js b/runtime/ui-react/src/components/dialogs/Policy/ViewAllPolicies.js index 04965352b..f571bc16d 100644 --- a/runtime/ui-react/src/components/dialogs/Policy/ViewAllPolicies.js +++ b/runtime/ui-react/src/components/dialogs/Policy/ViewAllPolicies.js @@ -59,415 +59,417 @@ import PoliciesTreeViewer from './PoliciesTreeViewer'; import PolicyToscaFileSelector from './PolicyToscaFileSelector'; const DivWhiteSpaceStyled = styled.div` - white-space: pre; + white-space: pre; ` const ModalStyled = styled(Modal)` - @media (min-width: 800px) { - .modal-xl { - max-width: 96%; - } + @media (min-width: 800px) { + .modal-xl { + max-width: 96%; } - background-color: transparent; + } + background-color: transparent; ` const DetailedRow = styled.div` - margin: 0 auto; - background-color: ${props => props.theme.policyEditorBackgroundColor}; - font-size: ${props => props.theme.policyEditorFontSize}; - width: 97%; - margin-left: auto; - margin-right: auto; - margin-top: 20px; + margin: 0 auto; + background-color: ${ props => props.theme.policyEditorBackgroundColor }; + font-size: ${ props => props.theme.policyEditorFontSize }; + width: 97%; + margin-left: auto; + margin-right: auto; + margin-top: 20px; ` const PoliciesTreeViewerDiv = styled.div` - width: 20%; - float: left; - left: 0; - overflow: auto; + width: 20%; + float: left; + left: 0; + overflow: auto; ` const MaterialTableDiv = styled.div` - float: right; - width: 80%; - left: 20%; + float: right; + width: 80%; + left: 20%; ` const standardCellStyle = { backgroundColor: '#039be5', color: '#FFF', border: '1px solid black' }; const headerStyle = { backgroundColor: '#ddd', border: '2px solid black' }; -const rowHeaderStyle = {backgroundColor:'#ddd', fontSize: '15pt', text: 'bold', border: '1px solid black'}; +const rowHeaderStyle = { backgroundColor: '#ddd', fontSize: '15pt', text: 'bold', border: '1px solid black' }; export default class ViewAllPolicies extends React.Component { state = { - show: true, - policiesListData: [], - policiesListDataFiltered: [], - toscaModelsListData: [], - toscaModelsListDataFiltered: [], - jsonEditorForPolicy: new Map(), - showSuccessAlert: false, - showFailAlert: false, - showFileSelector: false, - policyColumnsDefinition: [ - { - title: "Policy Name", field: "name", - cellStyle: standardCellStyle, - headerStyle: headerStyle - }, - { - title: "Policy Version", field: "version", - cellStyle: standardCellStyle, - headerStyle: headerStyle, - }, - { - title: "Policy Type", field: "type", - cellStyle: standardCellStyle, - headerStyle: headerStyle - }, - { - title: "Policy Type Version", field: "type_version", - cellStyle: standardCellStyle, - headerStyle: headerStyle - }, - { - title: "Deployable in PDP Group", field: "supportedPdpGroupsString", - cellStyle: standardCellStyle, - headerStyle: headerStyle - }, - { - title: "Deployed in PDP Group", field: "pdpGroupInfoString", - cellStyle: standardCellStyle, - headerStyle: headerStyle - } - ], - toscaColumnsDefinition: [ - { - title: "Policy Model Type", field: "policyModelType", - cellStyle: standardCellStyle, - headerStyle: headerStyle - }, - { - title: "Policy Acronym", field: "policyAcronym", - cellStyle: standardCellStyle, - headerStyle: headerStyle - }, - { - title: "Version", field: "version", - cellStyle: standardCellStyle, - headerStyle: headerStyle - }, - { - title: "Uploaded By", field: "updatedBy", - cellStyle: standardCellStyle, - headerStyle: headerStyle - }, - { - title: "Uploaded Date", field: "updatedDate", editable: 'never', - cellStyle: standardCellStyle, - headerStyle: headerStyle - } - ], - tableIcons: { - Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />), - Check: forwardRef((props, ref) => <Check {...props} ref={ref} />), - Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />), - Delete: forwardRef((props, ref) => <DeleteRoundedIcon {...props} ref={ref} />), - DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />), - Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />), - Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />), - Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />), - FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />), - LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />), - NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />), - PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />), - ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />), - Search: forwardRef((props, ref) => <Search {...props} ref={ref} />), - SortArrow: forwardRef((props, ref) => <ArrowDownward {...props} ref={ref} />), - ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />), - ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />) - } - }; - - constructor(props, context) { - super(props, context); - this.handleClose = this.handleClose.bind(this); - this.handleDeletePolicy = this.handleDeletePolicy.bind(this); - this.disableAlert = this.disableAlert.bind(this); - this.getAllPolicies = this.getAllPolicies.bind(this); - this.getAllToscaModels = this.getAllToscaModels.bind(this); - this.generateAdditionalPolicyColumns = this.generateAdditionalPolicyColumns.bind(this); - this.filterPolicies = this.filterPolicies.bind(this); - this.filterTosca = this.filterTosca.bind(this); - this.showFileSelector = this.showFileSelector.bind(this); - this.disableFileSelector = this.disableFileSelector.bind(this); - this.getAllPolicies(); - this.getAllToscaModels(); + show: true, + policiesListData: [], + policiesListDataFiltered: [], + toscaModelsListData: [], + toscaModelsListDataFiltered: [], + jsonEditorForPolicy: new Map(), + showSuccessAlert: false, + showFailAlert: false, + showFileSelector: false, + policyColumnsDefinition: [ + { + title: "Policy Name", field: "name", + cellStyle: standardCellStyle, + headerStyle: headerStyle + }, + { + title: "Policy Version", field: "version", + cellStyle: standardCellStyle, + headerStyle: headerStyle, + }, + { + title: "Policy Type", field: "type", + cellStyle: standardCellStyle, + headerStyle: headerStyle + }, + { + title: "Policy Type Version", field: "type_version", + cellStyle: standardCellStyle, + headerStyle: headerStyle + }, + { + title: "Deployable in PDP Group", field: "supportedPdpGroupsString", + cellStyle: standardCellStyle, + headerStyle: headerStyle + }, + { + title: "Deployed in PDP Group", field: "pdpGroupInfoString", + cellStyle: standardCellStyle, + headerStyle: headerStyle + } + ], + toscaColumnsDefinition: [ + { + title: "Policy Model Type", field: "policyModelType", + cellStyle: standardCellStyle, + headerStyle: headerStyle + }, + { + title: "Policy Acronym", field: "policyAcronym", + cellStyle: standardCellStyle, + headerStyle: headerStyle + }, + { + title: "Version", field: "version", + cellStyle: standardCellStyle, + headerStyle: headerStyle + }, + { + title: "Uploaded By", field: "updatedBy", + cellStyle: standardCellStyle, + headerStyle: headerStyle + }, + { + title: "Uploaded Date", field: "updatedDate", editable: 'never', + cellStyle: standardCellStyle, + headerStyle: headerStyle + } + ], + tableIcons: { + Add: forwardRef((props, ref) => <AddBox { ...props } ref={ ref }/>), + Check: forwardRef((props, ref) => <Check { ...props } ref={ ref }/>), + Clear: forwardRef((props, ref) => <Clear { ...props } ref={ ref }/>), + Delete: forwardRef((props, ref) => <DeleteRoundedIcon { ...props } ref={ ref }/>), + DetailPanel: forwardRef((props, ref) => <ChevronRight { ...props } ref={ ref }/>), + Edit: forwardRef((props, ref) => <Edit { ...props } ref={ ref }/>), + Export: forwardRef((props, ref) => <SaveAlt { ...props } ref={ ref }/>), + Filter: forwardRef((props, ref) => <FilterList { ...props } ref={ ref }/>), + FirstPage: forwardRef((props, ref) => <FirstPage { ...props } ref={ ref }/>), + LastPage: forwardRef((props, ref) => <LastPage { ...props } ref={ ref }/>), + NextPage: forwardRef((props, ref) => <ChevronRight { ...props } ref={ ref }/>), + PreviousPage: forwardRef((props, ref) => <ChevronLeft { ...props } ref={ ref }/>), + ResetSearch: forwardRef((props, ref) => <Clear { ...props } ref={ ref }/>), + Search: forwardRef((props, ref) => <Search { ...props } ref={ ref }/>), + SortArrow: forwardRef((props, ref) => <ArrowDownward { ...props } ref={ ref }/>), + ThirdStateCheck: forwardRef((props, ref) => <Remove { ...props } ref={ ref }/>), + ViewColumn: forwardRef((props, ref) => <ViewColumn { ...props } ref={ ref }/>) } + }; - generateAdditionalPolicyColumns(policiesData) { - policiesData.forEach(policy => { - let supportedPdpGroupsString = ""; - if (typeof policy.supportedPdpGroups !== "undefined") { - for (const pdpGroup of policy["supportedPdpGroups"]) { - for (const pdpSubGroup of Object.values(pdpGroup)[0]) { - supportedPdpGroupsString += (Object.keys(pdpGroup)[0] + "/" + pdpSubGroup + "\r\n"); - } - } - policy["supportedPdpGroupsString"] = supportedPdpGroupsString; - } + constructor(props, context) { + super(props, context); + this.handleClose = this.handleClose.bind(this); + this.handleDeletePolicy = this.handleDeletePolicy.bind(this); + this.disableAlert = this.disableAlert.bind(this); + this.getAllPolicies = this.getAllPolicies.bind(this); + this.getAllToscaModels = this.getAllToscaModels.bind(this); + this.generateAdditionalPolicyColumns = this.generateAdditionalPolicyColumns.bind(this); + this.filterPolicies = this.filterPolicies.bind(this); + this.filterTosca = this.filterTosca.bind(this); + this.showFileSelector = this.showFileSelector.bind(this); + this.disableFileSelector = this.disableFileSelector.bind(this); + this.getAllPolicies(); + this.getAllToscaModels(); + } - let infoPdpGroup = ""; - if (typeof policy.pdpGroupInfo !== "undefined") { - policy["pdpGroupInfo"].forEach(pdpGroupElem => { - let groupName = Object.keys(pdpGroupElem)[0]; - pdpGroupElem[groupName]["pdpSubgroups"].forEach(pdpSubGroupElem => { - infoPdpGroup += (groupName + "/" + pdpSubGroupElem["pdpType"] + " (" - + pdpGroupElem[groupName]["pdpGroupState"] + ")" + "\r\n"); - }); - policy["pdpGroupInfoString"] = infoPdpGroup; - }); - } - }); - } + generateAdditionalPolicyColumns(policiesData) { + policiesData.forEach(policy => { + let supportedPdpGroupsString = ""; + if (typeof policy.supportedPdpGroups !== "undefined") { + for (const pdpGroup of policy["supportedPdpGroups"]) { + for (const pdpSubGroup of Object.values(pdpGroup)[0]) { + supportedPdpGroupsString += (Object.keys(pdpGroup)[0] + "/" + pdpSubGroup + "\r\n"); + } + } + policy["supportedPdpGroupsString"] = supportedPdpGroupsString; + } - getAllToscaModels() { - PolicyToscaService.getToscaPolicyModels().then(toscaModelsList => { - this.setState({ toscaModelsListData: toscaModelsList, - toscaModelsListDataFiltered: toscaModelsList - }); + let infoPdpGroup = ""; + if (typeof policy.pdpGroupInfo !== "undefined") { + policy["pdpGroupInfo"].forEach(pdpGroupElem => { + let groupName = Object.keys(pdpGroupElem)[0]; + pdpGroupElem[groupName]["pdpSubgroups"].forEach(pdpSubGroupElem => { + infoPdpGroup += (groupName + "/" + pdpSubGroupElem["pdpType"] + " (" + + pdpGroupElem[groupName]["pdpGroupState"] + ")" + "\r\n"); + }); + policy["pdpGroupInfoString"] = infoPdpGroup; }); - } + } + }); + } - getAllPolicies() { - PolicyService.getPoliciesList().then(allPolicies => { - this.generateAdditionalPolicyColumns(allPolicies["policies"]) - this.setState({ policiesListData: allPolicies["policies"], - policiesListDataFiltered: allPolicies["policies"], - }) - }); + getAllToscaModels() { + PolicyToscaService.getToscaPolicyModels().then(toscaModelsList => { + this.setState({ + toscaModelsListData: toscaModelsList, + toscaModelsListDataFiltered: toscaModelsList + }); + }); + } - } + getAllPolicies() { + PolicyService.getPoliciesList().then(allPolicies => { + this.generateAdditionalPolicyColumns(allPolicies["policies"]) + this.setState({ + policiesListData: allPolicies["policies"], + policiesListDataFiltered: allPolicies["policies"], + }) + }); - handleClose() { - this.setState({ show: false }); - this.props.history.push('/') - } + } - handleDeletePolicy(event, rowData) { - PolicyService.deletePolicy(rowData["type"], rowData["type_version"], rowData["name"],rowData["version"]).then( - respPolicyDeletion => { - if (typeof(respPolicyDeletion) === "undefined") { - //it indicates a failure - this.setState({ - showFailAlert: true, - showMessage: 'Policy Deletion Failure' - }); - } else { - this.setState({ - showSuccessAlert: true, - showMessage: 'Policy successfully Deleted' - }); - this.getAllPolicies(); - } - } - ) - } + handleClose() { + this.setState({ show: false }); + this.props.history.push('/') + } - disableAlert() { - this.setState ({ showSuccessAlert: false, showFailAlert: false }); - } + handleDeletePolicy(event, rowData) { + PolicyService.deletePolicy(rowData["type"], rowData["type_version"], rowData["name"], rowData["version"]).then( + respPolicyDeletion => { + if (typeof (respPolicyDeletion) === "undefined") { + //it indicates a failure + this.setState({ + showFailAlert: true, + showMessage: 'Policy Deletion Failure' + }); + } else { + this.setState({ + showSuccessAlert: true, + showMessage: 'Policy successfully Deleted' + }); + this.getAllPolicies(); + } + } + ) + } - filterPolicies(prefixForFiltering) { - this.setState({policiesListDataFiltered: this.state.policiesListData.filter(element => element.name.startsWith(prefixForFiltering))}); - } + disableAlert() { + this.setState({ showSuccessAlert: false, showFailAlert: false }); + } - filterTosca(prefixForFiltering) { - this.setState({toscaModelsListDataFiltered: this.state.toscaModelsListData.filter(element => element.policyModelType.startsWith(prefixForFiltering))}); - } + filterPolicies(prefixForFiltering) { + this.setState({ policiesListDataFiltered: this.state.policiesListData.filter(element => element.name.startsWith(prefixForFiltering)) }); + } - showFileSelector() { - this.setState({showFileSelector:true}); - } + filterTosca(prefixForFiltering) { + this.setState({ toscaModelsListDataFiltered: this.state.toscaModelsListData.filter(element => element.policyModelType.startsWith(prefixForFiltering)) }); + } - disableFileSelector() { - this.setState({showFileSelector:false}); - } + showFileSelector() { + this.setState({ showFileSelector: true }); + } - renderPoliciesTab() { - return ( - <Tab eventKey="policies" title="Policies in Policy Framework"> - <Modal.Body> - <div> - <PoliciesTreeViewerDiv> - <PoliciesTreeViewer policiesData={this.state.policiesListData} valueForTreeCreation="name" policiesFilterFunction={this.filterPolicies} /> - </PoliciesTreeViewerDiv> - <MaterialTableDiv> - <MaterialTable - title={"Policies"} - data={this.state.policiesListDataFiltered} - columns={this.state.policyColumnsDefinition} - icons={this.state.tableIcons} - onRowClick={(event, rowData, togglePanel) => togglePanel()} - options={{ - grouping: true, - exportButton: true, - headerStyle:rowHeaderStyle, - actionsColumnIndex: -1 - }} - detailPanel={[ - { - icon: ArrowForwardIosIcon, - tooltip: 'Show Configuration', - render: rowData => { - return ( - <DetailedRow> - <PolicyEditor policyModelType={rowData["type"]} policyModelTypeVersion={rowData["type_version"]} - policyName={rowData["name"]} policyVersion={rowData["version"]} policyProperties={rowData["properties"]} - policiesTableUpdateFunction={this.getAllPolicies} /> - </DetailedRow> - ) - }, - }, - { - icon: DehazeIcon, - openIcon: DehazeIcon, - tooltip: 'Show Raw Data', - render: rowData => { - return ( - <DetailedRow> - <pre>{JSON.stringify(rowData, null, 2)}</pre> - </DetailedRow> - ) - }, - }, - { - icon: PublishIcon, - openIcon: PublishIcon, - tooltip: 'PDP Group Deployment', - render: rowData => { - return ( - <DetailedRow> - <PolicyDeploymentEditor policyData={rowData} policiesTableUpdateFunction={this.getAllPolicies} /> - </DetailedRow> - ) - }, - } - ]} - actions={[ - { - icon: DeleteRoundedIcon, - tooltip: 'Delete Policy', - onClick: (event, rowData) => this.handleDeletePolicy(event, rowData) - } - ]} - /> - </MaterialTableDiv> - </div> - </Modal.Body> - </Tab> - ); - } + disableFileSelector() { + this.setState({ showFileSelector: false }); + } - renderToscaTab() { - return ( - <Tab eventKey="tosca models" title="Tosca Models in Policy Framework"> - <Modal.Body> - <div> - <PoliciesTreeViewerDiv> - <PoliciesTreeViewer policiesData={this.state.toscaModelsListData} valueForTreeCreation="policyModelType" policiesFilterFunction={this.filterTosca} /> - </PoliciesTreeViewerDiv> - <MaterialTableDiv> - <MaterialTable - title={"Tosca Models"} - data={this.state.toscaModelsListDataFiltered} - columns={this.state.toscaColumnsDefinition} - icons={this.state.tableIcons} - onRowClick={(event, rowData, togglePanel) => togglePanel()} - options={{ - grouping: true, - exportButton: true, - headerStyle:rowHeaderStyle, - actionsColumnIndex: -1 - }} - actions={[ - { - icon: AddIcon, - tooltip: 'Add New Tosca Model', - isFreeAction: true, - onClick: () => this.showFileSelector() - } - ]} - detailPanel={[ - { - icon: ArrowForwardIosIcon, - tooltip: 'Show Tosca', - render: rowData => { - return ( - <DetailedRow> - <ToscaViewer toscaData={rowData} /> - </DetailedRow> - ) - }, - }, - { - icon: DehazeIcon, - openIcon: DehazeIcon, - tooltip: 'Show Raw Data', - render: rowData => { - return ( - <DetailedRow> - <pre>{JSON.stringify(rowData, null, 2)}</pre> - </DetailedRow> - ) - }, - }, - { - icon: AddIcon, - openIcon: AddIcon, - tooltip: 'Create a policy from this model', - render: rowData => { - return ( - <DetailedRow> - <PolicyEditor policyModelType={rowData["policyModelType"]} policyModelTypeVersion={rowData["version"]} policyProperties={{}} policiesTableUpdateFunction={this.getAllPolicies} /> - </DetailedRow> - ) - }, - }, - ]} - /> - </MaterialTableDiv> - </div> - </Modal.Body> - </Tab> - ); - } + renderPoliciesTab() { + return ( + <Tab eventKey="policies" title="Policies in Policy Framework"> + <Modal.Body> + <div> + <PoliciesTreeViewerDiv> + <PoliciesTreeViewer policiesData={ this.state.policiesListData } valueForTreeCreation="name" policiesFilterFunction={ this.filterPolicies }/> + </PoliciesTreeViewerDiv> + <MaterialTableDiv> + <MaterialTable + title={ "Policies" } + data={ this.state.policiesListDataFiltered } + columns={ this.state.policyColumnsDefinition } + icons={ this.state.tableIcons } + onRowClick={ (event, rowData, togglePanel) => togglePanel() } + options={ { + grouping: true, + exportButton: true, + headerStyle: rowHeaderStyle, + actionsColumnIndex: -1 + } } + detailPanel={ [ + { + icon: ArrowForwardIosIcon, + tooltip: 'Show Configuration', + render: rowData => { + return ( + <DetailedRow> + <PolicyEditor policyModelType={ rowData["type"] } policyModelTypeVersion={ rowData["type_version"] } + policyName={ rowData["name"] } policyVersion={ rowData["version"] } policyProperties={ rowData["properties"] } + policiesTableUpdateFunction={ this.getAllPolicies }/> + </DetailedRow> + ) + }, + }, + { + icon: DehazeIcon, + openIcon: DehazeIcon, + tooltip: 'Show Raw Data', + render: rowData => { + return ( + <DetailedRow> + <pre>{ JSON.stringify(rowData, null, 2) }</pre> + </DetailedRow> + ) + }, + }, + { + icon: PublishIcon, + openIcon: PublishIcon, + tooltip: 'PDP Group Deployment', + render: rowData => { + return ( + <DetailedRow> + <PolicyDeploymentEditor policyData={ rowData } policiesTableUpdateFunction={ this.getAllPolicies }/> + </DetailedRow> + ) + }, + } + ] } + actions={ [ + { + icon: DeleteRoundedIcon, + tooltip: 'Delete Policy', + onClick: (event, rowData) => this.handleDeletePolicy(event, rowData) + } + ] } + /> + </MaterialTableDiv> + </div> + </Modal.Body> + </Tab> + ); + } - render() { - return ( - <React.Fragment> - <ModalStyled size="xl" show={this.state.show} onHide={this.handleClose} backdrop="static" keyboard={false}> - <Modal.Header closeButton> - </Modal.Header> - <Tabs id="controlled-tab-example" activeKey={this.state.key} onSelect={key => this.setState({ key, selectedRowData: {} })}> - {this.renderPoliciesTab()} - {this.renderToscaTab()} - </Tabs> - <Alert variant="success" show={this.state.showSuccessAlert} onClose={this.disableAlert} dismissible> - <DivWhiteSpaceStyled> - {this.state.showMessage} - </DivWhiteSpaceStyled> - </Alert> - <Alert variant="danger" show={this.state.showFailAlert} onClose={this.disableAlert} dismissible> - <DivWhiteSpaceStyled> - {this.state.showMessage} - </DivWhiteSpaceStyled> - </Alert> - <Modal.Footer> - <Button variant="secondary" onClick={this.handleClose}>Close</Button> - </Modal.Footer> - </ModalStyled> - <PolicyToscaFileSelector show={this.state.showFileSelector} disableFunction={this.disableFileSelector} toscaTableUpdateFunction={this.getAllToscaModels}/> - </React.Fragment> - ); - } - }
\ No newline at end of file + renderToscaTab() { + return ( + <Tab eventKey="tosca models" title="Tosca Models in Policy Framework"> + <Modal.Body> + <div> + <PoliciesTreeViewerDiv> + <PoliciesTreeViewer policiesData={ this.state.toscaModelsListData } valueForTreeCreation="policyModelType" policiesFilterFunction={ this.filterTosca }/> + </PoliciesTreeViewerDiv> + <MaterialTableDiv> + <MaterialTable + title={ "Tosca Models" } + data={ this.state.toscaModelsListDataFiltered } + columns={ this.state.toscaColumnsDefinition } + icons={ this.state.tableIcons } + onRowClick={ (event, rowData, togglePanel) => togglePanel() } + options={ { + grouping: true, + exportButton: true, + headerStyle: rowHeaderStyle, + actionsColumnIndex: -1 + } } + actions={ [ + { + icon: AddIcon, + tooltip: 'Add New Tosca Model', + isFreeAction: true, + onClick: () => this.showFileSelector() + } + ] } + detailPanel={ [ + { + icon: ArrowForwardIosIcon, + tooltip: 'Show Tosca', + render: rowData => { + return ( + <DetailedRow> + <ToscaViewer toscaData={ rowData }/> + </DetailedRow> + ) + }, + }, + { + icon: DehazeIcon, + openIcon: DehazeIcon, + tooltip: 'Show Raw Data', + render: rowData => { + return ( + <DetailedRow> + <pre>{ JSON.stringify(rowData, null, 2) }</pre> + </DetailedRow> + ) + }, + }, + { + icon: AddIcon, + openIcon: AddIcon, + tooltip: 'Create a policy from this model', + render: rowData => { + return ( + <DetailedRow> + <PolicyEditor policyModelType={ rowData["policyModelType"] } policyModelTypeVersion={ rowData["version"] } policyProperties={ {} } policiesTableUpdateFunction={ this.getAllPolicies }/> + </DetailedRow> + ) + }, + }, + ] } + /> + </MaterialTableDiv> + </div> + </Modal.Body> + </Tab> + ); + } + + render() { + return ( + <React.Fragment> + <ModalStyled size="xl" show={ this.state.show } onHide={ this.handleClose } backdrop="static" keyboard={ false }> + <Modal.Header closeButton> + </Modal.Header> + <Tabs id="controlled-tab-example" activeKey={ this.state.key } onSelect={ key => this.setState({ key, selectedRowData: {} }) }> + { this.renderPoliciesTab() } + { this.renderToscaTab() } + </Tabs> + <Alert variant="success" show={ this.state.showSuccessAlert } onClose={ this.disableAlert } dismissible> + <DivWhiteSpaceStyled> + { this.state.showMessage } + </DivWhiteSpaceStyled> + </Alert> + <Alert variant="danger" show={ this.state.showFailAlert } onClose={ this.disableAlert } dismissible> + <DivWhiteSpaceStyled> + { this.state.showMessage } + </DivWhiteSpaceStyled> + </Alert> + <Modal.Footer> + <Button variant="secondary" onClick={ this.handleClose }>Close</Button> + </Modal.Footer> + </ModalStyled> + <PolicyToscaFileSelector show={ this.state.showFileSelector } disableFunction={ this.disableFileSelector } toscaTableUpdateFunction={ this.getAllToscaModels }/> + </React.Fragment> + ); + } +} diff --git a/runtime/ui-react/src/components/dialogs/RefreshStatus.js b/runtime/ui-react/src/components/dialogs/RefreshStatus.js index bb0939152..e23ab3f84 100644 --- a/runtime/ui-react/src/components/dialogs/RefreshStatus.js +++ b/runtime/ui-react/src/components/dialogs/RefreshStatus.js @@ -26,40 +26,40 @@ import Spinner from 'react-bootstrap/Spinner'; import styled from 'styled-components'; const StyledSpinnerDiv = styled.div` - justify-content: center !important; - display: flex !important; + justify-content: center !important; + display: flex !important; `; export default class RefreshStatus extends React.Component { - state = { - loopName: this.props.loopCache.getLoopName() - }; + state = { + loopName: this.props.loopCache.getLoopName() + }; - componentWillReceiveProps(newProps) { - this.setState({ - loopName: newProps.loopCache.getLoopName() - }); - } + componentWillReceiveProps(newProps) { + this.setState({ + loopName: newProps.loopCache.getLoopName() + }); + } - componentDidMount() { - // refresh status and update loop logs - LoopActionService.refreshStatus(this.state.loopName).then(data => { - this.props.showSucAlert("Status successfully refreshed"); - this.props.updateLoopFunction(data); - this.props.history.push('/'); - }) - .catch(error => { - this.props.showFailAlert("Status refreshing failed"); - this.props.history.push('/'); - }); - } + componentDidMount() { + // refresh status and update loop logs + LoopActionService.refreshStatus(this.state.loopName).then(data => { + this.props.showSucAlert("Status successfully refreshed"); + this.props.updateLoopFunction(data); + this.props.history.push('/'); + }) + .catch(error => { + this.props.showFailAlert("Status refreshing failed"); + this.props.history.push('/'); + }); + } - render() { - return ( - <StyledSpinnerDiv> - <Spinner animation="border" role="status"> - </Spinner> - </StyledSpinnerDiv> - ); - } + render() { + return ( + <StyledSpinnerDiv> + <Spinner animation="border" role="status"> + </Spinner> + </StyledSpinnerDiv> + ); + } } diff --git a/runtime/ui-react/src/components/dialogs/RefreshStatus.test.js b/runtime/ui-react/src/components/dialogs/RefreshStatus.test.js index e08c50d2e..7736ffd49 100644 --- a/runtime/ui-react/src/components/dialogs/RefreshStatus.test.js +++ b/runtime/ui-react/src/components/dialogs/RefreshStatus.test.js @@ -28,44 +28,45 @@ import LoopActionService from '../../api/LoopActionService'; describe('Verify RefreshStatus', () => { - const loopCache = new LoopCache({ - "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca" - }); + const loopCache = new LoopCache({ + "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca" + }); - it('Test refresh status failed', async () => { - const flushPromises = () => new Promise(setImmediate); - const historyMock = { push: jest.fn() }; - const showSucAlert = jest.fn(); - const showFailAlert = jest.fn(); + it('Test refresh status failed', async () => { + const flushPromises = () => new Promise(setImmediate); + const historyMock = { push: jest.fn() }; + const showSucAlert = jest.fn(); + const showFailAlert = jest.fn(); - const component = shallow(<RefreshStatus loopCache={loopCache} history={historyMock} showSucAlert={showSucAlert} showFailAlert={showFailAlert} />) - await flushPromises(); - component.update(); + const component = shallow(<RefreshStatus loopCache={ loopCache } history={ historyMock } showSucAlert={ showSucAlert } showFailAlert={ showFailAlert }/>) + await flushPromises(); + component.update(); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); - }); + expect(historyMock.push.mock.calls[0]).toEqual(['/']); + }); - it('Test refresh status successful', async () => { - const flushPromises = () => new Promise(setImmediate); - const historyMock = { push: jest.fn() }; - const updateLoopFunction = jest.fn(); - const showSucAlert = jest.fn(); - const showFailAlert = jest.fn(); + it('Test refresh status successful', async () => { + const flushPromises = () => new Promise(setImmediate); + const historyMock = { push: jest.fn() }; + const updateLoopFunction = jest.fn(); + const showSucAlert = jest.fn(); + const showFailAlert = jest.fn(); - LoopActionService.refreshStatus = jest.fn().mockImplementation(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => {} - }); - }); + LoopActionService.refreshStatus = jest.fn().mockImplementation(() => { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + } + }); + }); - const component = shallow(<RefreshStatus loopCache={loopCache} - loopAction="submit" history={historyMock} updateLoopFunction={updateLoopFunction} showSucAlert={showSucAlert} showFailAlert={showFailAlert} />) - await flushPromises(); - component.update(); + const component = shallow(<RefreshStatus loopCache={ loopCache } + loopAction="submit" history={ historyMock } updateLoopFunction={ updateLoopFunction } showSucAlert={ showSucAlert } showFailAlert={ showFailAlert }/>) + await flushPromises(); + component.update(); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); - }); + expect(historyMock.push.mock.calls[0]).toEqual(['/']); + }); }); diff --git a/runtime/ui-react/src/components/dialogs/Tosca/ViewLoopTemplatesModal.js b/runtime/ui-react/src/components/dialogs/Tosca/ViewLoopTemplatesModal.js index 4796b8d73..e7be9841e 100644 --- a/runtime/ui-react/src/components/dialogs/Tosca/ViewLoopTemplatesModal.js +++ b/runtime/ui-react/src/components/dialogs/Tosca/ViewLoopTemplatesModal.js @@ -38,126 +38,136 @@ import LoopCache from '../../../api/LoopCache'; import SvgGenerator from '../../loop_viewer/svg/SvgGenerator'; const ModalStyled = styled(Modal)` - background-color: transparent; + background-color: transparent; ` const cellStyle = { border: '1px solid black' }; -const headerStyle = { backgroundColor: '#ddd', border: '2px solid black' }; -const rowHeaderStyle = {backgroundColor:'#ddd', fontSize: '15pt', text: 'bold', border: '1px solid black'}; +const headerStyle = { backgroundColor: '#ddd', border: '2px solid black' }; +const rowHeaderStyle = { backgroundColor: '#ddd', fontSize: '15pt', text: 'bold', border: '1px solid black' }; export default class ViewLoopTemplatesModal extends React.Component { state = { - show: true, - content: 'Please select a loop template to display it', - selectedRow: -1, - loopTemplatesData: [], - fakeLoopCacheWithTemplate: new LoopCache({}), - loopTemplateColumnsDefinition: [ - { title: "#", field: "index", render: rowData => rowData.tableData.id + 1, - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { title: "Template Name", field: "name", - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { title: "Service Model Name", field: "modelService.serviceDetails.name", - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { title: "Loop Type Allowed", field: "allowedLoopType", - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { title: "# Instances Allowed", field: "maximumInstancesAllowed", - cellStyle: cellStyle, - headerStyle: headerStyle - }, - { title: "Modified Date", field: "updatedDate", editable: 'never', - cellStyle: cellStyle, - headerStyle: headerStyle - } - ], - tableIcons: { - FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />), - LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />), - NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />), - PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />), - ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />), - Search: forwardRef((props, ref) => <Search {...props} ref={ref} />), - SortArrow: forwardRef((props, ref) => <ArrowUpward {...props} ref={ref} />) - } - }; - - constructor(props, context) { - super(props, context); - this.handleClose = this.handleClose.bind(this); - this.renderSvg = this.renderSvg.bind(this); - this.getLoopTemplate = this.getLoopTemplate.bind(this); - this.getAllLoopTemplates(); - } + show: true, + content: 'Please select a loop template to display it', + selectedRow: -1, + loopTemplatesData: [], + fakeLoopCacheWithTemplate: new LoopCache({}), + loopTemplateColumnsDefinition: [ + { + title: "#", field: "index", render: rowData => rowData.tableData.id + 1, + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Template Name", field: "name", + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Service Model Name", field: "modelService.serviceDetails.name", + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Loop Type Allowed", field: "allowedLoopType", + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "# Instances Allowed", field: "maximumInstancesAllowed", + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Modified Date", field: "updatedDate", editable: 'never', + cellStyle: cellStyle, + headerStyle: headerStyle + } + ], + tableIcons: { + FirstPage: forwardRef((props, ref) => <FirstPage { ...props } ref={ ref }/>), + LastPage: forwardRef((props, ref) => <LastPage { ...props } ref={ ref }/>), + NextPage: forwardRef((props, ref) => <ChevronRight { ...props } ref={ ref }/>), + PreviousPage: forwardRef((props, ref) => <ChevronLeft { ...props } ref={ ref }/>), + ResetSearch: forwardRef((props, ref) => <Clear { ...props } ref={ ref }/>), + Search: forwardRef((props, ref) => <Search { ...props } ref={ ref }/>), + SortArrow: forwardRef((props, ref) => <ArrowUpward { ...props } ref={ ref }/>) + } + }; - getAllLoopTemplates() { - TemplateService.getAllLoopTemplates().then(templatesData => { - // replace -1 in maximumInstancesAllowed with more meaningful 'No Limit' - for (let item in templatesData) { - if (templatesData[item].maximumInstancesAllowed === -1) { - templatesData[item].maximumInstancesAllowed = 'No Limit'; - } - } - this.setState({ loopTemplatesData: templatesData }) - }); - } + constructor(props, context) { + super(props, context); + this.handleClose = this.handleClose.bind(this); + this.renderSvg = this.renderSvg.bind(this); + this.getLoopTemplate = this.getLoopTemplate.bind(this); + this.getAllLoopTemplates(); + } - getLoopTemplate(templateIdInDataArray) { - if (typeof templateIdInDataArray !== "undefined") { - this.setState({ fakeLoopCacheWithTemplate: - new LoopCache({ - "loopTemplate":this.state.loopTemplatesData[templateIdInDataArray], - "name": "fakeLoop" - }) - }) - } else { - this.setState({ fakeLoopCacheWithTemplate: new LoopCache({}) }) + getAllLoopTemplates() { + TemplateService.getAllLoopTemplates().then(templatesData => { + // replace -1 in maximumInstancesAllowed with more meaningful 'No Limit' + for (let item in templatesData) { + if (templatesData[item].maximumInstancesAllowed === -1) { + templatesData[item].maximumInstancesAllowed = 'No Limit'; } + } + this.setState({ loopTemplatesData: templatesData }) + }); + } + + getLoopTemplate(templateIdInDataArray) { + if (typeof templateIdInDataArray !== "undefined") { + this.setState({ + fakeLoopCacheWithTemplate: + new LoopCache({ + "loopTemplate": this.state.loopTemplatesData[templateIdInDataArray], + "name": "fakeLoop" + }) + }) + } else { + this.setState({ fakeLoopCacheWithTemplate: new LoopCache({}) }) } + } - handleClose() { - this.setState({ show: false }); - this.props.history.push('/') - } + handleClose() { + this.setState({ show: false }); + this.props.history.push('/') + } - renderSvg() { - return( - <SvgGenerator loopCache={this.state.fakeLoopCacheWithTemplate} clickable={false} generatedFrom={SvgGenerator.GENERATED_FROM_TEMPLATE}/> - ) - } + renderSvg() { + return ( + <SvgGenerator loopCache={ this.state.fakeLoopCacheWithTemplate } clickable={ false } generatedFrom={ SvgGenerator.GENERATED_FROM_TEMPLATE }/> + ) + } - render() { + render() { return ( - <ModalStyled size="xl" show={this.state.show} onHide={this.handleClose} backdrop="static" keyboard={false}> - <Modal.Header closeButton> - </Modal.Header> - <Modal.Body> - <MaterialTable - title={"View Blueprint MicroService Templates"} - data={this.state.loopTemplatesData} - columns={this.state.loopTemplateColumnsDefinition} - icons={this.state.tableIcons} - onRowClick={(event, rowData) => {this.getLoopTemplate(rowData.tableData.id);this.setState({selectedRow: rowData.tableData.id})}} - options={{ - headerStyle:rowHeaderStyle, - rowStyle: rowData => ({ - backgroundColor: (this.state.selectedRow !== -1 && this.state.selectedRow === rowData.tableData.id) ? '#EEE' : '#FFF' - }) - }} - /> - {this.renderSvg()} - </Modal.Body> - <Modal.Footer> - <Button variant="secondary" onClick={this.handleClose}>Close</Button> - </Modal.Footer> + <ModalStyled size="xl" show={ this.state.show } onHide={ this.handleClose } backdrop="static" keyboard={ false }> + <Modal.Header closeButton> + </Modal.Header> + <Modal.Body> + <MaterialTable + title={ "View Blueprint MicroService Templates" } + data={ this.state.loopTemplatesData } + columns={ this.state.loopTemplateColumnsDefinition } + icons={ this.state.tableIcons } + onRowClick={ (event, rowData) => { + this.getLoopTemplate(rowData.tableData.id); + this.setState({ selectedRow: rowData.tableData.id }) + } } + options={ { + headerStyle: rowHeaderStyle, + rowStyle: rowData => ({ + backgroundColor: (this.state.selectedRow !== -1 && this.state.selectedRow === rowData.tableData.id) ? '#EEE' : '#FFF' + }) + } } + /> + { this.renderSvg() } + </Modal.Body> + <Modal.Footer> + <Button variant="secondary" onClick={ this.handleClose }>Close</Button> + </Modal.Footer> </ModalStyled> - ); - } + ); } +} diff --git a/runtime/ui-react/src/components/dialogs/Tosca/ViewLoopTemplatesModal.test.js b/runtime/ui-react/src/components/dialogs/Tosca/ViewLoopTemplatesModal.test.js index 7680ec4b9..d93f0b00c 100644 --- a/runtime/ui-react/src/components/dialogs/Tosca/ViewLoopTemplatesModal.test.js +++ b/runtime/ui-react/src/components/dialogs/Tosca/ViewLoopTemplatesModal.test.js @@ -27,136 +27,137 @@ import { mount } from 'enzyme'; import { BrowserRouter as Router } from 'react-router-dom'; describe('Verify ViewLoopTemplatesModal', () => { - beforeEach(() => { - fetch.resetMocks(); - }); + beforeEach(() => { + fetch.resetMocks(); + }); - it('Test API Successful', () => { - fetch.mockImplementationOnce(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => { - return Promise.resolve({ - "index": "1", - "name": "MTCA version 1", - "modelService.serviceDetails.name": "MTCA", - "allowedLoopType" : "CLOSED", - "maximumInstancesAllowed":1, - "updatedDate":"2019-09-06 19:09:42" - }); - } - }); - }); - const component = shallow(<ViewLoopTemplatesModal/>); - }); - - it('Test API Exception', () => { - fetch.mockImplementationOnce(() => { - return Promise.resolve({ - ok: false, - status: 500, - json: () => { - return Promise.resolve({ - "index": "1", - "name": "MTCA version 1", - "modelService.serviceDetails.name": "MTCA", - "allowedLoopType" : "CLOSED", - "maximumInstancesAllowed":1, - "updatedDate":"2019-09-06 19:09:42" - }); - } - }); - }); - const component = shallow(<ViewLoopTemplatesModal/>); - }); + it('Test API Successful', () => { + fetch.mockImplementationOnce(() => { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + return Promise.resolve({ + "index": "1", + "name": "MTCA version 1", + "modelService.serviceDetails.name": "MTCA", + "allowedLoopType": "CLOSED", + "maximumInstancesAllowed": 1, + "updatedDate": "2019-09-06 19:09:42" + }); + } + }); + }); + const component = shallow(<ViewLoopTemplatesModal/>); + }); - it('Test API Rejection', () => { - const myMockFunc = fetch.mockImplementationOnce(() => Promise.reject('error')); - setTimeout( () => myMockFunc().catch(e => { - console.info(e); - }), - 100 - ); - const component = shallow(<ViewLoopTemplatesModal/>); - expect(myMockFunc.mock.calls.length).toBe(1); - }); + it('Test API Exception', () => { + fetch.mockImplementationOnce(() => { + return Promise.resolve({ + ok: false, + status: 500, + json: () => { + return Promise.resolve({ + "index": "1", + "name": "MTCA version 1", + "modelService.serviceDetails.name": "MTCA", + "allowedLoopType": "CLOSED", + "maximumInstancesAllowed": 1, + "updatedDate": "2019-09-06 19:09:42" + }); + } + }); + }); + const component = shallow(<ViewLoopTemplatesModal/>); + }); - it('Test the tosca model view render method', () => { - fetch.mockImplementationOnce(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => { - return Promise.resolve({ - "index": "1", - "name": "MTCA version 1", - "modelService.serviceDetails.name": "MTCA", - "allowedLoopType" : "CLOSED", - "maximumInstancesAllowed":1, - "updatedDate":"2019-09-06 19:09:42" - }); - } - }); - }); - const component = shallow(<ViewLoopTemplatesModal/>); - component.setState({ loopTemplateData: { - "index": "1", - "name": "MTCA version 1", - "modelService.serviceDetails.name": "MTCA", - "allowedLoopType" : "CLOSED", - "maximumInstancesAllowed":1, - "updatedDate":"2019-09-06 19:09:42" - } - }); - expect(component).toMatchSnapshot(); - }); + it('Test API Rejection', () => { + const myMockFunc = fetch.mockImplementationOnce(() => Promise.reject('error')); + setTimeout(() => myMockFunc().catch(e => { + console.info(e); + }), + 100 + ); + const component = shallow(<ViewLoopTemplatesModal/>); + expect(myMockFunc.mock.calls.length).toBe(1); + }); - it('Test Table icons', () => { - fetch.mockImplementationOnce(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => { - return Promise.resolve({ - "index": "1", - "name": "MTCA version 1", - "modelService.serviceDetails.name": "MTCA", - "allowedLoopType" : "CLOSED", - "maximumInstancesAllowed":1, - "updatedDate":"2019-09-06 19:09:42" - }); - } - }); - }); - const component = mount(<Router><ViewLoopTemplatesModal/></Router>); - expect(component.find('[className="MuiSelect-icon MuiTablePagination-selectIcon"]')).toBeTruthy(); - }); - - it('Test handleClose', () => { - fetch.mockImplementationOnce(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => { - return Promise.resolve({ - "index": "1", - "name": "MTCA version 1", - "modelService.serviceDetails.name": "MTCA", - "allowedLoopType" : "CLOSED", - "maximumInstancesAllowed":1, - "updatedDate":"2019-09-06 19:09:42" - }); - } - }); - }); - const historyMock = { push: jest.fn() }; - const handleClose = jest.spyOn(ViewLoopTemplatesModal.prototype,'handleClose'); - const component = shallow(<ViewLoopTemplatesModal history={historyMock} />) - component.find('[variant="secondary"]').prop('onClick')(); - expect(handleClose).toHaveBeenCalledTimes(1); - expect(component.state('show')).toEqual(false); - expect(historyMock.push.mock.calls[0]).toEqual([ '/']); - handleClose.mockClear(); - }); - }); + it('Test the tosca model view render method', () => { + fetch.mockImplementationOnce(() => { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + return Promise.resolve({ + "index": "1", + "name": "MTCA version 1", + "modelService.serviceDetails.name": "MTCA", + "allowedLoopType": "CLOSED", + "maximumInstancesAllowed": 1, + "updatedDate": "2019-09-06 19:09:42" + }); + } + }); + }); + const component = shallow(<ViewLoopTemplatesModal/>); + component.setState({ + loopTemplateData: { + "index": "1", + "name": "MTCA version 1", + "modelService.serviceDetails.name": "MTCA", + "allowedLoopType": "CLOSED", + "maximumInstancesAllowed": 1, + "updatedDate": "2019-09-06 19:09:42" + } + }); + expect(component).toMatchSnapshot(); + }); + + it('Test Table icons', () => { + fetch.mockImplementationOnce(() => { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + return Promise.resolve({ + "index": "1", + "name": "MTCA version 1", + "modelService.serviceDetails.name": "MTCA", + "allowedLoopType": "CLOSED", + "maximumInstancesAllowed": 1, + "updatedDate": "2019-09-06 19:09:42" + }); + } + }); + }); + const component = mount(<Router><ViewLoopTemplatesModal/></Router>); + expect(component.find('[className="MuiSelect-icon MuiTablePagination-selectIcon"]')).toBeTruthy(); + }); + + it('Test handleClose', () => { + fetch.mockImplementationOnce(() => { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + return Promise.resolve({ + "index": "1", + "name": "MTCA version 1", + "modelService.serviceDetails.name": "MTCA", + "allowedLoopType": "CLOSED", + "maximumInstancesAllowed": 1, + "updatedDate": "2019-09-06 19:09:42" + }); + } + }); + }); + const historyMock = { push: jest.fn() }; + const handleClose = jest.spyOn(ViewLoopTemplatesModal.prototype, 'handleClose'); + const component = shallow(<ViewLoopTemplatesModal history={ historyMock }/>) + component.find('[variant="secondary"]').prop('onClick')(); + expect(handleClose).toHaveBeenCalledTimes(1); + expect(component.state('show')).toEqual(false); + expect(historyMock.push.mock.calls[0]).toEqual(['/']); + handleClose.mockClear(); + }); +}); diff --git a/runtime/ui-react/src/components/dialogs/UserInfoModal.js b/runtime/ui-react/src/components/dialogs/UserInfoModal.js index 96eabb4c2..d452f6de0 100644 --- a/runtime/ui-react/src/components/dialogs/UserInfoModal.js +++ b/runtime/ui-react/src/components/dialogs/UserInfoModal.js @@ -30,81 +30,86 @@ import styled from 'styled-components'; import UserService from '../../api/UserService'; const ModalStyled = styled(Modal)` - background-color: transparent; + background-color: transparent; ` export default class UserInfoModal extends React.Component { - constructor(props, context) { - super(props, context); + constructor(props, context) { + super(props, context); - this.handleClose = this.handleClose.bind(this); - this.renderPermissions = this.renderPermissions.bind(this); - this.renderUserName = this.renderUserName.bind(this); - this.state = { - show: true, - userInfo: {} - }; - } - componentWillMount() { - UserService.getUserInfo().then(userInfo => { - this.setState({ userInfo: userInfo }) - }); - } + this.handleClose = this.handleClose.bind(this); + this.renderPermissions = this.renderPermissions.bind(this); + this.renderUserName = this.renderUserName.bind(this); + this.state = { + show: true, + userInfo: {} + }; + } - handleClose() { - this.props.history.push('/'); - } - renderPermissions() { - if (this.state.userInfo["allPermissions"]) { - var listOfPermissions = this.state.userInfo["allPermissions"].map(function(perm) { - return <Form.Control key={perm} plaintext readOnly defaultValue={perm} />; - }) - return listOfPermissions; - } else { - return; - } - } - renderUserName() { - if (this.state.userInfo["userName"]) { - return <Form.Control plaintext readOnly defaultValue={this.state.userInfo["userName"]} /> - } else { - return; - } - } - renderVersion() { - if (this.state.userInfo["cldsVersion"]) { - return <Form.Control plaintext readOnly defaultValue={this.state.userInfo["cldsVersion"]} /> - } else { - return; - } - } - render() { - return ( - <ModalStyled size="lg" show={this.state.show} onHide={this.handleClose}> - <Modal.Header closeButton> - <Modal.Title>User Info</Modal.Title> - </Modal.Header> - <Modal.Body> - <Form.Group as={Row} controlId="userName"> - <Form.Label column sm="3">Current User:</Form.Label> - <Col>{this.renderUserName()}</Col> - </Form.Group> - <Form.Group as={Row} controlId="cldsVersion"> - <Form.Label column sm="3">CLDS Version:</Form.Label> - <Col>{this.renderVersion()}</Col> - </Form.Group> - <Form.Group as={Row} controlId="userPermissions"> - <Form.Label column sm="3">User Permissions:</Form.Label> - <Col> - {this.renderPermissions()} - </Col> - </Form.Group> - </Modal.Body> - <Modal.Footer> - <Button variant="secondary" type="null" onClick={this.handleClose}>Cancel</Button> - </Modal.Footer> - </ModalStyled> - ); - } + componentWillMount() { + UserService.getUserInfo().then(userInfo => { + this.setState({ userInfo: userInfo }) + }); + } + + handleClose() { + this.props.history.push('/'); + } + + renderPermissions() { + if (this.state.userInfo["allPermissions"]) { + var listOfPermissions = this.state.userInfo["allPermissions"].map(function (perm) { + return <Form.Control key={ perm } plaintext readOnly defaultValue={ perm }/>; + }) + return listOfPermissions; + } else { + return; + } + } + + renderUserName() { + if (this.state.userInfo["userName"]) { + return <Form.Control plaintext readOnly defaultValue={ this.state.userInfo["userName"] }/> + } else { + return; + } + } + + renderVersion() { + if (this.state.userInfo["cldsVersion"]) { + return <Form.Control plaintext readOnly defaultValue={ this.state.userInfo["cldsVersion"] }/> + } else { + return; + } + } + + render() { + return ( + <ModalStyled size="lg" show={ this.state.show } onHide={ this.handleClose }> + <Modal.Header closeButton> + <Modal.Title>User Info</Modal.Title> + </Modal.Header> + <Modal.Body> + <Form.Group as={ Row } controlId="userName"> + <Form.Label column sm="3">Current User:</Form.Label> + <Col>{ this.renderUserName() }</Col> + </Form.Group> + <Form.Group as={ Row } controlId="cldsVersion"> + <Form.Label column sm="3">CLDS Version:</Form.Label> + <Col>{ this.renderVersion() }</Col> + </Form.Group> + <Form.Group as={ Row } controlId="userPermissions"> + <Form.Label column sm="3">User Permissions:</Form.Label> + <Col> + { this.renderPermissions() } + </Col> + </Form.Group> + </Modal.Body> + <Modal.Footer> + <Button variant="secondary" type="null" onClick={ this.handleClose }>Cancel</Button> + </Modal.Footer> + </ModalStyled> + ); + } } diff --git a/runtime/ui-react/src/components/dialogs/UserInfoModal.test.js b/runtime/ui-react/src/components/dialogs/UserInfoModal.test.js index f5ed0ae10..716879232 100644 --- a/runtime/ui-react/src/components/dialogs/UserInfoModal.test.js +++ b/runtime/ui-react/src/components/dialogs/UserInfoModal.test.js @@ -26,53 +26,59 @@ import UserInfoModal from './UserInfoModal'; describe('Verify UserInfoModal', () => { - beforeEach(() => { - fetch.resetMocks(); - fetch.mockImplementation(() => { - return Promise.resolve({ - ok: true, - status: 200, - json: () => { - return Promise.resolve({ - "userName": "test", - "cldsVersion": "1.0.0" - }); - }}); - }); - }) + beforeEach(() => { + fetch.resetMocks(); + fetch.mockImplementation(() => { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + return Promise.resolve({ + "userName": "test", + "cldsVersion": "1.0.0" + }); + } + }); + }); + }) - it('Test the render method full permission', () => { - const component = shallow(<UserInfoModal />) - component.setState({ userInfo: { - "userName": "test", - "cldsVersion": "1.0.0", - "allPermissions": ["permission1","permission2"] - }}); - expect(component).toMatchSnapshot(); - }); + it('Test the render method full permission', () => { + const component = shallow(<UserInfoModal/>) + component.setState({ + userInfo: { + "userName": "test", + "cldsVersion": "1.0.0", + "allPermissions": ["permission1", "permission2"] + } + }); + expect(component).toMatchSnapshot(); + }); - it('Test the render method no permission', () => { - const component = shallow(<UserInfoModal />) - component.setState({ userInfo: {} - }); + it('Test the render method no permission', () => { + const component = shallow(<UserInfoModal/>) + component.setState({ + userInfo: {} + }); - expect(component.find('FormControl').length).toEqual(0); - }); + expect(component.find('FormControl').length).toEqual(0); + }); - it('Test the render method read permission', () => { - const component = shallow(<UserInfoModal />) - component.setState({ userInfo: { - "userName": "test", - "cldsVersion": "1.0.0", - "allPermissions": ["permission1","permission2"] - }}); + it('Test the render method read permission', () => { + const component = shallow(<UserInfoModal/>) + component.setState({ + userInfo: { + "userName": "test", + "cldsVersion": "1.0.0", + "allPermissions": ["permission1", "permission2"] + } + }); - expect(component.find('FormControl').length).toEqual(4); + expect(component.find('FormControl').length).toEqual(4); - const forms = component.find('FormControl'); - expect(forms.get(0).props.defaultValue).toEqual("test"); - expect(forms.get(1).props.defaultValue).toEqual("1.0.0"); - expect(forms.get(2).props.defaultValue).toEqual("permission1"); - expect(forms.get(3).props.defaultValue).toEqual("permission2"); - }); + const forms = component.find('FormControl'); + expect(forms.get(0).props.defaultValue).toEqual("test"); + expect(forms.get(1).props.defaultValue).toEqual("1.0.0"); + expect(forms.get(2).props.defaultValue).toEqual("permission1"); + expect(forms.get(3).props.defaultValue).toEqual("permission2"); + }); }); diff --git a/runtime/ui-react/src/components/loop_viewer/logs/LoopLogs.js b/runtime/ui-react/src/components/loop_viewer/logs/LoopLogs.js index e3d9f601f..3435ba3bc 100644 --- a/runtime/ui-react/src/components/loop_viewer/logs/LoopLogs.js +++ b/runtime/ui-react/src/components/loop_viewer/logs/LoopLogs.js @@ -26,71 +26,72 @@ import LoopCache from '../../../api/LoopCache'; import styled from 'styled-components'; const LoopLogsHeaderDivStyled = styled.div` - background-color: ${props => props.theme.loopLogsHeaderBackgroundColor}; - padding: 10px 10px; - color: ${props => props.theme.loopLogsHeaderFontColor}; + background-color: ${ props => props.theme.loopLogsHeaderBackgroundColor }; + padding: 10px 10px; + color: ${ props => props.theme.loopLogsHeaderFontColor }; ` const TableStyled = styled(Table)` - - overflow: auto; + + overflow: auto; ` const TableRow = ({ logRow }) => ( - <tr> - <td>{logRow.logInstant}</td> - <td>{logRow.logType}</td> - <td>{logRow.logComponent}</td> - <td>{logRow.message}</td> - </tr> + <tr> + <td>{ logRow.logInstant }</td> + <td>{ logRow.logType }</td> + <td>{ logRow.logComponent }</td> + <td>{ logRow.message }</td> + </tr> ) export default class LoopLogs extends React.Component { - state = { - loopCache: new LoopCache({}) - } - constructor(props) { - super(props); - this.renderLogs = this.renderLogs.bind(this); - this.state.loopCache = props.loopCache; - } + state = { + loopCache: new LoopCache({}) + } + + constructor(props) { + super(props); + this.renderLogs = this.renderLogs.bind(this); + this.state.loopCache = props.loopCache; + } - shouldComponentUpdate(nextProps, nextState) { - return this.state.loopCache !== nextState.loopCache; - } + shouldComponentUpdate(nextProps, nextState) { + return this.state.loopCache !== nextState.loopCache; + } - componentWillReceiveProps(newProps) { - this.setState({ - loopCache: newProps.loopCache - }); - } + componentWillReceiveProps(newProps) { + this.setState({ + loopCache: newProps.loopCache + }); + } - renderLogs() { - let logsArray = this.state.loopCache.getLoopLogsArray(); - if (logsArray != null) { - return (logsArray.map(row => <TableRow key={row.id} logRow={row} />)); - } - } + renderLogs() { + let logsArray = this.state.loopCache.getLoopLogsArray(); + if (logsArray != null) { + return (logsArray.map(row => <TableRow key={ row.id } logRow={ row }/>)); + } + } - render() { - return ( - <LoopLogsHeaderDivStyled> - <label>Loop Logs</label> - <TableStyled striped hover variant responsive> - <thead> - <tr> - <th><span align="left">Date</span></th> - <th><span align="left">Type</span></th> - <th><span align="left">Component</span></th> - <th><span align="right">Log</span></th> - </tr> - </thead> - <tbody> - {this.renderLogs()} - </tbody> - </TableStyled> - </LoopLogsHeaderDivStyled> + render() { + return ( + <LoopLogsHeaderDivStyled> + <label>Loop Logs</label> + <TableStyled striped hover variant responsive> + <thead> + <tr> + <th><span align="left">Date</span></th> + <th><span align="left">Type</span></th> + <th><span align="left">Component</span></th> + <th><span align="right">Log</span></th> + </tr> + </thead> + <tbody> + { this.renderLogs() } + </tbody> + </TableStyled> + </LoopLogsHeaderDivStyled> - ); - } + ); + } } diff --git a/runtime/ui-react/src/components/loop_viewer/logs/LoopLogs.test.js b/runtime/ui-react/src/components/loop_viewer/logs/LoopLogs.test.js index 3b7fd413a..d3a21d80d 100644 --- a/runtime/ui-react/src/components/loop_viewer/logs/LoopLogs.test.js +++ b/runtime/ui-react/src/components/loop_viewer/logs/LoopLogs.test.js @@ -27,44 +27,44 @@ import LoopCache from '../../../api/LoopCache'; describe('Verify LoopLogs', () => { - const loopCache = new LoopCache({ - "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca", - "loopLogs": [ - { - "id": 1, - "logType": "INFO", - "logComponent": "CLAMP", - "message": "Operational policies UPDATED", - "logInstant": "2019-07-08T09:44:37Z" - } - ] - }); + const loopCache = new LoopCache({ + "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca", + "loopLogs": [ + { + "id": 1, + "logType": "INFO", + "logComponent": "CLAMP", + "message": "Operational policies UPDATED", + "logInstant": "2019-07-08T09:44:37Z" + } + ] + }); - it('Test the render method', () => { - const component = shallow(<LoopLogs loopCache={loopCache}/>) - expect(component).toMatchSnapshot(); + it('Test the render method', () => { + const component = shallow(<LoopLogs loopCache={ loopCache }/>) + expect(component).toMatchSnapshot(); - const loopCacheUpdated = new LoopCache({ - "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca", - "loopLogs": [ - { - "id": 1, - "logType": "INFO", - "logComponent": "CLAMP", - "message": "Operational policies UPDATED", - "logInstant": "2019-07-08T09:44:37Z" - }, - { - "id": 2, - "logType": "INFO", - "logComponent": "CLAMP", - "message": "Operational policies UPDATED", - "logInstant": "2019-07-08T09:44:50Z" - } - ] - }); + const loopCacheUpdated = new LoopCache({ + "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca", + "loopLogs": [ + { + "id": 1, + "logType": "INFO", + "logComponent": "CLAMP", + "message": "Operational policies UPDATED", + "logInstant": "2019-07-08T09:44:37Z" + }, + { + "id": 2, + "logType": "INFO", + "logComponent": "CLAMP", + "message": "Operational policies UPDATED", + "logInstant": "2019-07-08T09:44:50Z" + } + ] + }); - component.setProps({ loopCache: loopCacheUpdated }); - expect(component.find('TableRow').length).toEqual(2); - }); -});
\ No newline at end of file + component.setProps({ loopCache: loopCacheUpdated }); + expect(component.find('TableRow').length).toEqual(2); + }); +}); diff --git a/runtime/ui-react/src/components/loop_viewer/status/LoopStatus.js b/runtime/ui-react/src/components/loop_viewer/status/LoopStatus.js index 4b35b48e1..f539ad436 100644 --- a/runtime/ui-react/src/components/loop_viewer/status/LoopStatus.js +++ b/runtime/ui-react/src/components/loop_viewer/status/LoopStatus.js @@ -26,81 +26,85 @@ import styled from 'styled-components'; import LoopCache from '../../../api/LoopCache'; const LoopStatusViewDivStyled = styled.div` - background-color: ${props => props.theme.loopViewerHeaderBackgroundColor}; - padding: 10px 10px; - color: ${props => props.theme.loopViewerHeaderFontColor}; + background-color: ${ props => props.theme.loopViewerHeaderBackgroundColor }; + padding: 10px 10px; + color: ${ props => props.theme.loopViewerHeaderFontColor }; ` const TableStyled = styled(Table)` - overflow: auto; + overflow: auto; ` const TableRow = ({ statusRow }) => ( - <tr> - <td>{statusRow.componentName}</td> - <td>{statusRow.stateName}</td> - <td>{statusRow.description}</td> - </tr> + <tr> + <td>{ statusRow.componentName }</td> + <td>{ statusRow.stateName }</td> + <td>{ statusRow.description }</td> + </tr> ) export default class LoopStatus extends React.Component { - state = { - loopCache: new LoopCache({}) - } + state = { + loopCache: new LoopCache({}) + } - constructor(props) { - super(props); - this.renderStatus = this.renderStatus.bind(this); - this.state.loopCache = props.loopCache; - } + constructor(props) { + super(props); + this.renderStatus = this.renderStatus.bind(this); + this.state.loopCache = props.loopCache; + } - renderStatus() { - let componentStates = this.state.loopCache.getComponentStates(); - if (componentStates != null) { - return Object.keys(componentStates).map((key) => { - console.debug("Adding status for: ",key); - var res={} - res[key]=this.state.loopCache.getComponentStates()[key]; - return (<TableRow key={key} statusRow={{'componentName':key,'stateName':this.state.loopCache.getComponentStates()[key].componentState.stateName,'description':this.state.loopCache.getComponentStates()[key].componentState.description}} />) - }) + renderStatus() { + let componentStates = this.state.loopCache.getComponentStates(); + if (componentStates != null) { + return Object.keys(componentStates).map((key) => { + console.debug("Adding status for: ", key); + var res = {} + res[key] = this.state.loopCache.getComponentStates()[key]; + return (<TableRow key={ key } statusRow={ { + 'componentName': key, + 'stateName': this.state.loopCache.getComponentStates()[key].componentState.stateName, + 'description': this.state.loopCache.getComponentStates()[key].componentState.description + } }/>) + }) - } - } + } + } - shouldComponentUpdate(nextProps, nextState) { - return this.state.loopCache !== nextState.loopCache; - } + shouldComponentUpdate(nextProps, nextState) { + return this.state.loopCache !== nextState.loopCache; + } - componentWillReceiveProps(newProps) { - this.setState({ - loopCache: newProps.loopCache - }); - } + componentWillReceiveProps(newProps) { + this.setState({ + loopCache: newProps.loopCache + }); + } - render() { - return ( - <LoopStatusViewDivStyled> - <label>Loop Status: {this.state.loopCache.getComputedState()} - </label> + render() { + return ( + <LoopStatusViewDivStyled> + <label>Loop Status: { this.state.loopCache.getComputedState() } + </label> - <div > - <TableStyled striped hover variant responsive> - <thead> - <tr> - <th><span align="left">Component Name</span></th> - <th><span align="left">Component State</span></th> - <th><span align="right">Description</span></th> - </tr> - </thead> - <tbody> - {this.renderStatus()} - </tbody> - </TableStyled> - </div> - </LoopStatusViewDivStyled> - ); - } + <div> + <TableStyled striped hover variant responsive> + <thead> + <tr> + <th><span align="left">Component Name</span></th> + <th><span align="left">Component State</span></th> + <th><span align="right">Description</span></th> + </tr> + </thead> + <tbody> + { this.renderStatus() } + </tbody> + </TableStyled> + </div> + </LoopStatusViewDivStyled> + ); + } } diff --git a/runtime/ui-react/src/components/loop_viewer/status/LoopStatus.test.js b/runtime/ui-react/src/components/loop_viewer/status/LoopStatus.test.js index 8d0448796..b84067e18 100644 --- a/runtime/ui-react/src/components/loop_viewer/status/LoopStatus.test.js +++ b/runtime/ui-react/src/components/loop_viewer/status/LoopStatus.test.js @@ -27,52 +27,52 @@ import LoopCache from '../../../api/LoopCache'; describe('Verify LoopStatus', () => { - const loopCache = new LoopCache({ - "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca", - "lastComputedState": "DESIGN", - "components": { - "POLICY": { - "componentState": { - "stateName": "NOT_SENT", - "description": "The policies defined have NOT yet been created on the policy engine" - } - }, - "DCAE": { - "componentState": { - "stateName": "BLUEPRINT_DEPLOYED", - "description": "The DCAE blueprint has been found in the DCAE inventory but not yet instancianted for this loop" - } - } - } - }); + const loopCache = new LoopCache({ + "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca", + "lastComputedState": "DESIGN", + "components": { + "POLICY": { + "componentState": { + "stateName": "NOT_SENT", + "description": "The policies defined have NOT yet been created on the policy engine" + } + }, + "DCAE": { + "componentState": { + "stateName": "BLUEPRINT_DEPLOYED", + "description": "The DCAE blueprint has been found in the DCAE inventory but not yet instancianted for this loop" + } + } + } + }); - it('Test the render method', () => { - const component = shallow(<LoopStatus loopCache={loopCache}/>) + it('Test the render method', () => { + const component = shallow(<LoopStatus loopCache={ loopCache }/>) - expect(component).toMatchSnapshot(); - - const loopCacheUpdated = new LoopCache({ - "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca", - "lastComputedState": "SUBMIT", - "components": { - "POLICY": { - "componentState": { - "stateName": "SENT", - "description": "The policies defined have NOT yet been created on the policy engine" - } - }, - "DCAE": { - "componentState": { - "stateName": "BLUEPRINT_DEPLOYED", - "description": "The DCAE blueprint has been found in the DCAE inventory but not yet instancianted for this loop" - } - } - } - }); - component.setProps({ loopCache: loopCacheUpdated }); + expect(component).toMatchSnapshot(); - const forms = component.find('TableRow'); - expect(forms.get(0).props.statusRow.stateName).toEqual("SENT"); - expect(component.find('label').text()).toContain('SUBMIT'); - }); -});
\ No newline at end of file + const loopCacheUpdated = new LoopCache({ + "name": "LOOP_Jbv1z_v1_0_ResourceInstanceName1_tca", + "lastComputedState": "SUBMIT", + "components": { + "POLICY": { + "componentState": { + "stateName": "SENT", + "description": "The policies defined have NOT yet been created on the policy engine" + } + }, + "DCAE": { + "componentState": { + "stateName": "BLUEPRINT_DEPLOYED", + "description": "The DCAE blueprint has been found in the DCAE inventory but not yet instancianted for this loop" + } + } + } + }); + component.setProps({ loopCache: loopCacheUpdated }); + + const forms = component.find('TableRow'); + expect(forms.get(0).props.statusRow.stateName).toEqual("SENT"); + expect(component.find('label').text()).toContain('SUBMIT'); + }); +}); diff --git a/runtime/ui-react/src/components/menu/MenuBar.test.js b/runtime/ui-react/src/components/menu/MenuBar.test.js index 3e96dbf38..81117bb90 100644 --- a/runtime/ui-react/src/components/menu/MenuBar.test.js +++ b/runtime/ui-react/src/components/menu/MenuBar.test.js @@ -26,21 +26,21 @@ import MenuBar from './MenuBar'; describe('Verify MenuBar', () => { - it('Test the render method', () => { - const component = shallow(<MenuBar />) + it('Test the render method', () => { + const component = shallow(<MenuBar/>) - expect(component).toMatchSnapshot(); - }); + expect(component).toMatchSnapshot(); + }); - it('Update loopName', () => { - const component = shallow(<MenuBar />) - component.setProps({ loopName: "newLoop" }); - expect(component.state('disabled')).toBe(false); - }); + it('Update loopName', () => { + const component = shallow(<MenuBar/>) + component.setProps({ loopName: "newLoop" }); + expect(component.state('disabled')).toBe(false); + }); - it('Default loopName', () => { - const component = shallow(<MenuBar />) - component.setProps({ loopName: "Empty (NO loop loaded yet)" }); - expect(component.state('disabled')).toBe(true); - }); + it('Default loopName', () => { + const component = shallow(<MenuBar/>) + component.setProps({ loopName: "Empty (NO loop loaded yet)" }); + expect(component.state('disabled')).toBe(true); + }); }); |