Updated Sparky to add ECOMP functionality Browse, Specialized Search, BYOQ, and the...
[aai/sparky-fe.git] / src / app / modifications / Modifications.jsx
1 /*
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2021 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
10  *
11  *       http://www.apache.org/licenses/LICENSE-2.0
12  *
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  */
20
21 import React, {Component} from 'react';
22 import {GlobalExtConstants} from 'utils/GlobalExtConstants.js';
23 import Col from 'react-bootstrap/lib/Col';
24 import Row from 'react-bootstrap/lib/Row';
25 import Grid from 'react-bootstrap/lib/Grid';
26 import Panel from 'react-bootstrap/lib/Panel';
27 import * as Excel from 'exceljs/dist/exceljs.min.js';
28 import Spinner from 'utils/SpinnerContainer.jsx';
29
30 let INVLIST = GlobalExtConstants.INVLIST;
31 let OXM = GlobalExtConstants.OXM;
32
33 let invList = null;
34
35 class Modifications extends Component {
36
37   state = {
38             file:null,
39             enableBusyFeedback: false,
40             enableUploadFeedback: false,
41             showResults: false,
42             errorResults: true
43           };
44
45   constructor(){
46     super();
47   }
48   componentDidMount(){
49   };
50   addValidationError = (baseString, sheetName, row, validationError) => {
51     return baseString += 'Error occurred on worksheet ' + sheetName + ' at Row ' + row + ' '
52             + validationError + '\n';
53   }
54   uploadedFile = (e) => {
55       this.setState({enableUploadFeedback: true,enableBusyFeedback:false,showResults:false,errorResults:false});
56       let reader = new FileReader();
57       let file = e.target.files[0];
58       let wb = new Excel.Workbook();
59       var columnHeaders = [];
60       var jsonPayload = [];
61       reader.onload= () => {
62             const buffer = reader.result;
63             var validationErrors = {};
64                 wb.xlsx.load(buffer).then(workbook => {
65                   workbook.eachSheet(function(worksheet, sheetId) {
66                                       worksheet.eachRow({ includeEmpty: true }, function(row, rowNumber) {
67                                       if(rowNumber === 1){
68                                         for(var j = 1;j <= row.values.length; j++){
69                                             columnHeaders[sheetId + '-' + j ] = row.values[j];
70                                         }
71                                       }else{
72                                         var obj = {};
73                                         obj.properties = {};
74                                         obj['node-type'] = worksheet.name;
75                                         for(var j = 1;j <= row.values.length; j++){
76                                             if(['uri','action'].indexOf(columnHeaders[sheetId + '-' + j ]) > -1){
77                                                 obj[columnHeaders[sheetId + '-' + j ]] = row.values[j];
78                                                 if(!row.values[j] || row.values[j] === ""){
79
80                                                 }else if (columnHeaders[sheetId + '-' + j ] === 'action'
81                                                     && ['DELETE','UPDATE', 'ADD'].indexOf((row.values[j]).toUpperCase()) === -1 ){
82                                                     validationErrors = this.addValidationError(validationErrors,
83                                                         worksheet.name, j, 'Action needs to be DELETE, UPDATE, or ADD');
84                                                 }
85                                             }else if(columnHeaders[sheetId + '-' + j ] !== 'relationship-list'){
86                                                 obj.properties[columnHeaders[sheetId + '-' + j ]] = row.values[j];
87                                             }
88                                         }
89                                         jsonPayload.push(obj);
90                                       }
91                                       console.log("Row " + rowNumber + " = " + JSON.stringify(row.values));
92                                       });
93                        console.log(JSON.stringify(jsonPayload));
94                   });
95                   this.setState({enableUploadFeedback: false});
96                 });
97
98       }
99       if((file.name).endsWith(".xls") || (file.name).endsWith(".xlsx")){
100         reader.readAsArrayBuffer(file);
101       }else{
102         var error = {};
103         error.validationMsg =  "Please upload a valid file, valid files are .xslx and .xsl only."
104         triggerError(error);
105         this.setState({enableUploadFeedback: false});
106       }
107   }
108   onFileSubmit = () => {
109     this.setState({enableBusyFeedback:true,showResults:false,errorResults:false});
110   }
111   triggerError = (error) => {
112      console.error('[Modifications.jsx] error : ', JSON.stringify(error));
113      this.setState({
114             enableBusyFeedback: false,
115                 showResults: false,
116                 errorResults: true
117        });
118       let errMsg = '';
119       if(error.validationMsg){
120         errMsg = error.validationMsg;
121       } else if (error.response) {
122         // The request was made and the server responded with a status code
123         // that falls out of the range of 2xx
124         console.log(error.response.data);
125         console.log(error.response.status);
126         console.log(error.response.headers);
127         if(error.response.status){
128             errMsg += " Code: " + error.response.status;
129         }
130             if(error.response.data){
131             errMsg += " - " + JSON.stringify(error.response.data);
132         }
133       } else if (error.request) {
134         // The request was made but no response was received
135         // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
136         // http.ClientRequest in node.js
137         console.log(error.request);
138         errMsg += " - Request was made but no response received";
139       } else {
140         // Something happened in setting up the request that triggered an Error
141         console.log('Error', error.message);
142         errMsg += " - Unknown error occurred " + error.message;
143       }
144       //Suppress Error Message when 404 results not found occur
145       if(error.response && error.response.status === 404){
146            this.setState({errorMessage:'', errorResults:false});
147       }else{
148            this.setState({errorMessage:errMsg});
149       }
150    }
151   render = () => {
152     return(
153       <div>
154           <div id='modifications'>
155                 <header className='addPadding jumbotron my-4'>
156                     <h1 className='display-2'>Modifications Page</h1>
157                     <p className='lead'>
158                       On this page you have the ability to make modifications to the data by uploading a xslx.
159                     </p>
160                 </header>
161                 <Grid fluid={true} className='model-container'>
162                     <Spinner loading={this.state.enableUploadFeedback}>
163                         <Row>
164                             <form className="addPadding" onSubmit={this.onFileSubmit}>
165                                   <div className="row justify-content-center mb-2">
166                                        <input onChange={this.uploadedFile} type="file" id="excelFile" accept=".xlsx, .xls"/>
167                                        <button type="submit" className="btn btn-sm btn-info">Send</button>
168                                    </div>
169                             </form>
170                         </Row>
171                     </Spinner>
172                     <Spinner loading={this.state.enableBusyFeedback}>
173                          <Row>
174                            <div className={'addPaddingTop alert alert-danger ' +(this.state.errorResults ? 'show' : 'hidden')} role="alert">
175                                An error occurred, please try again later. If this issue persists, please contact the system administrator. {this.state.errorMessage}
176                            </div>
177                          </Row>
178                          <Row>
179                            <div className={'addPaddingTop alert alert-success ' +(this.state.showResults ? 'show' : 'hidden')} role="alert">
180                                The updates were made successfully.
181                            </div>
182                          </Row>
183                     </Spinner>
184                 </Grid>
185           </div>
186       </div>
187     );
188   }
189  }
190 export default Modifications;