7aad140a6fe2d0ca64c5ff49d403d7f5107014e8
[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, PLATFORM_ID, Inject, 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   emptyImg = null;
55   emptyImgForPreview:string;
56   conflictMessages = {};
57   result: any;
58   isEditMode: boolean = false;
59   appImageTypeError: boolean = false;
60   isSaving: boolean = false;
61   originalImage: any;
62   ECOMP_URL_REGEX = "/^((?:https?\:\/\/|ftp?\:\/\/)?(w{3}.)?(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)[^-_.]$/i";
63   private ngbModal:NgbModal;
64
65   constructor(public activeModal: NgbActiveModal,
66     public applicationsService : ApplicationsService,@Inject(PLATFORM_ID)private platformId:Object,private injector:Injector) {
67       if(isPlatformBrowser(this.platformId))
68       {
69         this.ngbModal = this.injector.get(NgbModal);
70       }
71      }
72
73   @Input() applicationObj: IApplications;
74   @Output() passEntry: EventEmitter<any> = new EventEmitter();
75
76   newAppModel = {
77     'id': null,
78     'name': null,
79     'imageUrl': null,
80     'description': null,
81     'notes': null,
82     'url': null,
83     'alternateUrl': null,
84     'restUrl': null,
85     'isOpen': false,
86     'username': null,
87     'appPassword': null,
88     'thumbnail': this.emptyImg,
89     'isEnabled': false,
90     'restrictedApp': false,
91     'nameSpace':null,
92     'isCentralAuth': false,
93     'uebTopicName':null,
94     'uebKey': null,
95     'uebSecret': null,
96     'imageLink': null
97   };
98
99
100   ngOnInit() {
101     if(this.applicationObj.id){
102       this.isEditMode = true;
103     }else{
104       this.isEditMode = false;
105     }
106     //console.log("isEditMode :: ",this.isEditMode);
107     this.originalImage = null
108     this.emptyImgForPreview = '../../../assets/images/default_app_image.gif';
109   }
110
111   appImageHandler(event: any){
112     var reader = new FileReader();
113     if(event.target.files && event.target.files[0]){
114       reader.readAsDataURL(event.target.files[0]); // read file as data url
115       var fileName = event.target.files[0].name;
116       var validFormats = ['jpg', 'jpeg', 'bmp', 'gif', 'png'];
117       //Get file extension
118       var ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
119       //console.log("fileName::>>",fileName ,ext)
120       //console.log("fileExtetion::>>",ext)
121       //Check for valid format
122       if(validFormats.indexOf(ext) == -1){
123           this.newAppModel.thumbnail = this.emptyImg;
124           this.originalImage = null;
125           this.applicationObj.imageUrl = null;
126           this.applicationObj.imageLink = null;
127           this.applicationObj.thumbnail = null;
128           if(!this.isEditMode){
129             this.newAppModel.imageUrl = null;
130             this.newAppModel.imageLink = null;
131             this.newAppModel.thumbnail = null;
132           }
133           this.appImageTypeError=true;
134       }else{
135         reader.onload = (event: any) => { // called once readAsDataURL is completed
136           this.applicationObj.imageLink = event.target.result;
137           this.applicationObj.imageUrl = event.target.result;
138           this.applicationObj.thumbnail = event.target.result;
139           this.originalImage =  event.target.result;
140           if(!this.isEditMode){
141             this.newAppModel.imageLink = event.target.result;
142             this.newAppModel.imageUrl = event.target.result;
143             this.newAppModel.thumbnail = event.target.result;
144             this.originalImage =  event.target.result;
145           }
146         }
147       }
148     }
149   }
150
151   removeImage(){
152     let confirmationMsg = 'Are you sure you want to remove the image?';
153     this.openInformationModal("Confirmation",confirmationMsg).result.then((result) => {
154       if (result === 'Ok') {
155         //this.imageApi.clearFile();
156         this.applicationObj.thumbnail = this.emptyImg;
157         this.originalImage = null;
158         this.applicationObj.imageUrl = null;
159         this.applicationObj.imageLink = null;
160         this.emptyImgForPreview = '../../../assets/images/default_app_image.gif';
161       }
162     }, (resut) => {
163       return;
164     })
165   }
166
167   /** Add/Edit Application Method*/
168   saveChanges() {
169     //console.log("addNewApplication getting called..");
170     if(this.applicationObj.isCentralAuth){
171         //if valid.
172         if(!this.applicationObj.isEnabled){
173           if(((this.applicationObj.name == 'undefined' || !this.applicationObj.name)||(this.applicationObj.nameSpace == 'undefined'
174           || !this.applicationObj.nameSpace) ||(this.applicationObj.username == 'undefined' || !this.applicationObj.username))) {
175             this.openConfirmationModal('','Please fill in all required fields(*) for centralized application');
176             return;
177           }
178         }
179         if(this.applicationObj.isEnabled){
180           if(((this.applicationObj.name == 'undefined' || !this.applicationObj.name)
181           ||(this.applicationObj.url == 'undefined'|| !this.applicationObj.url)
182           ||(this.applicationObj.username == 'undefined' || !this.applicationObj.username)||(this.applicationObj.nameSpace == 'undefined'
183           || !this.applicationObj.nameSpace))) {
184
185             this.openConfirmationModal('','Please fill in all required fields(*) for centralized active application');
186             return;
187           }
188         }
189     }else{
190         if(!this.applicationObj.isEnabled) {
191             if((this.applicationObj.name == 'undefined' || !this.applicationObj.name)){
192                 this.openConfirmationModal('','Please fill in all required field(*) ApplicationName to Save the applictaion');
193                 return;
194             }
195         }else if(this.applicationObj.isEnabled && !this.applicationObj.restrictedApp){
196           if((this.applicationObj.name == 'undefined' || !this.applicationObj.name)
197             ||(this.applicationObj.url == 'undefined'|| !this.applicationObj.url)
198             ||(this.applicationObj.username == 'undefined' || !this.applicationObj.username)||
199             (this.applicationObj.appPassword== 'undefined' || !this.applicationObj.appPassword)) {
200
201               this.openConfirmationModal('','Please fill in all required fields(*) along with password as the app is not centralized');
202               return;
203           }
204         }else if(this.applicationObj.isEnabled && this.applicationObj.restrictedApp){
205             if((this.applicationObj.name == 'undefined' || !this.applicationObj.name) ||(this.applicationObj.url == 'undefined'
206             || !this.applicationObj.url)){
207                 this.openConfirmationModal('','Please fill in all required fields(*)');
208                 return;
209             }
210         }
211     }
212
213     //URL Validation
214     if(this.applicationObj.isEnabled){
215       if(this.applicationObj.url && this.applicationObj.url !='undefined' && this.applicationObj.url != ''){
216         let isValidURL = this.isUrlValid(this.applicationObj.url);
217         if(!isValidURL){
218           this.openConfirmationModal('Error','Application URL must be a valid URL.');
219           return;
220         }
221       }else{
222         this.openConfirmationModal('Error','Application URL is required.');
223         return;
224       }
225     }
226
227
228     this.isSaving = true;
229     // For a restricted app, null out all irrelevant fields
230     if(this.applicationObj.restrictedApp) {
231       this.newAppModel.restUrl = null;
232       this.newAppModel.isOpen = true;
233       this.newAppModel.username = null;
234       this.newAppModel.appPassword = null;
235       this.newAppModel.uebTopicName = null;
236       this.newAppModel.uebKey = null;
237       this.newAppModel.uebSecret = null;
238
239       /**Need to set below fields values based on input provided in the dialog */
240       this.newAppModel.restrictedApp = this.applicationObj.restrictedApp;
241       this.newAppModel.name = this.applicationObj.name;
242       this.newAppModel.url = this.applicationObj.url;
243       if(this.applicationObj.isEnabled){
244         this.newAppModel.isEnabled = this.applicationObj.isEnabled;
245       }else{
246         this.newAppModel.isEnabled = false;
247       }
248
249     }else{
250
251        /**Need to set below fields values based on input provided in the dialog */
252        this.newAppModel.restrictedApp = false;
253        this.newAppModel.name = this.applicationObj.name;
254        this.newAppModel.url = this.applicationObj.url;
255        this.newAppModel.restUrl = this.applicationObj.restUrl;
256        this.newAppModel.username = this.applicationObj.username;
257        this.newAppModel.appPassword = this.applicationObj.appPassword;
258
259        if(this.applicationObj.isEnabled){
260         this.newAppModel.isEnabled = this.applicationObj.isEnabled;
261        }else{
262         this.newAppModel.isEnabled = false;
263        }
264
265        if(this.applicationObj.isOpen){
266         this.newAppModel.isOpen = this.applicationObj.isOpen;
267        }else{
268         this.newAppModel.isOpen = false;
269        }
270        //console.log("this.applicationObj.isOpen",this.applicationObj.isOpen);
271
272        if(this.applicationObj.isCentralAuth){
273         this.newAppModel.isCentralAuth = this.applicationObj.isCentralAuth;
274        }else{
275         this.newAppModel.isCentralAuth = false;
276        }
277
278     }
279
280     if (this.applicationObj.nameSpace=="") {
281       this.newAppModel.nameSpace = null;
282     }else{
283       this.newAppModel.nameSpace = this.applicationObj.nameSpace;
284     }
285
286     if(this.isEditMode){
287       this.applicationsService.updateOnboardingApp(this.applicationObj)
288         .subscribe( _data => {
289           this.result = _data;
290           //console.log("update application response :: ",this.result);
291           if(this.result !=null && this.result.httpStatusCode ==200){
292             this.passEntry.emit(this.result);
293             this.ngbModal.dismissAll();
294           }else{
295             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);
296             return
297           }
298         }, error => {
299           console.log(error);
300           if(error.status == 409){
301             this.openConfirmationModal('Error', 'There was a problem updating the application changes. ' +
302             'The Application Name and Namespace should  be unique.  Error: ' +
303             error.status);
304             return;
305           }else if(error.status == 500){
306             this.openConfirmationModal('Error', 'There was a problem updating the application information. ' +
307             'Please try again later. Error: ' +error.status);
308             return;
309           }else if(error.status == 404 || error.status == 403){
310             this.openConfirmationModal('Error', 'There was a problem updating the application information. ' +
311             'Invalid namespace. Error: ' +error.status);
312             return;
313           }else if(error.status == 401){
314             this.openConfirmationModal('Error', 'There was a problem updating the application information. ' +
315             'Portal Mechid is unauthorized to access the given namespace. Error: ' +error.status);
316             return;
317           }else if(error.status == 400){
318             this.openConfirmationModal('Error','Bad Request Error: ' + error.status);
319             return;
320           } else{
321             this.openConfirmationModal('Error', 'There was a problem updating the application changes. ' +
322             'Please try again. If the problem persists, then try again later. Error: ' +
323             error.status);
324             return;
325           }
326       });
327
328     }else{
329       //console.log("Coming inside add application",this.newAppModel);
330
331       this.applicationsService.addOnboardingApp(this.newAppModel)
332         .subscribe( _data => {
333           this.result = _data;
334           //console.log("Add application response :: ",this.result);
335           if(this.result !=null && this.result.httpStatusCode ==200){
336             this.passEntry.emit(this.result);
337             this.ngbModal.dismissAll();
338           }else{
339             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);
340             return
341           }
342         }, error => {
343           console.log(error);
344           if(error.status == 409){
345             this.openConfirmationModal('Error', 'There was a problem adding the application changes. ' +
346             'The Application Name and URL should  be unique.  Error: ' +
347             error.status);
348             return;
349           } else if(error.status == 500){
350             this.openConfirmationModal('Error', 'There was a problem adding the application information. ' +
351             'Please try again later. Error: ' +error.status);
352             return;
353           }else if(error.status == 400){
354             this.openConfirmationModal('Error','Bad Request Error: ' + error.status);
355             return;
356           } else{
357             this.openConfirmationModal('Error', 'There was a problem adding the application changes. ' +
358             'Please try again. If the problem persists, then try again later. Error: ' +
359             error.status);
360             return;
361           }
362       });
363     }
364   }
365
366   isUrlValid(userInput){
367     //let  regexQuery = "/^((?:https?\:\/\/|ftp?\:\/\/)?(w{3}.)?(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)[^-_.]$/i";
368     let  regexQuery = "https?://.+";
369     let res = userInput.match(regexQuery);
370     if(res == null){
371       return false;
372     }else{
373       return true;
374     }
375   }
376
377   openConfirmationModal(_title: string, _message: string) {
378     const modalInfoRef = this.ngbModal.open(ConfirmationModalComponent);
379     modalInfoRef.componentInstance.title = _title;
380     modalInfoRef.componentInstance.message = _message;
381   }
382
383   openInformationModal(_title: string, _message: string){
384     const modalInfoRef = this.ngbModal.open(InformationModalComponent);
385     modalInfoRef.componentInstance.title = _title;
386     modalInfoRef.componentInstance.message = _message;
387     return modalInfoRef;
388   }
389 }