From: drveerendra Date: Thu, 5 Mar 2020 01:30:44 +0000 (-0500) Subject: Adding manage dictionary UI feature X-Git-Tag: 5.0.0~27^2 X-Git-Url: https://gerrit.onap.org/r/gitweb?p=clamp.git;a=commitdiff_plain;h=5032095d221292ad2909f0cb9c9c99d3d5111d0c Adding manage dictionary UI feature Adding manage dictionaries.js, its test file and respective changes in loopui, menu js files Issue-ID: CLAMP-589 Change-Id: Ib0440a7a966f3736682d2964e3329e08c91578d3 Signed-off-by: drveerendra --- diff --git a/ui-react/src/LoopUI.js b/ui-react/src/LoopUI.js index 471e8720..bc3f2355 100644 --- a/ui-react/src/LoopUI.js +++ b/ui-react/src/LoopUI.js @@ -49,6 +49,7 @@ import LoopService from './api/LoopService'; import UploadToscaPolicyModal from './components/dialogs/Tosca/UploadToscaPolicyModal'; import ViewToscaPolicyModal from './components/dialogs/Tosca/ViewToscaPolicyModal'; import ViewLoopTemplatesModal from './components/dialogs/Tosca/ViewLoopTemplatesModal'; +import ManageDictionaries from './components/dialogs/ManageDictionaries/ManageDictionaries'; import PerformAction from './components/dialogs/PerformActions'; import RefreshStatus from './components/dialogs/RefreshStatus'; import DeployLoopModal from './components/dialogs/Loop/DeployLoopModal'; @@ -255,6 +256,7 @@ export default class LoopUI extends React.Component { ()} /> ()} /> ()} /> + ()} /> ()} /> ()} /> diff --git a/ui-react/src/__snapshots__/LoopUI.test.js.snap b/ui-react/src/__snapshots__/LoopUI.test.js.snap index 7d2c4467..9de232dd 100644 --- a/ui-react/src/__snapshots__/LoopUI.test.js.snap +++ b/ui-react/src/__snapshots__/LoopUI.test.js.snap @@ -16,6 +16,10 @@ exports[`Verify LoopUI Test the render method 1`] = ` path="/ViewLoopTemplatesModal" render={[Function]} /> + + { + var options = e.target.options; + var SelectedDictTypes = ''; + for (var 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); + } + return( +
+ +
+ ) +} + +function SubDict(props) { + const {onChange} = props; + const subDicts = []; + subDicts.push('Default'); + for(var item in dictList) { + if(dictList[item].secondLevelDictionary === 1) { + subDicts.push(dictList[item].name); + } + }; + subDicts.push(''); + var optionItems = subDicts.map( + (item) => + ); + function selectedValue (e) { + onChange(e.target.value); + } + return( + + ) +} + +export default class ManageDictionaries extends React.Component { + constructor(props, context) { + super(props, context); + this.handleClose = this.handleClose.bind(this); + this.getDictionary = this.getDictionary.bind(this); + this.getDictionaryElements = this.getDictionaryElements.bind(this); + this.clickHandler = this.clickHandler.bind(this); + this.addDictionary = this.addDictionary.bind(this); + this.deleteDictionary = this.deleteDictionary.bind(this); + this.fileSelectedHandler = this.fileSelectedHandler.bind(this); + this.state = { + show: true, + selectedFile: '', + dictNameFlag: false, + exportFilename: '', + content: null, + newDict: '', + newDictItem: '', + delDictItem: '', + addDict: false, + delData: '', + delDict: false, + validImport: false, + dictionaryNames: [], + dictionaryElements: [], + tableIcons: { + Add: forwardRef((props, ref) => ), + Check: forwardRef((props, ref) => ), + Clear: forwardRef((props, ref) => ), + Delete: forwardRef((props, ref) => ), + DetailPanel: forwardRef((props, ref) => ), + Edit: forwardRef((props, ref) => ), + Export: forwardRef((props, ref) => ), + Filter: forwardRef((props, ref) => ), + FirstPage: forwardRef((props, ref) => ), + LastPage: forwardRef((props, ref) => ), + NextPage: forwardRef((props, ref) => ), + PreviousPage: forwardRef((props, ref) => ), + ResetSearch: forwardRef((props, ref) => ), + Search: forwardRef((props, ref) => ), + SortArrow: forwardRef((props, ref) => ), + ThirdStateCheck: forwardRef((props, ref) => ), + ViewColumn: forwardRef((props, 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 => ( +
+ +
+ ), + cellStyle: cellStyle, + headerStyle: headerStyle + }, + { + title: "Sub-Dictionary", field: "subDictionary", + editComponent: props => ( +
+ +
+ ), + 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 + } + ] + } + } + + componentWillMount() { + this.getDictionary(); + } + + getDictionary() { + TemplateMenuService.getDictionary().then(dictionaryNames => { + this.setState({ dictionaryNames: dictionaryNames }) + }); + var dictNamesingetDict = this.state.dictionaryNames; + } + + getDictionaryElements(dictionaryName) { + TemplateMenuService.getDictionaryElements(dictionaryName).then(dictionaryElements => { + dictList = this.state.dictionaryNames; + this.setState({ dictionaryElements: dictionaryElements.dictionaryElements}); + }); + } + + clickHandler(rowData) { + this.setState({ + dictNameFlag: false, + addDict: false, + }); + } + + handleClose() { + this.setState({ show: false }); + this.props.history.push('/'); + } + + addDictionary() { + var modifiedData = []; + if(this.state.newDict !== '') { + modifiedData = this.state.newDict; + } else { + modifiedData = {"name": this.state.dictionaryName, 'dictionaryElements': this.state.newDictItem}; + } + if(this.state.newDictItem === '') { + TemplateMenuService.insDictionary(modifiedData).then(resp => { + }); + } else { + TemplateMenuService.insDictionaryElements(modifiedData).then(resp => { + }); + } + } + + deleteDictionary() { + var modifiedData = []; + if(this.state.delData !== '') { + modifiedData = this.state.delData.name; + } else { + modifiedData = {"name": this.state.dictionaryName, "shortName": this.state.delDictItem.shortName}; + } + if(this.state.delDictItem === '') { + TemplateMenuService.deleteDictionary(modifiedData).then(resp => { + }); + } else { + TemplateMenuService.deleteDictionaryElements(modifiedData).then(resp => { + }); + } + } + + fileSelectedHandler = (event) => { + const text = this; + var dictionaryElements = []; + if (event.target.files[0].type === 'text/csv' ) { + if (event.target.files && event.target.files[0]) { + let reader = new FileReader(); + reader.onload = function(e) { + var dictElems = reader.result.split('\n'); + var jsonObj = []; + var headers = dictElems[0].split(','); + for(var i = 0; i < dictElems.length; i++) { + var data = dictElems[i].split(','); + var obj = {}; + for(var j = 0; j < data.length; j++) { + obj[headers[j].trim()] = data[j].trim(); + } + jsonObj.push(obj); + } + JSON.stringify(jsonObj); + const dictKeys = ['Element Short Name','Element Name','Element Description','Element Type','Sub-Dictionary']; + const mandatoryKeys = [ 'Element Short Name', 'Element Name', 'Element Type' ]; + const validTypes = ['string','number','datetime','json','map']; + if (!dictElems){ + + text.setState({validData: false}); + } else if (headers.length !== dictKeys.length){ + text.setState({validImport: false}); + } else { + var subDictionaries = []; + for(var item in dictList) { + if(dictList[item].secondLevelDictionary === 1) { + subDictionaries.push(dictList[item].name); + } + }; + subDictionaries = subDictionaries.toString(); + var row = 0; + for (var dictElem of jsonObj){ + ++row; + for (var itemKey in dictElem){ + var value = dictElem[itemKey].trim(); + if (dictKeys.indexOf(itemKey) < 0){ + var errorMessage = 'unknown field name of, ' + itemKey + ', found in CSV header'; + text.setState({validImport: false}); + alert(errorMessage); + break; + } else if (value === "" && mandatoryKeys.indexOf(itemKey) >= 0){ + errorMessage = 'value for ' + itemKey + ', at row #, ' + row + ', is empty but required'; + text.setState({validImport: false}); + alert(errorMessage); + break; + } else if (itemKey === 'Element Type' && validTypes.indexOf(value) < 0 && row > 1) { + errorMessage = 'invalid dictElemenType of ' + value + ' at row #' + row; + text.setState({validImport: false}); + alert(errorMessage); + break; + } else if (value !== "" && itemKey === 'Sub-Dictionary' && subDictionaries.indexOf(value) < 0 && row > 1) { + errorMessage = 'invalid subDictionary of ' + value + ' at row #' + row; + text.setState({validImport: false}); + alert(errorMessage); + } + } + } + } + const headerKeys = ['shortName','name','description','type','subDictionary']; + + for(i = 1; i < dictElems.length; i++) { + data = dictElems[i].split(','); + obj = {}; + for(j = 0; j < data.length; j++) { + obj[headerKeys[j].trim()] = data[j].trim(); + } + dictionaryElements.push(obj); + } + text.setState({newDictItem: dictionaryElements, addDict: true}); + } + reader.readAsText(event.target.files[0]); + } + this.setState({selectedFile: event.target.files[0]}) + } else { + text.setState({validImport: false}); + alert('Please upload .csv extention files only.'); + } + + } + + render() { + return ( + + + Manage Dictionaries + + + {!this.state.dictNameFlag? {this.getDictionaryElements(rowData.name);this.setState({dictNameFlag: true, exportFilename: rowData.name, dictionaryName: rowData.name})}} + options={{ + headerStyle: rowHeaderStyle, + }} + editable={{ + onRowAdd: newData => + new Promise((resolve, reject) => { + setTimeout(() => { + { + const dictionaryNames = this.state.dictionaryNames; + var validData = true; + if(/[^a-zA-Z0-9-_.]/.test(newData.name)) { + validData = false; + alert('Please enter alphanumberic input. Only allowed special characters are:(period, hyphen, underscore)'); + } + for (var i = 0; i < this.state.dictionaryNames.length; i++) { + if (this.state.dictionaryNames[i].name === newData.name) { + validData = false; + alert(newData.name + ' dictionary name already exists') + } + } + if(validData){ + dictionaryNames.push(newData); + this.setState({ dictionaryNames }, () => resolve()); + this.setState({addDict: true, newDict: newData}); + } + } + resolve(); + }, 1000); + }), + onRowUpdate: (newData, oldData) => + new Promise((resolve, reject) => { + setTimeout(() => { + { + const dictionaryNames = this.state.dictionaryNames; + var validData = true; + if(/[^a-zA-Z0-9-_.]/.test(newData.name)) { + validData = false; + alert('Please enter alphanumberic input. Only allowed special characters are:(period, hyphen, underscore)'); + } + if(validData){ + const index = dictionaryNames.indexOf(oldData); + dictionaryNames[index] = newData; + this.setState({ dictionaryNames }, () => resolve()); + this.setState({addDict: true, newDict: newData}); + } + } + resolve(); + }, 1000); + }), + onRowDelete: oldData => + new Promise((resolve, reject) => { + setTimeout(() => { + { + let data = this.state.dictionaryNames; + const index = data.indexOf(oldData); + data.splice(index, 1); + this.setState({ data }, () => resolve()); + this.setState({delDict: true, delData: oldData}) + } + resolve() + }, 1000) + }) + }} + />:"" + } + {this.state.dictNameFlag? ( +
+ +
+ + + this.fileUpload.click()}> + + + + +
+ {this.fileUpload = fileUpload;}} style={{ visibility: 'hidden'}} onChange={this.fileSelectedHandler} /> +
+ ) + }} + editable={{ + onRowAdd: newData => + new Promise((resolve, reject) => { + setTimeout(() => { + { + const dictionaryElements = this.state.dictionaryElements; + var validData = true; + for (var i = 0; i < this.state.dictionaryElements.length; i++) { + if (this.state.dictionaryElements[i].shortName === newData.shortName) { + validData = false; + alert(newData.shortname + 'short name already exists') + } + } + if(/[^a-zA-Z0-9-_.]/.test(newData.shortName)) { + validData = false; + alert('Please enter alphanumberic input. Only allowed special characters are:(period, hyphen, underscore)'); + } + if(!newData.type){ + validData = false; + alert('Element Type cannot be null'); + } + if(validData){ + dictionaryElements.push(newData); + this.setState({ dictionaryElements }, () => resolve()); + this.setState({addDict: true, newDictItem: [newData]}); + } + } + resolve(); + }, 1000); + }), + onRowUpdate: (newData, oldData) => + new Promise((resolve, reject) => { + setTimeout(() => { + { + const dictionaryElements = this.state.dictionaryElements; + var validData = true; + if(!newData.type){ + validData = false; + alert('Element Type cannot be null'); + } + if(validData){ + const index = dictionaryElements.indexOf(oldData); + dictionaryElements[index] = newData; + this.setState({ dictionaryElements }, () => resolve()); + this.setState({addDict: true, newDictItem: [newData]}); + } + } + resolve(); + }, 1000); + }), + onRowDelete: oldData => + new Promise((resolve, reject) => { + setTimeout(() => { + { + let data = this.state.dictionaryElements; + const index = data.indexOf(oldData); + data.splice(index, 1); + this.setState({ data }, () => resolve()); + this.setState({delDict: true, delDictItem: oldData}) + } + resolve() + }, 1000) + }) + }} + />:"" + } + {this.state.dictNameFlag?:""} + {this.state.addDict && this.addDictionary()} + {this.state.delDict && this.deleteDictionary()} +
+ + + +
+ ); + } +} diff --git a/ui-react/src/components/dialogs/ManageDictionaries/ManageDictionaries.test.js b/ui-react/src/components/dialogs/ManageDictionaries/ManageDictionaries.test.js new file mode 100644 index 00000000..4363da92 --- /dev/null +++ b/ui-react/src/components/dialogs/ManageDictionaries/ManageDictionaries.test.js @@ -0,0 +1,202 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ +import React from 'react'; +import { shallow } from 'enzyme'; +import { mount } from 'enzyme'; +import { render } from 'enzyme'; +import ManageDictionaries from './ManageDictionaries'; +import TemplateMenuService from '../../../api/TemplateService' + +describe('Verify ManageDictionaries', () => { + 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(); + 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(); + }); + + it('Test API Rejection', () => { + const myMockFunc = fetch.mockImplementationOnce(() => Promise.reject('error')); + setTimeout( () => myMockFunc().catch(e => { + console.log(e); + }), + 100 + ); + new Promise(resolve => setTimeout(resolve, 200)); + const component = shallow(); + expect(myMockFunc.mock.calls.length).toBe(1); + }); + + it('Test Table icons', () => { + 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 = mount(); + expect(component.find('[className="MuiSelect-icon MuiTablePagination-selectIcon"]')).toBeTruthy(); + }); + + test('Test get dictionaryNames/dictionaryElements, add/delete dictionary functions', async () => { + const historyMock = { push: jest.fn() }; + TemplateMenuService.getDictionary = jest.fn().mockImplementation(() => { + return Promise.resolve("test"); + }); + TemplateMenuService.getDictionaryElements = jest.fn().mockImplementation(() => { + return Promise.resolve({dictionaryElements:"testitem"}); + }); + TemplateMenuService.insDictionary = jest.fn().mockImplementation(() => { + return Promise.resolve(200); + }); + TemplateMenuService.deleteDictionary = jest.fn().mockImplementation(() => { + return Promise.resolve(200); + }); + const flushPromises = () => new Promise(setImmediate); + const component = shallow() + component.setState({ newDict: { + "name": "test", + "secondLevelDictionary": "0", + "subDictionaryType": "string" + } + }); + component.setState({ delData: { + "name": "test", + "secondLevelDictionary": "0", + "subDictionaryType": "string" + } + }); + const instance = component.instance(); + instance.getDictionaryElements("test"); + instance.clickHandler(); + instance.addDictionary(); + instance.deleteDictionary(); + await flushPromises(); + expect(component.state('dictionaryNames')).toEqual("test"); + expect(component.state('dictionaryElements')).toEqual("testitem"); + expect(component.state('dictNameFlag')).toEqual(false); + }); + + test('Test adding and deleting dictionaryelements', async () => { + const historyMock = { push: jest.fn() }; + TemplateMenuService.getDictionary = jest.fn().mockImplementation(() => { + return Promise.resolve("test"); + }); + TemplateMenuService.insDictionaryElements = jest.fn().mockImplementation(() => { + return Promise.resolve(200); + }); + TemplateMenuService.deleteDictionaryElements = jest.fn().mockImplementation(() => { + return Promise.resolve(200); + }); + const flushPromises = () => new Promise(setImmediate); + const component = shallow() + component.setState({ newDictItem: { + "name": "test", + "dictionaryElements" : { + "shortName": "shorttest", + } + }}); + component.setState({ delDictItem: { + "name": "test", + "dictionaryElements" : { + "shortName": "shortTest", + } + }}); + const instance = component.instance(); + instance.addDictionary(); + instance.deleteDictionary(); + await flushPromises(); + expect(component.state('dictionaryNames')).toEqual("test"); + }); + + 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 historyMock = { push: jest.fn() }; + const handleClose = jest.spyOn(ManageDictionaries.prototype,'handleClose'); + const component = shallow() + 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/ui-react/src/components/dialogs/ManageDictionaries/__snapshots__/ManageDictionaries.test.js.snap b/ui-react/src/components/dialogs/ManageDictionaries/__snapshots__/ManageDictionaries.test.js.snap new file mode 100644 index 00000000..e7829221 --- /dev/null +++ b/ui-react/src/components/dialogs/ManageDictionaries/__snapshots__/ManageDictionaries.test.js.snap @@ -0,0 +1,195 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Verify ManageDictionaries Test API Successful 1`] = ` + + + + Manage Dictionaries + + + + + + + + + +`; diff --git a/ui-react/src/components/menu/MenuBar.js b/ui-react/src/components/menu/MenuBar.js index 92380ab6..4eafaa44 100644 --- a/ui-react/src/components/menu/MenuBar.js +++ b/ui-react/src/components/menu/MenuBar.js @@ -93,6 +93,9 @@ export default class MenuBar extends React.Component { Upload Tosca Model View Tosca Models + + + Manage Dictionaries Create diff --git a/ui-react/src/components/menu/__snapshots__/MenuBar.test.js.snap b/ui-react/src/components/menu/__snapshots__/MenuBar.test.js.snap index dfc6a568..9070e87e 100644 --- a/ui-react/src/components/menu/__snapshots__/MenuBar.test.js.snap +++ b/ui-react/src/components/menu/__snapshots__/MenuBar.test.js.snap @@ -163,6 +163,61 @@ exports[`Verify MenuBar Test the render method 1`] = ` View Tosca Models + + + Manage Dictionaries + +