Added Widget-Onboarding and dependent Services
[portal.git] / portal-FE-common / src / app / pages / widget-onboarding / widget-onboarding.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, ViewChild, Input, ChangeDetectionStrategy } from '@angular/core';
40 import { MatTableDataSource } from '@angular/material';
41 import { MatSort, MatPaginator } from '@angular/material';
42 import { WidgetOnboardingService, MicroserviceService } from '../../shared/services/index';
43 import { IMircroservies } from 'src/app/shared/model/microservice-onboarding/microservices';
44 import { IWidget } from 'src/app/shared/model/widget-onboarding/widget';
45 import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
46 import { HttpClient } from '@angular/common/http';
47 import { WidgetDetailsDialogComponent } from './widget-details-dialog/widget-details-dialog.component';
48 import { ConfirmationModalComponent } from 'src/app/modals/confirmation-modal/confirmation-modal.component';
49 import { InformationModalComponent } from 'src/app/modals/information-modal/information-modal.component';
50
51 @Component({
52   changeDetection: ChangeDetectionStrategy.OnPush,
53   selector: 'app-widget-onboarding',
54   templateUrl: './widget-onboarding.component.html',
55   styleUrls: ['./widget-onboarding.component.scss']
56 })
57 export class WidgetOnboardingComponent implements OnInit {
58
59   widgetsList: Array<IWidget> = [];
60   applicationList: Array<Object> = [];
61   availableMicroServices: Array<IMircroservies> = [];
62   displayedColumns: string[] = ['widgetName', 'application', 'download','delete'];
63   isCommError: boolean = false;
64   dataSource = new MatTableDataSource(this.widgetsList);
65   @ViewChild(MatSort) sort: MatSort;
66   @ViewChild(MatPaginator) paginator: MatPaginator;
67  
68   isEditMode: boolean = false;
69   result: any;
70   
71
72   constructor( public widgetOnboardingService: WidgetOnboardingService, 
73     public microservice: MicroserviceService,public ngbModal: NgbModal) { }
74
75   ngOnInit() {
76     this.prepareApplicationRoleName();
77     this.getOnboardingWidgets();
78     this.populateAvailableApps();
79     this.getAvailableMicroServices();  
80   }
81
82   getOnboardingWidgets(){
83     this.isCommError = false;
84     this.widgetOnboardingService.getManagedWidgets()
85       .subscribe(_data => {
86           this.result = _data
87           if(!(_data instanceof Array)){
88             this.isCommError = true;
89             return;
90           }
91           //console.log("getOnboardingWidgets Data :: ", _data);
92           if (this.result == null || this.result == 'undefined') {
93               console.log('WidgetOnboardingService::getOnboardingWidgets Failed: Result or result.data is null');
94           }else {
95             let reSortedWidget = _data.sort(this.getSortOrder("name"));
96             this.widgetsList = reSortedWidget;
97             this.prepareApplicationRoleName();
98             this.populateTableData(this.widgetsList);
99         }
100       }, error =>{
101         console.log(error);
102     });
103   }
104
105   //Refactor this into a directive
106   getSortOrder(prop){
107     return function(a, b) {
108         if (a[prop].toLowerCase() > b[prop].toLowerCase()) {
109             return 1;
110         } else if (a[prop].toLowerCase() < b[prop].toLowerCase()) {
111             return -1;
112         }
113         return 0;
114     }
115   }
116
117   removeWidget(widget: IWidget) {
118     let confirmationMsg = 'You are about to delete this Widget : ' + widget.name+ '. Click OK to continue.';
119     this.openInformationModal("Confirmation",confirmationMsg).result.then((result) => {
120       if (result === 'Ok') {
121         if(!widget || widget == null){
122           console.log('WidgetOnboardingCtrl::deleteService: No widget or ID... cannot delete');
123           return;
124         }
125         
126         this.widgetsList.splice(this.widgetsList.indexOf(widget), 1);
127         
128         this.widgetOnboardingService.deleteWidget(widget.id)
129           .subscribe( _data => {
130             this.result = _data;
131             this.openConfirmationModal("Success",'Widget deleted successfully');
132           }, error => {
133             console.log(error);
134         }); 
135     
136         this.populateTableData(this.widgetsList);
137       }
138     }, (resut) => {
139       this.openConfirmationModal('Error', resut);
140       return;
141     })
142   }
143
144   
145   openAddWigetModal(rowData:any){
146       //console.log("openAddWigetModal getting called...");
147       const modalRef = this.ngbModal.open(WidgetDetailsDialogComponent, { size: 'lg' });
148       modalRef.componentInstance.widget = rowData;
149       modalRef.componentInstance.availableMicroServices = this.availableMicroServices;
150       modalRef.componentInstance.applicationList = this.applicationList;
151       modalRef.componentInstance.widgetsList = this.widgetsList;
152       if(rowData != 'undefined' && rowData){
153         this.isEditMode = true;
154       }else{
155         modalRef.componentInstance.widget = {};
156         this.isEditMode = false;
157       }
158       modalRef.componentInstance.passEntry.subscribe((receivedEntry: any) => {
159         //console.log("receivedEntry >>> ",receivedEntry);
160         if(receivedEntry){
161           this.widgetsList = [];
162           this.getOnboardingWidgets();
163         }
164       });
165   }
166
167   applyFilter(filterValue: string) {
168     this.dataSource.filter = filterValue.trim().toLowerCase();
169   }
170
171   applyAppFilter(event) {
172     let filterByApp = event.title;
173     if(filterByApp == 'All Applications'){
174       this.getOnboardingWidgets();
175     }else{
176       this.dataSource.filter = filterByApp.trim().toLowerCase();
177     }
178   }
179
180   downloadWidget(widget){
181     this.widgetOnboardingService.downloadWidgetFile(widget.id)
182       .subscribe(res => {
183         var data = res;
184         //console.log("downloadWidgetFile response :: ",data);
185         var filename = widget.name + ".zip";    
186         if (data == undefined || data == null){
187           this.openConfirmationModal("Could not download. Please retry.", '');
188           return;               
189         }
190         var a = document.createElement('a');
191         var blob = new Blob([data], {type: 'application/octet-stream'});
192         var url = window.URL.createObjectURL(blob);
193         a.href = url;
194         a.download = filename;
195         document.body.appendChild(a);
196         a.click();
197         
198         setTimeout(function(){
199           document.body.removeChild(a);
200           window.URL.revokeObjectURL(url);  
201         }, 100);  
202     
203     }, error =>{
204       console.log(error);
205       this.openConfirmationModal("Could not download. Please retry.", error.message);
206     });
207   }
208
209   
210   populateTableData(wigetList: Array<IWidget>){
211     this.dataSource = new MatTableDataSource(wigetList);
212     this.dataSource.sort = this.sort;
213     this.dataSource.paginator = this.paginator;
214   };
215
216   prepareApplicationRoleName(){
217     if(this.widgetsList && this.widgetsList.length > 0){
218       for(var i = 0; i < this.widgetsList.length; i++){
219         let set = new Set();
220         var info = "";
221         var appContent = [];
222         var appName = [];       
223         if(this.widgetsList[i].widgetRoles && this.widgetsList[i].widgetRoles.length >0){
224           for(var n = 0; n < this.widgetsList[i].widgetRoles.length; n++){
225             if(this.widgetsList[i].widgetRoles[n].app)
226             set.add(this.widgetsList[i].widgetRoles[n].app.appName);
227           }
228           set.forEach(function (item) {
229             info = item.toString() + " - ";
230             for(var n = 0; n < this.widgetsList[i].widgetRoles.length; n++){
231               if(this.widgetsList[i].widgetRoles[n].app && item.toString() == this.widgetsList[i].widgetRoles[n].app.appName){
232                   info += this.widgetsList[i].widgetRoles[n].roleName + "; ";
233               }
234             }
235             appContent.push(info);
236             appName.push(item.toString());
237           }.bind(this));
238         }
239         if(this.widgetsList[i].allowAllUser == "Y"){
240           info = "All Applications";
241           appContent.push("All Applications");
242           appName.push("All Applications");
243         }
244         this.widgetsList[i].appContent = appContent;
245         this.widgetsList[i].appName = appName;
246       }
247     }
248   }
249
250   populateAvailableApps(){
251     this.widgetOnboardingService.populateAvailableApps()
252       .subscribe( _data => {
253         this.applicationList.push({
254           index: 0,
255           title: 'All Applications',
256           value: ''
257         })
258         var reSortedApp = _data.sort(this.getSortOrder("name"));
259         var realAppIndex = 1;
260         for (let i = 1; i <= reSortedApp.length; i++) {
261             if (!reSortedApp[i-1].restrictedApp) {
262                 if(_data[i - 1].name && _data[i - 1].name!=""){
263                   this.applicationList.push({
264                       index: realAppIndex,
265                       title: _data[i - 1].name,
266                       value: _data[i - 1].id
267                   })
268                 }
269                 realAppIndex = realAppIndex + 1;
270             }
271         }
272       }, error => {
273         console.log(error);
274     }); 
275   }
276
277   getAvailableMicroServices = () =>{
278     this.availableMicroServices = [];
279     this.microservice.getServiceList()
280     .subscribe(_data => {
281         this.result = _data;
282         if (this.result == null || this.result == 'undefined') {
283              console.log('MicroserviceService::getAvailableMicroServices Failed: Result or result.data is null');
284         }else {
285           for(var i = 0; i < _data.length; i++){
286             this.availableMicroServices.push({
287               id: _data[i].id,
288               name: _data[i].name,
289               option: _data[i].name + ": " + _data[i].url
290             });
291           }
292         }
293     }, error =>{
294       console.log(error);
295     });
296   }
297
298   openConfirmationModal(_title: string, _message: string) {
299     const modalInfoRef = this.ngbModal.open(ConfirmationModalComponent);
300     modalInfoRef.componentInstance.title = _title;
301     modalInfoRef.componentInstance.message = _message;
302   }
303
304   openInformationModal(_title: string, _message: string){
305     const modalInfoRef = this.ngbModal.open(InformationModalComponent);
306     modalInfoRef.componentInstance.title = _title;
307     modalInfoRef.componentInstance.message = _message;
308     return modalInfoRef;
309   }
310
311 }