App onboarding fixes
[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, ViewChild, ElementRef, Inject, PLATFORM_ID, Injector } 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 import { isPlatformBrowser } from '@angular/common';
46
47 @Component({
48   selector: 'app-application-details-dialog',
49   templateUrl: './application-details-dialog.component.html',
50   styleUrls: ['./application-details-dialog.component.scss'],
51 })
52 export class ApplicationDetailsDialogComponent implements OnInit {
53
54   addEditAction: any;
55   emptyImg = null;
56   emptyImgForPreview:string;
57   conflictMessages = {};
58   result: any;
59   isEditMode: boolean = false;
60   appImageTypeError: boolean = false;
61   isSaving: boolean = false;
62   originalImage: any;
63   ECOMP_URL_REGEX = "/^((?:https?\:\/\/|ftp?\:\/\/)?(w{3}.)?(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)[^-_.]$/i";
64   private ngbModal:NgbModal;
65
66   constructor(public activeModal: NgbActiveModal,
67     public applicationsService : ApplicationsService,@Inject(PLATFORM_ID)private platformId:Object,private injector:Injector) {
68       if(isPlatformBrowser(this.platformId))
69       {
70         this.ngbModal = this.injector.get(NgbModal);
71       }
72      }
73
74   @Input() applicationObj: IApplications;
75   @Input() action: any;
76   @Output() passEntry: EventEmitter<any> = new EventEmitter();
77   @ViewChild('applicationName') applicationNameElement: ElementRef;
78   @ViewChild('inputAppImageUpload') inputAppImageUpload: ElementRef;
79
80   newAppModel = {
81     'id': null,
82     'appName': null,
83     'imageUrl': null,
84     'appDescription': null,
85     'appNotes': null,
86     'landingPage': null,
87     'alternateUrl': null,
88     'restUrl': null,
89     'isOpen': false,
90     'appBasicAuthUsername': null,
91     'appBasicAuthPassword': null,
92     'thumbnail': this.emptyImg,
93     'isEnabled': false,
94     'applicationType': null,
95     'rolesInAAF': false,
96     'nameSpace': null,
97     'uebTopicName': null,
98     'uebKey': null,
99     'uebSecret': null,
100     'imageLink': null,
101     'usesCadi': true,
102     'modeOfIntegration': null,
103     'appAck': false,
104     'restrictedApp': false
105   };
106
107   applicationTypeArray: any[] = [
108     { name: 'GUI Application', value: "1" },
109     { name: 'HyperLink Application', value: "2" },
110     { name: 'Non-GUI Application', value: "3" }
111
112   ];
113
114   rolesManagementType: any[] = [
115     { name: 'Roles in Application (Non-Centralized)', value: false },
116     { name: 'Roles in AAF (Centralized)', value: true }
117   ];
118
119   modeOfIntegration: any[] = [
120     { name: 'Portal SDK Based', value: 'sdk' },
121     { name: 'Framework Based', value: 'fw' }
122   ]
123
124   ngOnInit() {
125
126     this.addEditAction = this.action;
127
128
129     if (this.action === 'add') {
130       this.applicationObj.applicationType = "1";
131       if (this.applicationObj.applicationType == '1') {
132         this.applicationObj.modeOfIntegration = this.modeOfIntegration[0].value;
133       }
134       this.applicationObj.rolesInAAF = true;
135       this.applicationObj.usesCadi = true;
136       this.applicationObj.appAck = false;
137       console.log("Action : ", this.action);
138       console.log("Focus : ", this.applicationNameElement.nativeElement);
139       setTimeout(() => { // this will make the execution after the above boolean has changed
140         this.applicationNameElement.nativeElement.focus();
141       }, 0);
142     }
143
144     if (this.applicationObj.id) {
145       this.isEditMode = true;
146     }else{
147       this.isEditMode = false;
148     }
149     //console.log("isEditMode :: ",this.isEditMode);
150     this.originalImage = null
151     this.emptyImgForPreview = '../../../assets/images/default_app_image.gif';
152   }
153
154   appImageHandler(event: any){
155     var reader = new FileReader();
156     if(event.target.files && event.target.files[0]){
157       reader.readAsDataURL(event.target.files[0]); // read file as data url
158       var fileName = event.target.files[0].name;
159       var validFormats = ['jpg', 'jpeg', 'bmp', 'gif', 'png'];
160       //Get file extension
161       var ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
162       //console.log("fileName::>>",fileName ,ext)
163       //console.log("fileExtetion::>>",ext)
164       //Check for valid format
165       if(validFormats.indexOf(ext) == -1){
166           this.newAppModel.thumbnail = this.emptyImg;
167           this.originalImage = null;
168           this.applicationObj.imageUrl = null;
169           this.applicationObj.imageLink = null;
170           this.applicationObj.thumbnail = null;
171           if(!this.isEditMode){
172             this.newAppModel.imageUrl = null;
173             this.newAppModel.imageLink = null;
174             this.newAppModel.thumbnail = null;
175           }
176           this.appImageTypeError=true;
177       }else{
178         reader.onload = (event: any) => { // called once readAsDataURL is completed
179           this.applicationObj.imageLink = event.target.result;
180           this.applicationObj.imageUrl = event.target.result;
181           this.applicationObj.thumbnail = event.target.result;
182           this.originalImage =  event.target.result;
183           if(!this.isEditMode){
184             this.newAppModel.imageLink = event.target.result;
185             this.newAppModel.imageUrl = event.target.result;
186             this.newAppModel.thumbnail = event.target.result;
187             this.originalImage =  event.target.result;
188           }
189         }
190       }
191     }
192   }
193
194   removeImage(){
195     let confirmationMsg = 'Are you sure you want to remove the image?';
196     this.openInformationModal("Confirmation",confirmationMsg).result.then((result) => {
197       if (result === 'Ok') {
198         //this.imageApi.clearFile();
199         this.applicationObj.thumbnail = this.emptyImg;
200         this.originalImage = null;
201         this.applicationObj.imageUrl = null;
202         this.applicationObj.imageLink = null;
203         this.emptyImgForPreview = '../../../assets/images/default_app_image.gif';
204         this.inputAppImageUpload.nativeElement.value = "";
205       }
206     }, (resut) => {
207       return;
208     })
209   }
210
211   /** Add/Edit Application Method*/
212   saveChanges() {
213     //console.log("addNewApplication getting called..");
214     if (this.applicationObj.rolesInAAF) {
215       //if valid.
216       if (this.applicationObj.applicationType == "1") {
217         console.log("Gui Application valodations");
218         //if valid.
219         if (!this.applicationObj.isEnabled) {
220           if (((this.applicationObj.appName == 'undefined' || !this.applicationObj.appName) || (this.applicationObj.nameSpace == 'undefined'
221             || !this.applicationObj.nameSpace) || (this.applicationObj.appBasicAuthUsername == 'undefined' || !this.applicationObj.appBasicAuthUsername))) {
222             this.openConfirmationModal('', 'Please fill in all required fields(*) for centralized application');
223             return;
224           }
225         }
226         if (this.applicationObj.isEnabled) {
227           if (((this.applicationObj.appName == 'undefined' || !this.applicationObj.appName)
228             || (this.applicationObj.landingPage == 'undefined' || !this.applicationObj.landingPage)
229             || (this.applicationObj.appBasicAuthUsername == 'undefined' || !this.applicationObj.appBasicAuthUsername) || (this.applicationObj.nameSpace == 'undefined'
230               || !this.applicationObj.nameSpace))) {
231
232             this.openConfirmationModal('', 'Please fill in all required fields(*) for centralized active application');
233             return;
234           }
235         }
236       } else if (this.applicationObj.applicationType == "3") {
237         console.log("Non-Gui Application valodations");
238         if (!this.applicationObj.isEnabled) {
239           if (((this.applicationObj.appName == 'undefined' || !this.applicationObj.appName) || (this.applicationObj.nameSpace == 'undefined'
240             || !this.applicationObj.nameSpace) || (this.applicationObj.appBasicAuthUsername == 'undefined' || !this.applicationObj.appBasicAuthUsername))) {
241             this.openConfirmationModal('', 'Please fill in all required fields(*) for centralized application');
242             return;
243           }
244         }
245
246         if (this.applicationObj.isEnabled) {
247           if (((this.applicationObj.appName == 'undefined' || !this.applicationObj.appName)
248             || (this.applicationObj.appBasicAuthUsername == 'undefined' || !this.applicationObj.appBasicAuthUsername) || (this.applicationObj.nameSpace == 'undefined'
249               || !this.applicationObj.nameSpace))) {
250
251             this.openConfirmationModal('', 'Please fill in all required fields(*) for centralized active application');
252             return;
253           }
254         }
255       }
256     } else {
257       console.log("Non-centralized applications validation");
258       this.applicationObj.appAck = null;
259       if (!this.applicationObj.isEnabled) {
260         if ((this.applicationObj.appName == 'undefined' || !this.applicationObj.appName)) {
261           this.openConfirmationModal('', 'Please fill in all required field(*) ApplicationName to Save the applictaion');
262           return;
263         }
264       } else if (this.applicationObj.isEnabled && (this.applicationObj.applicationType == "1")) {
265         if ((this.applicationObj.appName == 'undefined' || !this.applicationObj.appName)
266           || (this.applicationObj.landingPage == 'undefined' || !this.applicationObj.landingPage)
267           || (this.applicationObj.appBasicAuthUsername == 'undefined' || !this.applicationObj.appBasicAuthUsername) ||
268           (this.applicationObj.appBasicAuthPassword == 'undefined' || !this.applicationObj.appBasicAuthPassword)) {
269
270           this.openConfirmationModal('', 'Please fill in all required fields(*) along with password as the app is not centralized');
271           return;
272         }
273       } else if (this.applicationObj.isEnabled && (this.applicationObj.applicationType == "3")) {
274         console.log("Non gui validation");
275         if ((this.applicationObj.appName == 'undefined' || !this.applicationObj.appName)
276           || (this.applicationObj.appBasicAuthUsername == 'undefined' || !this.applicationObj.appBasicAuthUsername)) {
277           this.openConfirmationModal('', 'Please fill in all required fields(*)');
278           return;
279         }
280       } else if (this.applicationObj.isEnabled && (this.applicationObj.applicationType == "2")) {
281         if ((this.applicationObj.appName == 'undefined' || !this.applicationObj.appName) || (this.applicationObj.landingPage == 'undefined'
282           || !this.applicationObj.landingPage)) {
283           this.openConfirmationModal('', 'Please fill in all required fields(*)');
284           return;
285         }
286       }
287     }
288
289     //URL Validation
290     if (this.applicationObj.isEnabled && this.applicationObj.applicationType == "1") {
291       if (this.applicationObj.landingPage && this.applicationObj.landingPage != 'undefined' && this.applicationObj.landingPage != '') {
292         let isValidURL = this.isUrlValid(this.applicationObj.landingPage);
293         if (!isValidURL) {
294           this.openConfirmationModal('Error', 'Application URL must be a valid URL.');
295           return;
296         }
297       } else {
298         this.openConfirmationModal('Error', 'Application URL is required.');
299         return;
300       }
301     }
302
303
304     this.isSaving = true;
305     // For a restricted app, null out all irrelevant fields
306     if (this.applicationObj.applicationType == "2") {
307       console.log("Hyperlinka pplication validation");
308       this.newAppModel.restUrl = null;
309       this.newAppModel.isOpen = true;
310       this.newAppModel.appBasicAuthUsername = null;
311       this.newAppModel.appBasicAuthPassword = null;
312       this.newAppModel.uebTopicName = null;
313       this.newAppModel.uebKey = null;
314       this.newAppModel.uebSecret = null;
315       this.newAppModel.restrictedApp = true;
316
317       /**Need to set below fields values based on input provided in the dialog */
318       this.newAppModel.applicationType = this.applicationObj.applicationType;
319       this.newAppModel.appName = this.applicationObj.appName;
320       this.newAppModel.landingPage = this.applicationObj.landingPage;
321       this.newAppModel.usesCadi = this.applicationObj.usesCadi;
322       if (this.applicationObj.isEnabled) {
323         this.newAppModel.isEnabled = this.applicationObj.isEnabled;
324       }else{
325         this.newAppModel.isEnabled = false;
326       }
327       console.log("New Model : ", this.newAppModel);
328     } else {
329
330       /**Need to set below fields values based on input provided in the dialog */
331       this.newAppModel.applicationType = this.applicationObj.applicationType;
332       this.newAppModel.appName = this.applicationObj.appName;
333       this.newAppModel.landingPage = this.applicationObj.landingPage;
334       this.newAppModel.restUrl = this.applicationObj.restUrl;
335       this.newAppModel.appBasicAuthUsername = this.applicationObj.appBasicAuthUsername;
336       this.newAppModel.appBasicAuthPassword = this.applicationObj.appBasicAuthPassword;
337       this.newAppModel.modeOfIntegration = this.applicationObj.modeOfIntegration;
338       this.newAppModel.usesCadi = this.applicationObj.usesCadi;
339       this.newAppModel.appAck = this.applicationObj.appAck;
340
341        if(this.applicationObj.isEnabled){
342         this.newAppModel.isEnabled = this.applicationObj.isEnabled;
343        }else{
344         this.newAppModel.isEnabled = false;
345        }
346
347        if(this.applicationObj.isOpen){
348         this.newAppModel.isOpen = this.applicationObj.isOpen;
349        }else{
350         this.newAppModel.isOpen = false;
351        }
352        //console.log("this.applicationObj.isOpen",this.applicationObj.isOpen);
353
354       if (this.applicationObj.rolesInAAF) {
355         this.newAppModel.rolesInAAF = this.applicationObj.rolesInAAF;
356       } else {
357         this.newAppModel.rolesInAAF = false;
358         this.newAppModel.usesCadi = false;
359       }
360
361     }
362
363     if (this.applicationObj.nameSpace=="") {
364       this.newAppModel.nameSpace = null;
365     }else{
366       this.newAppModel.nameSpace = this.applicationObj.nameSpace;
367     }
368
369     if (this.applicationObj.applicationType == "2" || this.applicationObj.applicationType == "3") {
370       this.applicationObj.modeOfIntegration = null;
371     }
372
373     if (this.newAppModel.applicationType == "2" || this.newAppModel.applicationType == "3") {
374       this.newAppModel.modeOfIntegration = null;
375     }
376
377     if (this.isEditMode) {
378       console.log("Edit application Object : ", JSON.stringify(this.applicationObj));
379       console.log("Mode Of iNtegration : ", this.applicationObj.modeOfIntegration);
380       this.applicationsService.updateOnboardingApp(this.applicationObj)
381         .subscribe( _data => {
382           this.result = _data;
383           //console.log("update application response :: ",this.result);
384           if(this.result !=null && this.result.httpStatusCode ==200){
385             this.passEntry.emit(this.result);
386             this.ngbModal.dismissAll();
387           }else{
388             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);
389             return
390           }
391         }, error => {
392           console.log(error);
393           if(error.status == 409){
394             this.openConfirmationModal('Error', 'There was a problem updating the application changes. ' +
395             'The Application Name and Namespace should  be unique.  Error: ' +
396             error.status);
397             return;
398           }else if(error.status == 500){
399             this.openConfirmationModal('Error', 'There was a problem updating the application information. ' +
400             'Please try again later. Error: ' +error.status);
401             return;
402           }else if(error.status == 404 || error.status == 403){
403             this.openConfirmationModal('Error', 'There was a problem updating the application information. ' +
404             'Invalid namespace. Error: ' +error.status);
405             return;
406           }else if(error.status == 401){
407             this.openConfirmationModal('Error', 'There was a problem updating the application information. ' +
408             'Portal Mechid is unauthorized to access the given namespace. Error: ' +error.status);
409             return;
410           }else if(error.status == 400){
411             this.openConfirmationModal('Error','Bad Request Error: ' + error.status);
412             return;
413           } else{
414             this.openConfirmationModal('Error', 'There was a problem updating the application changes. ' +
415             'Please try again. If the problem persists, then try again later. Error: ' +
416             error.status);
417             return;
418           }
419       });
420
421     }else{
422       //console.log("Coming inside add application",this.newAppModel);
423
424       this.applicationsService.addOnboardingApp(this.newAppModel)
425         .subscribe( _data => {
426           this.result = _data;
427           //console.log("Add application response :: ",this.result);
428           if(this.result !=null && this.result.httpStatusCode ==200){
429             this.passEntry.emit(this.result);
430             this.ngbModal.dismissAll();
431           }else{
432             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);
433             return
434           }
435         }, error => {
436           console.log(error);
437           if(error.status == 409){
438             this.openConfirmationModal('Error', 'There was a problem adding the application changes. ' +
439             'The Application Name and URL should  be unique.  Error: ' +
440             error.status);
441             return;
442           } else if(error.status == 500){
443             this.openConfirmationModal('Error', 'There was a problem adding the application information. ' +
444             'Please try again later. Error: ' +error.status);
445             return;
446           }else if(error.status == 400){
447             this.openConfirmationModal('Error','Bad Request Error: ' + error.status);
448             return;
449           } else{
450             this.openConfirmationModal('Error', 'There was a problem adding the application changes. ' +
451             'Please try again. If the problem persists, then try again later. Error: ' +
452             error.status);
453             return;
454           }
455       });
456     }
457   }
458
459   isUrlValid(userInput){
460     //let  regexQuery = "/^((?:https?\:\/\/|ftp?\:\/\/)?(w{3}.)?(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)[^-_.]$/i";
461     let  regexQuery = "https?://.+";
462     let res = userInput.match(regexQuery);
463     if(res == null){
464       return false;
465     }else{
466       return true;
467     }
468   }
469
470   openConfirmationModal(_title: string, _message: string) {
471     const modalInfoRef = this.ngbModal.open(ConfirmationModalComponent);
472     modalInfoRef.componentInstance.title = _title;
473     modalInfoRef.componentInstance.message = _message;
474   }
475
476   openInformationModal(_title: string, _message: string){
477     const modalInfoRef = this.ngbModal.open(InformationModalComponent);
478     modalInfoRef.componentInstance.title = _title;
479     modalInfoRef.componentInstance.message = _message;
480     return modalInfoRef;
481   }
482 }