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 for(var item in dictList) {
91 if(dictList[item].secondLevelDictionary === 1) {
92 subDicts.push(dictList[item].name);
96 var optionItems = subDicts.map(
97 (item) => <option key={item}>{item}</option>
99 function selectedValue (e) {
100 onChange(e.target.value);
103 <select onChange={selectedValue} >
109 export default class ManageDictionaries extends React.Component {
110 constructor(props, context) {
111 super(props, context);
112 this.handleClose = this.handleClose.bind(this);
113 this.getDictionary = this.getDictionary.bind(this);
114 this.getDictionaryElements = this.getDictionaryElements.bind(this);
115 this.clickHandler = this.clickHandler.bind(this);
116 this.addDictionary = this.addDictionary.bind(this);
117 this.deleteDictionary = this.deleteDictionary.bind(this);
118 this.fileSelectedHandler = this.fileSelectedHandler.bind(this);
133 dictionaryElements: [],
135 Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
136 Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
137 Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
138 Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
139 DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
140 Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
141 Export: forwardRef((props, ref) => <VerticalAlignBottomIcon {...props} ref={ref} />),
142 Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
143 FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
144 LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
145 NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
146 PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />),
147 ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
148 Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
149 SortArrow: forwardRef((props, ref) => <ArrowUpward {...props} ref={ref} />),
150 ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
151 ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />)
155 title: "Dictionary Name", field: "name",editable: 'onAdd',
156 cellStyle: cellStyle,
157 headerStyle: headerStyle
160 title: "Sub Dictionary ?", field: "secondLevelDictionary", lookup: {0: 'No', 1: 'Yes'},
161 cellStyle: cellStyle,
162 headerStyle: headerStyle
165 title: "Dictionary Type", field: "subDictionaryType",lookup: {string: 'string', number: 'number'},
166 cellStyle: cellStyle,
167 headerStyle: headerStyle
170 title: "Updated By", field: "updatedBy", editable: 'never',
171 cellStyle: cellStyle,
172 headerStyle: headerStyle
175 title: "Last Updated Date", field: "updatedDate", editable: 'never',
176 cellStyle: cellStyle,
177 headerStyle: headerStyle
180 dictElementColumns: [
182 title: "Element Short Name", field: "shortName",editable: 'onAdd',
183 cellStyle: cellStyle,
184 headerStyle: headerStyle
187 title: "Element Name", field: "name",
188 cellStyle: cellStyle,
189 headerStyle: headerStyle
192 title: "Element Description", field: "description",
193 cellStyle: cellStyle,
194 headerStyle: headerStyle
197 title: "Element Type", field: "type",
198 editComponent: props => (
200 <SelectSubDictType value={props.value} onChange={props.onChange} />
203 cellStyle: cellStyle,
204 headerStyle: headerStyle
207 title: "Sub-Dictionary", field: "subDictionary",
208 editComponent: props => (
210 <SubDict value={props.value} onChange={props.onChange} />
213 cellStyle: cellStyle,
214 headerStyle: headerStyle
217 title: "Updated By", field: "updatedBy", editable: 'never',
218 cellStyle: cellStyle,
219 headerStyle: headerStyle
222 title: "Updated Date", field: "updatedDate", editable: 'never',
223 cellStyle: cellStyle,
224 headerStyle: headerStyle
230 componentWillMount() {
231 this.getDictionary();
235 TemplateMenuService.getDictionary().then(dictionaryNames => {
236 this.setState({ dictionaryNames: dictionaryNames })
240 getDictionaryElements(dictionaryName) {
241 TemplateMenuService.getDictionaryElements(dictionaryName).then(dictionaryElements => {
242 dictList = this.state.dictionaryNames;
243 this.setState({ dictionaryElements: dictionaryElements.dictionaryElements});
247 clickHandler(rowData) {
255 this.setState({ show: false });
256 this.props.history.push('/');
260 var modifiedData = [];
261 if(this.state.newDict !== '') {
262 modifiedData = this.state.newDict;
264 modifiedData = {"name": this.state.dictionaryName, 'dictionaryElements': this.state.newDictItem};
266 if(this.state.newDictItem === '') {
267 TemplateMenuService.insDictionary(modifiedData).then(resp => {
270 TemplateMenuService.insDictionaryElements(modifiedData).then(resp => {
276 var modifiedData = [];
277 if(this.state.delData !== '') {
278 modifiedData = this.state.delData.name;
280 modifiedData = {"name": this.state.dictionaryName, "shortName": this.state.delDictItem.shortName};
282 if(this.state.delDictItem === '') {
283 TemplateMenuService.deleteDictionary(modifiedData).then(resp => {
286 TemplateMenuService.deleteDictionaryElements(modifiedData).then(resp => {
291 fileSelectedHandler = (event) => {
293 var dictionaryElements = [];
294 if (event.target.files[0].type === 'text/csv' ) {
295 if (event.target.files && event.target.files[0]) {
296 const reader = new FileReader();
297 reader.onload = function(e) {
298 var dictElems = reader.result.split('\n');
300 var headers = dictElems[0].split(',');
301 for(var i = 0; i < dictElems.length; i++) {
302 var data = dictElems[i].split(',');
304 for(var j = 0; j < data.length; j++) {
305 obj[headers[j].trim()] = data[j].trim();
309 JSON.stringify(jsonObj);
310 const dictKeys = ['Element Short Name','Element Name','Element Description','Element Type','Sub-Dictionary'];
311 const mandatoryKeys = [ 'Element Short Name', 'Element Name', 'Element Type' ];
312 const validTypes = ['string','number','datetime','json','map'];
314 text.setState({validData: false});
315 } else if (headers.length !== dictKeys.length){
316 text.setState({validImport: false});
318 var subDictionaries = [];
319 for(var item in dictList) {
320 if(dictList[item].secondLevelDictionary === 1) {
321 subDictionaries.push(dictList[item].name);
324 subDictionaries = subDictionaries.toString();
326 for (var dictElem of jsonObj){
328 for (var itemKey in dictElem){
329 var value = dictElem[itemKey].trim();
330 if (dictKeys.indexOf(itemKey) < 0){
331 var errorMessage = 'unknown field name of, ' + itemKey + ', found in CSV header';
332 text.setState({validImport: false});
335 } else if (value === "" && mandatoryKeys.indexOf(itemKey) >= 0){
336 errorMessage = 'value for ' + itemKey + ', at row #, ' + row + ', is empty but required';
337 text.setState({validImport: false});
340 } else if (itemKey === 'Element Type' && validTypes.indexOf(value) < 0 && row > 1) {
341 errorMessage = 'invalid dictElemenType of ' + value + ' at row #' + row;
342 text.setState({validImport: false});
345 } else if (value !== "" && itemKey === 'Sub-Dictionary' && subDictionaries.indexOf(value) < 0 && row > 1) {
346 errorMessage = 'invalid subDictionary of ' + value + ' at row #' + row;
347 text.setState({validImport: false});
353 const headerKeys = ['shortName','name','description','type','subDictionary'];
355 for(i = 1; i < dictElems.length; i++) {
356 data = dictElems[i].split(',');
358 for(j = 0; j < data.length; j++) {
359 obj[headerKeys[j].trim()] = data[j].trim();
361 dictionaryElements.push(obj);
363 text.setState({newDictItem: dictionaryElements, addDict: true});
365 reader.readAsText(event.target.files[0]);
367 this.setState({selectedFile: event.target.files[0]})
369 text.setState({validImport: false});
370 alert('Please upload .csv extention files only.');
377 <ModalStyled size="xl" show={this.state.show} onHide={this.handleClose} backdrop="static" keyboard={false} >
378 <Modal.Header closeButton>
379 <Modal.Title>Manage Dictionaries</Modal.Title>
382 {!this.state.dictNameFlag? <MaterialTable
383 title={"Dictionary List"}
384 data={this.state.dictionaryNames}
385 columns={this.state.dictColumns}
386 icons={this.state.tableIcons}
387 onRowClick={(event, rowData) => {this.getDictionaryElements(rowData.name);this.setState({dictNameFlag: true, exportFilename: rowData.name, dictionaryName: rowData.name})}}
389 headerStyle: rowHeaderStyle,
393 new Promise((resolve, reject) => {
396 const dictionaryNames = this.state.dictionaryNames;
397 var validData = true;
398 if(/[^a-zA-Z0-9-_.]/.test(newData.name)) {
400 alert('Please enter alphanumberic input. Only allowed special characters are:(period, hyphen, underscore)');
402 for (var i = 0; i < this.state.dictionaryNames.length; i++) {
403 if (this.state.dictionaryNames[i].name === newData.name) {
405 alert(newData.name + ' dictionary name already exists')
409 dictionaryNames.push(newData);
410 this.setState({ dictionaryNames }, () => resolve());
411 this.setState({addDict: true, newDict: newData});
417 onRowUpdate: (newData, oldData) =>
418 new Promise((resolve, reject) => {
421 const dictionaryNames = this.state.dictionaryNames;
422 var validData = true;
423 if(/[^a-zA-Z0-9-_.]/.test(newData.name)) {
425 alert('Please enter alphanumberic input. Only allowed special characters are:(period, hyphen, underscore)');
428 const index = dictionaryNames.indexOf(oldData);
429 dictionaryNames[index] = newData;
430 this.setState({ dictionaryNames }, () => resolve());
431 this.setState({addDict: true, newDict: newData});
437 onRowDelete: oldData =>
438 new Promise((resolve, reject) => {
441 const data = this.state.dictionaryNames;
442 const index = data.indexOf(oldData);
443 data.splice(index, 1);
444 this.setState({ data }, () => resolve());
445 this.setState({delDict: true, delData: oldData})
453 {this.state.dictNameFlag? <MaterialTable
454 title={"Dictionary Elements List"}
455 data={this.state.dictionaryElements}
456 columns={this.state.dictElementColumns}
457 icons={this.state.tableIcons}
460 exportFileName: this.state.exportFilename,
461 headerStyle:{backgroundColor:'white', fontSize: '15pt', text: 'bold', border: '1px solid black'}
466 <MTableToolbar {...props} />
468 <Grid item container xs={12} alignItems="flex-end" direction="column" justify="flex-end">
469 <Tooltip title="Import" placement = "bottom">
470 <IconButton aria-label="import" onClick={() => this.fileUpload.click()}>
471 <VerticalAlignTopIcon />
476 <input type="file" ref={(fileUpload) => {this.fileUpload = fileUpload;}} style={{ visibility: 'hidden'}} onChange={this.fileSelectedHandler} />
482 new Promise((resolve, reject) => {
485 const dictionaryElements = this.state.dictionaryElements;
486 var validData = true;
487 for (var i = 0; i < this.state.dictionaryElements.length; i++) {
488 if (this.state.dictionaryElements[i].shortName === newData.shortName) {
490 alert(newData.shortname + 'short name already exists')
493 if(/[^a-zA-Z0-9-_.]/.test(newData.shortName)) {
495 alert('Please enter alphanumberic input. Only allowed special characters are:(period, hyphen, underscore)');
499 alert('Element Type cannot be null');
502 dictionaryElements.push(newData);
503 this.setState({ dictionaryElements }, () => resolve());
504 this.setState({addDict: true, newDictItem: [newData]});
510 onRowUpdate: (newData, oldData) =>
511 new Promise((resolve, reject) => {
514 const dictionaryElements = this.state.dictionaryElements;
515 var validData = true;
518 alert('Element Type cannot be null');
521 const index = dictionaryElements.indexOf(oldData);
522 dictionaryElements[index] = newData;
523 this.setState({ dictionaryElements }, () => resolve());
524 this.setState({addDict: true, newDictItem: [newData]});
530 onRowDelete: oldData =>
531 new Promise((resolve, reject) => {
534 let data = this.state.dictionaryElements;
535 const index = data.indexOf(oldData);
536 data.splice(index, 1);
537 this.setState({ data }, () => resolve());
538 this.setState({delDict: true, delDictItem: oldData})
546 {this.state.dictNameFlag?<button onClick={this.clickHandler} style={{marginTop: '25px'}}>Go Back to Dictionaries List</button>:""}
547 {this.state.addDict && this.addDictionary()}
548 {this.state.delDict && this.deleteDictionary()}
551 <Button variant="secondary" type="null" onClick={this.handleClose}>Close</Button>