Added Widget-Onboarding and dependent Services
[portal.git] / portal-FE-common / src / app / pages / widget-onboarding / widget-details-dialog / widget-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 { IWidget } from 'src/app/shared/model/widget-onboarding/widget';
41 import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
42 import { WidgetOnboardingService, MicroserviceService, AdminsService, ApplicationsService } from 'src/app/shared/services';
43 import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
44 import { IMircroservies } from 'src/app/shared/model/microservice-onboarding/microservices';
45 import { ConfirmationModalComponent } from 'src/app/modals/confirmation-modal/confirmation-modal.component';
46 import { InformationModalComponent } from 'src/app/modals/information-modal/information-modal.component';
47
48 @Component({
49   selector: 'app-widget-details-dialog',
50   templateUrl: './widget-details-dialog.component.html',
51   styleUrls: ['./widget-details-dialog.component.scss']
52 })
53 export class WidgetDetailsDialogComponent implements OnInit {
54   @Input() public widget: IWidget;
55   @Input() public availableMicroServices: Array<IMircroservies>;
56   @Input() public applicationList: Array<Object>;
57
58   @Output() passEntry: EventEmitter<any> = new EventEmitter();
59
60   widgetsList: any;
61   uploadForm: FormGroup;
62   result: any;
63   selected: any;
64   isEditMode: boolean = false;
65   hasSelectedApp: boolean = false;
66   availableApps = [];
67   availableRoles = [];
68   allRoleSelected: boolean = false;
69   appCounter = 0;
70   duplicatedName:boolean = true;
71   widgetFileTypeError:boolean = false;
72   isFileNotSelected:boolean = true;
73
74   constructor(public widgetOnboardingService: WidgetOnboardingService, 
75     public microservice: MicroserviceService, public applicationsService: ApplicationsService,
76     public formBuilder: FormBuilder, public activeModal: NgbActiveModal, 
77     public ngbModal: NgbModal, public adminsService: AdminsService) { }
78
79   ngOnInit() {
80     this.widget.allUser = true;
81     this.getOnboardingWidgets();
82     this.getAvailableApps();
83     this.duplicatedName = true;
84     this.allRoleSelected = false;
85     this.appCounter = 0;
86     this.uploadForm = this.formBuilder.group({
87       profile: [''],
88       widgetName:[''],
89       description:[''],
90       serviceEndPoint:[''],
91       allowAllUser:[''],
92       applicationName:[''],
93       applicationRole:['']
94     });
95     
96     if(this.widget && this.widget.name){
97       this.isEditMode = true;
98     }
99     if(this.isEditMode && this.widget && this.widget.allowAllUser == "Y"){
100       this.widget.allUser = true;
101     }else if(this.isEditMode && this.widget && this.widget.allowAllUser == "N"){
102       this.widget.allUser = false;
103     }
104     if(this.widget && this.widget.serviceId != null){
105       this.widget.serviceURL = this.widget.serviceId;
106     }
107   }
108
109   //Add Or Update Widget.
110   saveChanges(){
111     if(this.widget.name == '' || this.widget.name == undefined){
112       this.openConfirmationModal("Error",'Widget Name is required.');
113       return;
114     }
115
116     if(!this.isEditMode){
117       this.updateWidgetName();
118     }
119
120     if(this.duplicatedName == false){
121       this.openConfirmationModal("Error",'Name not available - please choose different name.');
122       return;
123     }
124
125     if(this.widgetFileTypeError == true){
126       this.openConfirmationModal("Error",'File must be .zip');
127       return;
128     }
129
130     let widgetName = this.widget.name;
131     let description = this.widget.desc
132     let file_loc = widgetName + ".zip";
133     const formData = new FormData();
134     formData.append('file', this.uploadForm.get('profile').value);
135     //console.log("FormData >>>>::> ",formData.get('file'));
136
137     /*if((formData == undefined && !this.isEditMode) ||
138       (!this.widget.allUser && this.appCounter == 0) ||
139       this.widget.name == null ||
140       (!this.widget.allUser && !this.allRoleSelected)){
141         console.log("return from 2nd check");
142         return; 
143     }*/
144     
145     let selectedRoles = [];
146
147     if(!this.widget.allUser){
148       for(var i = 0; i < this.availableApps.length; i++){
149         if(this.availableApps[i].isSelected){
150           for(var n = 0; n < this.availableApps[i].roles.length; n++) {
151             if(this.availableApps[i].roles[n].isSelected){
152               var role = {
153                     app: {appId: this.availableApps[i].id},
154                     roleId: this.availableApps[i].roles[n].id,
155                     roleName: this.availableApps[i].roles[n].name,
156                 };
157               selectedRoles.push(role);
158             }
159           }
160         }
161       }
162     }
163
164     let allowAllUser = 0;
165     if(this.widget.allUser){
166       allowAllUser = 1;
167     }
168
169     let serviceId = null;
170     if(this.widget.serviceURL != null &&   this.widget.serviceURL != undefined){
171         serviceId = parseInt(this.widget.serviceURL);
172     }
173     var newWidget = {
174         name: widgetName,
175         desc: description,
176         widgetRoles: selectedRoles,
177         fileLocation: file_loc,
178         allowAllUser: allowAllUser,
179         serviceId: serviceId
180     };
181
182     if(this.isEditMode){
183       //console.log("widget in updateWidget :::: >>> ",newWidget);
184       if(formData && formData.get('file')){
185         this.widgetOnboardingService.updateWidgetWithFile(formData, this.widget.id, newWidget)
186           .subscribe( _data => {
187             this.result = 'updated';
188             this.passEntry.emit(this.result);
189           }, error => {
190             console.log(error);
191             this.openConfirmationModal("Error",'Could not update. Please retry.');
192         });
193       }else{
194         this.widgetOnboardingService.updateWidget(this.widget.id, newWidget)
195           .subscribe( _data => {
196             this.result = 'updated';
197             this.passEntry.emit(this.result);
198           }, error => {
199             this.openConfirmationModal("Error",'Could not update. Please retry.');
200             console.log(error);
201         });
202       }
203     }else{
204       //console.log("newWidget in createWidget :::: >>> ",newWidget);
205       this.widgetOnboardingService.createWidget(newWidget, formData)
206         .subscribe( _data => {
207           this.result = 'created';
208           this.passEntry.emit(this.result);
209         }, error => {
210           this.openConfirmationModal("Error",'Could not save. Please retry.');
211           console.log(error);
212       });
213     }
214     this.ngbModal.dismissAll();
215   }
216
217   onFileSelect(event) {
218     this.widgetFileTypeError = false;
219     this.isFileNotSelected = false;
220     if (event.target.files.length > 0) {
221       const file = event.target.files[0];
222       //console.log("onFileSelect called.. ",file);
223       var fileName = file.name;
224       var validFormats = ['zip'];
225       var ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
226       if(validFormats.indexOf(ext) == -1){
227         this.widgetFileTypeError = true;
228       }
229       this.uploadForm.get('profile').setValue(file);
230     }
231   }
232
233   appUpdate(){
234     this.hasSelectedApp = false;
235     this.appCounter = 0;
236     for(var i = 0; i < this.availableApps.length; i++){
237       if(this.availableApps[i].isSelected){
238         this.appCounter++;
239         if(!this.hasSelectedApp)
240           this.hasSelectedApp = true;
241       }
242       if(this.availableApps[i].isSelected
243       && this.availableApps[i].roles.length == 0){
244         var index = i;
245         this.availableRoles = [];    
246         this.adminsService.getRolesByApp(this.availableApps[i].id)
247         .subscribe( roles => {
248           if(roles && roles.length >0){
249             for(var i = 0; i < roles.length; i++){
250               this.availableRoles.push({
251                 id: roles[i].id,
252                       name: roles[i].name,
253                       isSelected: false,
254               }); 
255             }
256           }
257           this.availableApps[index].roles = this.availableRoles;
258         }, error => {
259           console.log(error);
260         });
261       }
262     }
263     this.allRoleSelected = true;
264     this.checkRoleSelected();
265   }
266
267   roleUpdate(app){
268     this.allRoleSelected = true;
269       for(var i = 0; i < app.roles.length; i++){
270         if(app.roles[i].isSelected){
271           app.roleSelected = true;
272           this.checkRoleSelected();
273           return;
274         }
275       }
276     app.roleSelected = false;
277     this.checkRoleSelected();
278   }
279     
280   checkRoleSelected(){
281     for(var i = 0; i < this.availableApps.length; i++){
282       if(this.availableApps[i].isSelected
283       && !this.availableApps[i].roleSelected){
284         this.allRoleSelected = false;
285         return;
286       }
287     }
288   }
289
290   getAppName = function(appId){
291     for(var i = 0; i < this.availableApps.length; i++){
292       if(this.availableApps[i].id == appId){
293         return this.availableApps[i].name;
294       }
295     }
296   }
297
298   updateWidgetName(){
299     for(var i = 0; i < this.widgetsList.length; i++){
300       if(this.widget.name && this.widget.name.toUpperCase() == this.widgetsList[i].name.toUpperCase()){
301         this.duplicatedName = false;
302         return;
303       }
304     }
305     this.duplicatedName = true;
306   }
307
308   getOnboardingWidgets(){
309     this.widgetOnboardingService.getManagedWidgets()
310       .subscribe(_data => {
311           this.result = _data
312           if(!(_data instanceof Array)){
313            return;
314           }
315           if (this.result == null || this.result == 'undefined') {
316               console.log('WidgetOnboardingService::getOnboardingWidgets Failed: Result or result.data is null');
317           }else {
318             this.widgetsList = _data;
319         }
320       }, error =>{
321         console.log(error);
322     });
323   }
324
325   getAvailableApps(){
326     if(this.isEditMode == false){       
327       this.availableApps=[];
328       this.applicationsService.getAppsForSuperAdminAndAccountAdmin()
329         .subscribe(apps => {
330           this.availableApps=[];
331           for(var i=0;i<apps.length;i++) {
332             if (!apps[i].restrictedApp) {
333               this.availableApps.push({
334                   id: apps[i].id,
335                   name: apps[i].name,
336                   roles: [],
337                   roleSelected: false,
338                   isSelected: false,
339               });
340           }
341         }
342         }, error =>{
343           console.log(error);
344       });
345     }else if(this.isEditMode == true){
346       if(this.widget.allowAllUser == "Y"){
347         this.widget.allUser = true;
348       }
349       this.applicationsService.getAppsForSuperAdminAndAccountAdmin()
350       .subscribe(apps => {
351         this.availableApps=[];
352         let selectedApps = {};
353         var availableApps = this.availableApps;  
354         this.allRoleSelected = true;
355         for(var i=0; i < this.widget.widgetRoles.length; i++){
356           if(selectedApps[this.widget.widgetRoles[i].app.appId] != undefined)
357             selectedApps[this.widget.widgetRoles[i].app.appId] += this.widget.widgetRoles[i].roleId + ";" + this.widget.widgetRoles[i].roleName + ";"; 
358           else{
359             selectedApps[this.widget.widgetRoles[i].app.appId] = this.widget.widgetRoles[i].roleId + ";" + this.widget.widgetRoles[i].roleName + ";";                   
360             this.appCounter++;
361           }
362         }                       
363         apps.forEach(function(app, index){
364             availableApps.push({
365               id: app.id,
366               name: app.name,
367               roles: [],
368               roleSelected: false,
369               isSelected: false,
370             });
371             if(selectedApps[app.id] != undefined){
372               this.adminsService.getRolesByApp(app.id)
373               .subscribe(roles => {
374                 var role = selectedApps[app.id].split(';');
375                 var selectedRoles = [];
376                 var n = 0;
377                 while((n+1) < role.length){
378                     selectedRoles.push({
379                         id: role[n++],
380                         name: role[n++],
381                         isSelected: true,
382                     });
383                 }                                       
384                 for(var m = 0; m < roles.length; m++){
385                   var hasSelected = true;
386                   for(var n = 0; n < selectedRoles.length; n++){
387                     if(selectedRoles[n].id == roles[m].id){
388                       hasSelected = false;
389                       break;
390                     }
391                   }
392                   if(hasSelected){
393                     selectedRoles.push({
394                       id: roles[m].id,
395                       name: roles[m].name,
396                       isSelected: false,
397                     }); 
398                   }        
399                 }  
400                 availableApps[index].roleSelected = true;
401                 availableApps[index].isSelected = true;
402                 availableApps[index].roles = selectedRoles;
403               }, error =>{
404                   console.log(error);
405               });
406             }
407         })
408       
409       }, error =>{
410         console.log(error);
411       });
412     }
413     //console.log("this.availableApps :: ",this.availableApps);
414   }
415
416   openConfirmationModal(_title: string, _message: string) {
417     const modalInfoRef = this.ngbModal.open(ConfirmationModalComponent);
418     modalInfoRef.componentInstance.title = _title;
419     modalInfoRef.componentInstance.message = _message;
420   }
421
422   openInformationModal(_title: string, _message: string){
423     const modalInfoRef = this.ngbModal.open(InformationModalComponent);
424     modalInfoRef.componentInstance.title = _title;
425     modalInfoRef.componentInstance.message = _message;
426     return modalInfoRef;
427   }
428   
429 }