6065446147d9fb53de5d9b331bfe691aa1071bea
[portal.git] / portal-FE-os / src / app / pages / application-onboarding / application-details-dialog / application-details-dialog.component.ts
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  *
37  */
38
39 import { Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
40 import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
41 import { IApplications } from 'src/app/shared/model/applications-onboarding/applications';
42 import { ApplicationsService } from 'src/app/shared/services';
43 import { ConfirmationModalComponent } from 'src/app/modals/confirmation-modal/confirmation-modal.component';
44 import { InformationModalComponent } from 'src/app/modals/information-modal/information-modal.component';
45
46 @Component({
47   selector: 'app-application-details-dialog',
48   templateUrl: './application-details-dialog.component.html',
49   styleUrls: ['./application-details-dialog.component.scss'],
50 })
51 export class ApplicationDetailsDialogComponent implements OnInit {
52
53   emptyImg = null;
54   emptyImgForPreview:string;
55   conflictMessages = {};
56   result: any;
57   isEditMode: boolean = false;
58   appImageTypeError: boolean = false;
59   isSaving: boolean = false;
60   originalImage: any;
61   ECOMP_URL_REGEX = "/^((?:https?\:\/\/|ftp?\:\/\/)?(w{3}.)?(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)[^-_.]$/i";
62
63   constructor(public activeModal: NgbActiveModal, public ngbModal: NgbModal,
64     public applicationsService : ApplicationsService) { }
65
66   @Input() applicationObj: IApplications;
67   @Output() passEntry: EventEmitter<any> = new EventEmitter();
68
69   newAppModel = {
70     'id': null,
71     'name': null,
72     'imageUrl': null,
73     'description': null,
74     'notes': null,
75     'url': null,
76     'alternateUrl': null,
77     'restUrl': null,
78     'isOpen': false,
79     'username': null,
80     'appPassword': null,
81     'thumbnail': this.emptyImg,
82     'isEnabled': false,
83     'restrictedApp': false,
84     'nameSpace':null,
85     'isCentralAuth': false,
86     'uebTopicName':null,
87     'uebKey': null,
88     'uebSecret': null,
89     'imageLink': null
90   };
91
92
93   ngOnInit() {
94     if(this.applicationObj.id){
95       this.isEditMode = true;
96     }else{
97       this.isEditMode = false;
98     }
99     //console.log("isEditMode :: ",this.isEditMode);
100     this.originalImage = null
101     this.emptyImgForPreview = '../../../assets/images/default_app_image.gif';
102   }
103
104   appImageHandler(event: any){
105     var reader = new FileReader();
106     if(event.target.files && event.target.files[0]){
107       reader.readAsDataURL(event.target.files[0]); // read file as data url
108       var fileName = event.target.files[0].name;
109       var validFormats = ['jpg', 'jpeg', 'bmp', 'gif', 'png'];
110       //Get file extension
111       var ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
112       //console.log("fileName::>>",fileName ,ext)
113       //console.log("fileExtetion::>>",ext)
114       //Check for valid format
115       if(validFormats.indexOf(ext) == -1){
116           this.newAppModel.thumbnail = this.emptyImg;
117           this.originalImage = null;
118           this.applicationObj.imageUrl = null;
119           this.applicationObj.imageLink = null;
120           this.applicationObj.thumbnail = null;
121           if(!this.isEditMode){
122             this.newAppModel.imageUrl = null;
123             this.newAppModel.imageLink = null;
124             this.newAppModel.thumbnail = null;
125           }
126           this.appImageTypeError=true;
127       }else{
128         reader.onload = (event: any) => { // called once readAsDataURL is completed
129           this.applicationObj.imageLink = event.target.result;
130           this.applicationObj.imageUrl = event.target.result;
131           this.applicationObj.thumbnail = event.target.result;
132           this.originalImage =  event.target.result;
133           if(!this.isEditMode){
134             this.newAppModel.imageLink = event.target.result;
135             this.newAppModel.imageUrl = event.target.result;
136             this.newAppModel.thumbnail = event.target.result;
137             this.originalImage =  event.target.result;
138           }
139         }
140       }
141     }
142   }
143
144   removeImage(){
145     let confirmationMsg = 'Are you sure you want to remove the image?';
146     this.openInformationModal("Confirmation",confirmationMsg).result.then((result) => {
147       if (result === 'Ok') {
148         //this.imageApi.clearFile();
149         this.applicationObj.thumbnail = this.emptyImg;
150         this.originalImage = null;
151         this.applicationObj.imageUrl = null;
152         this.applicationObj.imageLink = null;
153         this.emptyImgForPreview = '../../../assets/images/default_app_image.gif';
154       }
155     }, (resut) => {
156       return;
157     })
158   }
159
160   /** Add/Edit Application Method*/
161   saveChanges() {
162     //console.log("addNewApplication getting called..");
163     if(this.applicationObj.isCentralAuth){
164         //if valid.
165         if(!this.applicationObj.isEnabled){
166           if(((this.applicationObj.name == 'undefined' || !this.applicationObj.name)||(this.applicationObj.nameSpace == 'undefined'
167           || !this.applicationObj.nameSpace) ||(this.applicationObj.username == 'undefined' || !this.applicationObj.username))) {
168             this.openConfirmationModal('','Please fill in all required fields(*) for centralized application');
169             return;
170           }
171         }
172         if(this.applicationObj.isEnabled){
173           if(((this.applicationObj.name == 'undefined' || !this.applicationObj.name)
174           ||(this.applicationObj.url == 'undefined'|| !this.applicationObj.url)
175           ||(this.applicationObj.username == 'undefined' || !this.applicationObj.username)||(this.applicationObj.nameSpace == 'undefined'
176           || !this.applicationObj.nameSpace))) {
177
178             this.openConfirmationModal('','Please fill in all required fields(*) for centralized active application');
179             return;
180           }
181         }
182     }else{
183         if(!this.applicationObj.isEnabled) {
184             if((this.applicationObj.name == 'undefined' || !this.applicationObj.name)){
185                 this.openConfirmationModal('','Please fill in all required field(*) ApplicationName to Save the applictaion');
186                 return;
187             }
188         }else if(this.applicationObj.isEnabled && !this.applicationObj.restrictedApp){
189           if((this.applicationObj.name == 'undefined' || !this.applicationObj.name)
190             ||(this.applicationObj.url == 'undefined'|| !this.applicationObj.url)
191             ||(this.applicationObj.username == 'undefined' || !this.applicationObj.username)||
192             (this.applicationObj.appPassword== 'undefined' || !this.applicationObj.appPassword)) {
193
194               this.openConfirmationModal('','Please fill in all required fields(*) along with password as the app is not centralized');
195               return;
196           }
197         }else if(this.applicationObj.isEnabled && this.applicationObj.restrictedApp){
198             if((this.applicationObj.name == 'undefined' || !this.applicationObj.name) ||(this.applicationObj.url == 'undefined'
199             || !this.applicationObj.url)){
200                 this.openConfirmationModal('','Please fill in all required fields(*)');
201                 return;
202             }
203         }
204     }
205
206     //URL Validation
207     if(this.applicationObj.isEnabled){
208       if(this.applicationObj.url && this.applicationObj.url !='undefined' && this.applicationObj.url != ''){
209         let isValidURL = this.isUrlValid(this.applicationObj.url);
210         if(!isValidURL){
211           this.openConfirmationModal('Error','Application URL must be a valid URL.');
212           return;
213         }
214       }else{
215         this.openConfirmationModal('Error','Application URL is required.');
216         return;
217       }
218     }
219
220
221     this.isSaving = true;
222     // For a restricted app, null out all irrelevant fields
223     if(this.applicationObj.restrictedApp) {
224       this.newAppModel.restUrl = null;
225       this.newAppModel.isOpen = true;
226       this.newAppModel.username = null;
227       this.newAppModel.appPassword = null;
228       this.newAppModel.uebTopicName = null;
229       this.newAppModel.uebKey = null;
230       this.newAppModel.uebSecret = null;
231
232       /**Need to set below fields values based on input provided in the dialog */
233       this.newAppModel.restrictedApp = this.applicationObj.restrictedApp;
234       this.newAppModel.name = this.applicationObj.name;
235       this.newAppModel.url = this.applicationObj.url;
236       if(this.applicationObj.isEnabled){
237         this.newAppModel.isEnabled = this.applicationObj.isEnabled;
238       }else{
239         this.newAppModel.isEnabled = false;
240       }
241
242     }else{
243
244        /**Need to set below fields values based on input provided in the dialog */
245        this.newAppModel.restrictedApp = false;
246        this.newAppModel.name = this.applicationObj.name;
247        this.newAppModel.url = this.applicationObj.url;
248        this.newAppModel.restUrl = this.applicationObj.restUrl;
249        this.newAppModel.username = this.applicationObj.username;
250        this.newAppModel.appPassword = this.applicationObj.appPassword;
251
252        if(this.applicationObj.isEnabled){
253         this.newAppModel.isEnabled = this.applicationObj.isEnabled;
254        }else{
255         this.newAppModel.isEnabled = false;
256        }
257
258        if(this.applicationObj.isOpen){
259         this.newAppModel.isOpen = this.applicationObj.isOpen;
260        }else{
261         this.newAppModel.isOpen = false;
262        }
263        //console.log("this.applicationObj.isOpen",this.applicationObj.isOpen);
264
265        if(this.applicationObj.isCentralAuth){
266         this.newAppModel.isCentralAuth = this.applicationObj.isCentralAuth;
267        }else{
268         this.newAppModel.isCentralAuth = false;
269        }
270
271     }
272
273     if (this.applicationObj.nameSpace=="") {
274       this.newAppModel.nameSpace = null;
275     }
276
277     if(this.isEditMode){
278       this.applicationsService.updateOnboardingApp(this.applicationObj)
279         .subscribe( _data => {
280           this.result = _data;
281           //console.log("update application response :: ",this.result);
282           if(this.result !=null && this.result.httpStatusCode ==200){
283             this.passEntry.emit(this.result);
284             this.ngbModal.dismissAll();
285           }else{
286             this.openConfirmationModal('Error','There was a problem updating the application changes. Please try again. If the problem persists, then try again later. Error: '+this.result);
287             return
288           }
289         }, error => {
290           console.log(error);
291           if(error.status == 409){
292             this.openConfirmationModal('Error', 'There was a problem updating the application changes. ' +
293             'The Application Name and URL should  be unique.  Error: ' +
294             error.status);
295             return;
296           }else if(error.status == 500){
297             this.openConfirmationModal('Error', 'There was a problem updating the application information. ' +
298             'Please try again later. Error: ' +error.status);
299             return;
300           }else if(error.status == 404 || error.status == 403){
301             this.openConfirmationModal('Error', 'There was a problem updating the application information. ' +
302             'Invalid namespace. Error: ' +error.status);
303             return;
304           }else if(error.status == 401){
305             this.openConfirmationModal('Error', 'There was a problem updating the application information. ' +
306             'Portal Mechid is unauthorized to access the given namespace. Error: ' +error.status);
307             return;
308           }else if(error.status == 400){
309             this.openConfirmationModal('Error','Bad Request Error: ' + error.status);
310             return;
311           } else{
312             this.openConfirmationModal('Error', 'There was a problem updating the application changes. ' +
313             'Please try again. If the problem persists, then try again later. Error: ' +
314             error.status);
315             return;
316           }
317       });
318
319     }else{
320       //console.log("Coming inside add application",this.newAppModel);
321
322       this.applicationsService.addOnboardingApp(this.newAppModel)
323         .subscribe( _data => {
324           this.result = _data;
325           //console.log("Add application response :: ",this.result);
326           if(this.result !=null && this.result.httpStatusCode ==200){
327             this.passEntry.emit(this.result);
328             this.ngbModal.dismissAll();
329           }else{
330             this.openConfirmationModal('Error','There was a problem adding the application changes. Please try again. If the problem persists, then try again later. Error: '+this.result);
331             return
332           }
333         }, error => {
334           console.log(error);
335           if(error.status == 409){
336             this.openConfirmationModal('Error', 'There was a problem adding the application changes. ' +
337             'The Application Name and URL should  be unique.  Error: ' +
338             error.status);
339             return;
340           } else if(error.status == 500){
341             this.openConfirmationModal('Error', 'There was a problem adding the application information. ' +
342             'Please try again later. Error: ' +error.status);
343             return;
344           }else if(error.status == 400){
345             this.openConfirmationModal('Error','Bad Request Error: ' + error.status);
346             return;
347           } else{
348             this.openConfirmationModal('Error', 'There was a problem adding the application changes. ' +
349             'Please try again. If the problem persists, then try again later. Error: ' +
350             error.status);
351             return;
352           }
353       });
354     }
355   }
356
357   isUrlValid(userInput){
358     //let  regexQuery = "/^((?:https?\:\/\/|ftp?\:\/\/)?(w{3}.)?(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)[^-_.]$/i";
359     let  regexQuery = "https?://.+";
360     let res = userInput.match(regexQuery);
361     if(res == null){
362       return false;
363     }else{
364       return true;
365     }
366   }
367
368   openConfirmationModal(_title: string, _message: string) {
369     const modalInfoRef = this.ngbModal.open(ConfirmationModalComponent);
370     modalInfoRef.componentInstance.title = _title;
371     modalInfoRef.componentInstance.message = _message;
372   }
373
374   openInformationModal(_title: string, _message: string){
375     const modalInfoRef = this.ngbModal.open(InformationModalComponent);
376     modalInfoRef.componentInstance.title = _title;
377     modalInfoRef.componentInstance.message = _message;
378     return modalInfoRef;
379   }
380 }