2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END============================================
19 * ===================================================================
24 import React, { forwardRef } from 'react';
25 import Button from 'react-bootstrap/Button';
26 import Modal from 'react-bootstrap/Modal';
27 import styled from 'styled-components';
28 import TemplateMenuService from '../../../api/TemplateService';
29 import MaterialTable, {MTableToolbar} from "material-table";
30 import IconButton from '@material-ui/core/IconButton';
31 import Tooltip from '@material-ui/core/Tooltip';
32 import Grid from '@material-ui/core/Grid';
33 import AddBox from '@material-ui/icons/AddBox';
34 import ArrowUpward from '@material-ui/icons/ArrowUpward';
35 import Check from '@material-ui/icons/Check';
36 import ChevronLeft from '@material-ui/icons/ChevronLeft';
37 import VerticalAlignTopIcon from '@material-ui/icons/VerticalAlignTop';
38 import VerticalAlignBottomIcon from '@material-ui/icons/VerticalAlignBottom';
39 import ChevronRight from '@material-ui/icons/ChevronRight';
40 import Clear from '@material-ui/icons/Clear';
41 import DeleteOutline from '@material-ui/icons/DeleteOutline';
42 import Edit from '@material-ui/icons/Edit';
43 import FilterList from '@material-ui/icons/FilterList';
44 import FirstPage from '@material-ui/icons/FirstPage';
45 import LastPage from '@material-ui/icons/LastPage';
46 import Remove from '@material-ui/icons/Remove';
47 import Search from '@material-ui/icons/Search';
48 import ViewColumn from '@material-ui/icons/ViewColumn';
51 const ModalStyled = styled(Modal)`
52 background-color: transparent;
54 const cellStyle = { border: '1px solid black' };
55 const headerStyle = { backgroundColor: '#ddd', border: '2px solid black' };
56 const rowHeaderStyle = {backgroundColor:'#ddd', fontSize: '15pt', text: 'bold', border: '1px solid black'};
59 function SelectSubDictType(props) {
60 const {onChange} = props;
61 const selectedValues = (e) => {
62 var options = e.target.options;
63 var SelectedDictTypes = '';
64 for (var dictType = 0, values = options.length; dictType < values; dictType++) {
65 if (options[dictType].selected) {
66 SelectedDictTypes = SelectedDictTypes.concat(options[dictType].value);
67 SelectedDictTypes = SelectedDictTypes.concat('|');
70 SelectedDictTypes = SelectedDictTypes.slice(0,-1);
71 onChange(SelectedDictTypes);
75 <select multiple={true} onChange={selectedValues}>
76 <option value="string">string</option>
77 <option value="number">number</option>
78 <option value="datetime">datetime</option>
79 <option value="map">map</option>
80 <option value="json">json</option>
86 function SubDict(props) {
87 const {onChange} = props;
89 subDicts.push('Default');
90 if (dictList != "undefined" && dictList.length > 0) {
91 for(var item in dictList) {
92 if(dictList[item].secondLevelDictionary === 1) {
93 subDicts.push(dictList[item].name);
98 var optionItems = subDicts.map(
99 (item) => <option key={item}>{item}</option>
101 function selectedValue (e) {
102 onChange(e.target.value);
105 <select onChange={selectedValue} >
111 export default class ManageDictionaries extends React.Component {
112 constructor(props, context) {
113 super(props, context);
114 this.handleClose = this.handleClose.bind(this);
115 this.getDictionary = this.getDictionary.bind(this);
116 this.getDictionaryElements = this.getDictionaryElements.bind(this);
117 this.clickHandler = this.clickHandler.bind(this);
118 this.addDictionary = this.addDictionary.bind(this);
119 this.deleteDictionary = this.deleteDictionary.bind(this);
120 this.fileSelectedHandler = this.fileSelectedHandler.bind(this);
135 dictionaryElements: [],
137 Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
138 Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
139 Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
140 Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
141 DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
142 Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
143 Export: forwardRef((props, ref) => <VerticalAlignBottomIcon {...props} ref={ref} />),
144 Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
145 FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
146 LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
147 NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
148 PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />),
149 ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
150 Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
151 SortArrow: forwardRef((props, ref) => <ArrowUpward {...props} ref={ref} />),
152 ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
153 ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />)
157 title: "Dictionary Name", field: "name",editable: 'onAdd',
158 cellStyle: cellStyle,
159 headerStyle: headerStyle
162 title: "Sub Dictionary ?", field: "secondLevelDictionary", lookup: {0: 'No', 1: 'Yes'},
163 cellStyle: cellStyle,
164 headerStyle: headerStyle
167 title: "Dictionary Type", field: "subDictionaryType",lookup: {string: 'string', number: 'number'},
168 cellStyle: cellStyle,
169 headerStyle: headerStyle
172 title: "Updated By", field: "updatedBy", editable: 'never',
173 cellStyle: cellStyle,
174 headerStyle: headerStyle
177 title: "Last Updated Date", field: "updatedDate", editable: 'never',
178 cellStyle: cellStyle,
179 headerStyle: headerStyle
182 dictElementColumns: [
184 title: "Element Short Name", field: "shortName",editable: 'onAdd',
185 cellStyle: cellStyle,
186 headerStyle: headerStyle
189 title: "Element Name", field: "name",
190 cellStyle: cellStyle,
191 headerStyle: headerStyle
194 title: "Element Description", field: "description",
195 cellStyle: cellStyle,
196 headerStyle: headerStyle
199 title: "Element Type", field: "type",
200 editComponent: props => (
202 <SelectSubDictType value={props.value} onChange={props.onChange} />
205 cellStyle: cellStyle,
206 headerStyle: headerStyle
209 title: "Sub-Dictionary", field: "subDictionary",
210 editComponent: props => (
212 <SubDict value={props.value} onChange={props.onChange} />
215 cellStyle: cellStyle,
216 headerStyle: headerStyle
219 title: "Updated By", field: "updatedBy", editable: 'never',
220 cellStyle: cellStyle,
221 headerStyle: headerStyle
224 title: "Updated Date", field: "updatedDate", editable: 'never',
225 cellStyle: cellStyle,
226 headerStyle: headerStyle
232 componentWillMount() {
233 this.getDictionary();
237 TemplateMenuService.getDictionary().then(dictionaryNames => {
238 this.setState({ dictionaryNames: dictionaryNames })
242 getDictionaryElements(dictionaryName) {
243 TemplateMenuService.getDictionaryElements(dictionaryName).then(dictionaryElements => {
244 dictList = this.state.dictionaryNames;
245 this.setState({ dictionaryElements: dictionaryElements.dictionaryElements});
249 clickHandler(rowData) {
257 this.setState({ show: false });
258 this.props.history.push('/');
262 var modifiedData = [];
263 if(this.state.newDict !== '') {
264 modifiedData = this.state.newDict;
266 modifiedData = {"name": this.state.dictionaryName, 'dictionaryElements': this.state.newDictItem};
268 if(this.state.newDictItem === '') {
269 TemplateMenuService.insDictionary(modifiedData).then(resp => {
272 TemplateMenuService.insDictionaryElements(modifiedData).then(resp => {
278 var modifiedData = [];
279 if(this.state.delData !== '') {
280 modifiedData = this.state.delData.name;
282 modifiedData = {"name": this.state.dictionaryName, "shortName": this.state.delDictItem.shortName};
284 if(this.state.delDictItem === '') {
285 TemplateMenuService.deleteDictionary(modifiedData).then(resp => {
288 TemplateMenuService.deleteDictionaryElements(modifiedData).then(resp => {
293 fileSelectedHandler = (event) => {
295 var dictionaryElements = [];
296 if (event.target.files[0].type === 'text/csv' ) {
297 if (event.target.files && event.target.files[0]) {
298 const reader = new FileReader();
299 reader.onload = function(e) {
300 var dictElems = reader.result.split('\n');
302 var headers = dictElems[0].split(',');
303 for(var i = 0; i < dictElems.length; i++) {
304 var data = dictElems[i].split(',');
306 for(var j = 0; j < data.length; j++) {
307 obj[headers[j].trim()] = data[j].trim();
311 JSON.stringify(jsonObj);
312 const dictKeys = ['Element Short Name','Element Name','Element Description','Element Type','Sub-Dictionary'];
313 const mandatoryKeys = [ 'Element Short Name', 'Element Name', 'Element Type' ];
314 const validTypes = ['string','number','datetime','json','map'];
316 text.setState({validData: false});
317 } else if (headers.length !== dictKeys.length){
318 text.setState({validImport: false});
320 var subDictionaries = [];
321 for(var item in dictList) {
322 if(dictList[item].secondLevelDictionary === 1) {
323 subDictionaries.push(dictList[item].name);
326 subDictionaries = subDictionaries.toString();
328 for (var dictElem of jsonObj){
330 for (var itemKey in dictElem){
331 var value = dictElem[itemKey].trim();
332 if (dictKeys.indexOf(itemKey) < 0){
333 var errorMessage = 'unknown field name of, ' + itemKey + ', found in CSV header';
334 text.setState({validImport: false});
337 } else if (value === "" && mandatoryKeys.indexOf(itemKey) >= 0){
338 errorMessage = 'value for ' + itemKey + ', at row #, ' + row + ', is empty but required';
339 text.setState({validImport: false});
342 } else if (itemKey === 'Element Type' && validTypes.indexOf(value) < 0 && row > 1) {
343 errorMessage = 'invalid dictElemenType of ' + value + ' at row #' + row;
344 text.setState({validImport: false});
347 } else if (value !== "" && itemKey === 'Sub-Dictionary' && subDictionaries.indexOf(value) < 0 && row > 1) {
348 errorMessage = 'invalid subDictionary of ' + value + ' at row #' + row;
349 text.setState({validImport: false});
355 const headerKeys = ['shortName','name','description','type','subDictionary'];
357 for(i = 1; i < dictElems.length; i++) {
358 data = dictElems[i].split(',');
360 for(j = 0; j < data.length; j++) {
361 obj[headerKeys[j].trim()] = data[j].trim();
363 dictionaryElements.push(obj);
365 text.setState({newDictItem: dictionaryElements, addDict: true});
367 reader.readAsText(event.target.files[0]);
369 this.setState({selectedFile: event.target.files[0]})
371 text.setState({validImport: false});
372 alert('Please upload .csv extention files only.');
379 <ModalStyled size="xl" show={this.state.show} onHide={this.handleClose} backdrop="static" keyboard={false} >
380 <Modal.Header closeButton>
381 <Modal.Title>Manage Dictionaries</Modal.Title>
384 {!this.state.dictNameFlag? <MaterialTable
385 title={"Dictionary List"}
386 data={this.state.dictionaryNames}
387 columns={this.state.dictColumns}
388 icons={this.state.tableIcons}
389 onRowClick={(event, rowData) => {this.getDictionaryElements(rowData.name);this.setState({dictNameFlag: true, exportFilename: rowData.name, dictionaryName: rowData.name})}}
391 headerStyle: rowHeaderStyle,
395 new Promise((resolve, reject) => {
398 const dictionaryNames = this.state.dictionaryNames;
399 var validData = true;
400 if(/[^a-zA-Z0-9-_.]/.test(newData.name)) {
402 alert('Please enter alphanumberic input. Only allowed special characters are:(period, hyphen, underscore)');
404 for (var i = 0; i < this.state.dictionaryNames.length; i++) {
405 if (this.state.dictionaryNames[i].name === newData.name) {
407 alert(newData.name + ' dictionary name already exists')
411 dictionaryNames.push(newData);
412 this.setState({ dictionaryNames }, () => resolve());
413 this.setState({addDict: true, newDict: newData});
419 onRowUpdate: (newData, oldData) =>
420 new Promise((resolve, reject) => {
423 const dictionaryNames = this.state.dictionaryNames;
424 var validData = true;
425 if(/[^a-zA-Z0-9-_.]/.test(newData.name)) {
427 alert('Please enter alphanumberic input. Only allowed special characters are:(period, hyphen, underscore)');
430 const index = dictionaryNames.indexOf(oldData);
431 dictionaryNames[index] = newData;
432 this.setState({ dictionaryNames }, () => resolve());
433 this.setState({addDict: true, newDict: newData});
439 onRowDelete: oldData =>
440 new Promise((resolve, reject) => {
443 const data = this.state.dictionaryNames;
444 const index = data.indexOf(oldData);
445 data.splice(index, 1);
446 this.setState({ data }, () => resolve());
447 this.setState({delDict: true, delData: oldData})
455 {this.state.dictNameFlag? <MaterialTable
456 title={"Dictionary Elements List"}
457 data={this.state.dictionaryElements}
458 columns={this.state.dictElementColumns}
459 icons={this.state.tableIcons}
462 exportFileName: this.state.exportFilename,
463 headerStyle:{backgroundColor:'white', fontSize: '15pt', text: 'bold', border: '1px solid black'}
468 <MTableToolbar {...props} />
470 <Grid item container xs={12} alignItems="flex-end" direction="column" justify="flex-end">
471 <Tooltip title="Import" placement = "bottom">
472 <IconButton aria-label="import" onClick={() => this.fileUpload.click()}>
473 <VerticalAlignTopIcon />
478 <input type="file" ref={(fileUpload) => {this.fileUpload = fileUpload;}} style={{ visibility: 'hidden'}} onChange={this.fileSelectedHandler} />
484 new Promise((resolve, reject) => {
487 const dictionaryElements = this.state.dictionaryElements;
488 var validData = true;
489 for (var i = 0; i < this.state.dictionaryElements.length; i++) {
490 if (this.state.dictionaryElements[i].shortName === newData.shortName) {
492 alert(newData.shortname + 'short name already exists')
495 if(/[^a-zA-Z0-9-_.]/.test(newData.shortName)) {
497 alert('Please enter alphanumberic input. Only allowed special characters are:(period, hyphen, underscore)');
501 alert('Element Type cannot be null');
504 dictionaryElements.push(newData);
505 this.setState({ dictionaryElements }, () => resolve());
506 this.setState({addDict: true, newDictItem: [newData]});
512 onRowUpdate: (newData, oldData) =>
513 new Promise((resolve, reject) => {
516 const dictionaryElements = this.state.dictionaryElements;
517 var validData = true;
520 alert('Element Type cannot be null');
523 const index = dictionaryElements.indexOf(oldData);
524 dictionaryElements[index] = newData;
525 this.setState({ dictionaryElements }, () => resolve());
526 this.setState({addDict: true, newDictItem: [newData]});
532 onRowDelete: oldData =>
533 new Promise((resolve, reject) => {
536 let data = this.state.dictionaryElements;
537 const index = data.indexOf(oldData);
538 data.splice(index, 1);
539 this.setState({ data }, () => resolve());
540 this.setState({delDict: true, delDictItem: oldData})
548 {this.state.dictNameFlag?<button onClick={this.clickHandler} style={{marginTop: '25px'}}>Go Back to Dictionaries List</button>:""}
549 {this.state.addDict && this.addDictionary()}
550 {this.state.delDict && this.deleteDictionary()}
553 <Button variant="secondary" type="null" onClick={this.handleClose}>Close</Button>