CADI AAF Integration and merging the code
[portal.git] / ecomp-portal-FE-common / client / app / views / widget-onboarding / widget-details-dialog / widget-details.controller.js
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 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 'use strict';
39 (function () {
40     class WidgetOnboardingDetailsModalCtrl {
41         constructor($scope, $timeout, $log, $interval, applicationsService, adminsService, microserviceService, widgetsCatalogService, errorMessageByCode, ECOMP_URL_REGEX, $window,userProfileService, confirmBoxService, $cookies,items) {
42             
43             this.appUpdate = function(){
44                 this.hasSelectedApp = false;
45                 this.appCounter = 0;
46                 for(var i = 0; i < this.availableApps.length; i++){
47                         if(this.availableApps[i].isSelected){
48                                 this.appCounter++;
49                                 if(!this.hasSelectedApp)
50                                         this.hasSelectedApp = true;
51                         }
52                         if(this.availableApps[i].isSelected
53                         && this.availableApps[i].roles.length == 0){
54                                 var index = i;
55                                 this.availableRoles = [];    
56                                 adminsService.getRolesByApp(this.availableApps[i].id).then(roles => {
57                                            for(var i = 0; i < roles.length; i++){
58                                                    this.availableRoles.push({
59                                                            id: roles[i].id,
60                                                    name: roles[i].name,
61                                                    isSelected: false,
62                                                    }); 
63                                            }
64                                            this.availableApps[index].roles = this.availableRoles;
65                                 });
66                         }
67                             }
68                 this.allRoleSelected = true;
69                 this.checkRoleSelected();
70             }
71             
72             this.roleUpdate = function(app){
73                         this.allRoleSelected = true;
74                 for(var i = 0; i < app.roles.length; i++){
75                         if(app.roles[i].isSelected){
76                                 app.roleSelected = true;
77                                 this.checkRoleSelected();
78                                 return;
79                         }
80                 }
81                         app.roleSelected = false;
82                         this.checkRoleSelected();
83             }
84             
85             this.checkRoleSelected = function(){
86                 for(var i = 0; i < this.availableApps.length; i++){
87                         if(this.availableApps[i].isSelected
88                         && !this.availableApps[i].roleSelected){
89                                 this.allRoleSelected = false;
90                                 return;
91                         }
92                 }
93             }
94                    
95             this.getAppName = function(appId){
96                  for(var i = 0; i < this.availableApps.length; i++){
97                          if(this.availableApps[i].id == appId){
98                                  return this.availableApps[i].name;
99                          }
100                  }
101             }
102             
103             let newWidgetModel = {
104                 name: null,
105                 roleId: null,
106                 roleName: null,
107                 appId: null,
108                 appName: null,
109                 url: null,
110                 showAppOptions: false,
111                 showRoleOptions: false,
112                 hasSelectedApp: false
113             };
114           
115             let getAvailableApps = () => {              
116                 
117                 if(this.isEditMode == false){   
118                         applicationsService.getAppsForSuperAdminAndAccountAdmin().then(apps => {
119                                 this.availableApps=[];
120                                 for(var i=0;i<apps.length;i++) {
121                                 if (!apps[i].restrictedApp) {
122                             this.availableApps.push({
123                                 id: apps[i].id,
124                                 name: apps[i].name,
125                                 roles: [],
126                                 roleSelected: false,
127                                 isSelected: false,
128                             });
129                                 }
130                             }
131                         }).catch(err => {
132                             $log.error(err);
133                         });
134                 }
135                 else if(this.isEditMode == true){
136                         if(this.widget.allowAllUser == "Y")
137                                 this.widget.allUser = true;
138                         applicationsService.getAppsForSuperAdminAndAccountAdmin().then(apps => {
139                                 this.availableApps=[];
140                                 let selectedApps = {};
141                                 var availableApps = this.availableApps;  
142                                 this.allRoleSelected = true;
143                                 for(var i=0; i < this.widget.widgetRoles.length; i++){
144                                         if(selectedApps[this.widget.widgetRoles[i].app.appId] != undefined)
145                                                 selectedApps[this.widget.widgetRoles[i].app.appId] += this.widget.widgetRoles[i].roleId + ";" + this.widget.widgetRoles[i].roleName + ";"; 
146                                         else{
147                                                 selectedApps[this.widget.widgetRoles[i].app.appId] = this.widget.widgetRoles[i].roleId + ";" + this.widget.widgetRoles[i].roleName + ";";                       
148                                                 this.appCounter++;
149                                         }
150                                 }                       
151                                 apps.forEach(function(app, index){
152                                                 availableApps.push({
153                                        id: app.id,
154                                        name: app.name,
155                                        roles: [],
156                                        roleSelected: false,
157                                        isSelected: false,
158                                                 });
159                                                 if(selectedApps[app.id] != undefined){
160                                                         adminsService.getRolesByApp(app.id).then(roles => {
161                                                         var role = selectedApps[app.id].split(';');
162                                                 var selectedRoles = [];
163                                                 var n = 0;
164                                                 while((n+1) < role.length){
165                                                         selectedRoles.push({
166                                                                            id: role[n++],
167                                                                    name: role[n++],
168                                                                    isSelected: true,
169                                                                 });
170                                                 }                                       
171                                                         for(var m = 0; m < roles.length; m++){
172                                                                 var hasSelected = true;
173                                                                 for(var n = 0; n < selectedRoles.length; n++){
174                                                                         if(selectedRoles[n].id == roles[m].id){
175                                                                                 hasSelected = false;
176                                                                                 break;
177                                                                         }
178                                                                 }
179                                                                 if(hasSelected){
180                                                                    selectedRoles.push({
181                                                                            id: roles[m].id,
182                                                                    name: roles[m].name,
183                                                                    isSelected: false,
184                                                                    }); 
185                                                                 }          
186                                                         }  
187                                                         availableApps[index].roleSelected = true;
188                                                         availableApps[index].isSelected = true;
189                                                         availableApps[index].roles = selectedRoles;
190                                                         });
191                                                 }
192                                 })
193                         })
194                 }
195             };
196             
197             let getAvailableServices = () =>{
198                 microserviceService.getServiceList().then(services => {
199                         this.availableServices = [];
200                         for(var i = 0; i < services.length; i++){
201                                 this.availableServices.push({
202                                         id: services[i].id,
203                                         name: services[i].name,
204                                         option: services[i].name + ": " + services[i].url
205                                 });
206                                 
207                                 if(this.widget.serviceId != null && this.widget.serviceId == services[i].id){
208                                         this.widget.serviceURL = this.availableServices[i];
209                                 }
210                         }
211                 }).catch(err => {
212                    $log.error(err);
213                 });
214             }
215             
216
217             let init = () => {
218                 $log.info('WidgetOnboardingDetailsModalCtrl::init');
219                 this.widgetsList = [];
220                 this.duplicatedName = true;
221                 this.allRoleSelected = false;
222                 this.appCounter = 0;
223                 this.isSaving = false;
224                 this.allUser = false;
225                 this.emptyWidgetName = false;
226                 
227                 if (items && items.widget) {
228                     this.isEditMode = true;
229                         this.allRoleSelected = true;
230                     this.widget = _.clone(items.widget);
231                 } else {
232                     this.isEditMode = false;
233                     this.widget = _.clone(newWidgetModel);
234                 }
235                 
236                 widgetsCatalogService.getManagedWidgets().then(res => {
237                         for(var i = 0; i < res.length; i++){
238                                 this.widgetsList.push(res[i].name);
239                         }
240                  }).catch(err => {
241                      $log.error('WidgetOnboardingDetailsModalCtrl::init error: ' + err);
242                  }).finally(()=> {
243                      this.isLoadingTable = false;
244                  });
245                 
246                 widgetsCatalogService.getUploadFlag().then(res => {
247                         this.uploadFlag=res;
248                  }).catch(err => {
249                      $log.error('WidgetOnboardingDetailsModalCtrl::init error: ' + err);
250                  }).finally(()=> {
251                  });
252                 
253                  getAvailableApps();
254                  getAvailableServices();
255             };
256             this.ECOMP_URL_REGEX = ECOMP_URL_REGEX;
257             this.conflictMessages = {};
258             this.scrollApi = {};
259
260             let resetConflict = fieldName => {
261                 delete this.conflictMessages[fieldName];
262                 if($scope.widgetForm[fieldName]){
263                     $scope.widgetForm[fieldName].$setValidity('conflict', true);
264                 }
265             };
266             
267             this.updateSelectedRole = () => {
268                 if (!this.selectedRole) {
269                     return;
270                 }
271                 this.widget.RoleId = this.selectedRole.id;
272                 this.widget.RoleName = this.selectedRole.name;
273             };
274             
275             let emptyCookies = () => {
276                 userProfileService.getUserProfile()
277                 .then(profile=> {
278                     $log.info('AppDetailsModalCtrl::emptyCookies profile: ', profile);
279                     $scope.orgUserId = profile.orgUserId;
280                     $log.info('user has the following orgUserId: ' + profile.orgUserId);
281                     if ($cookies.getObject($scope.orgUserId + '_widget') != undefined && $cookies.getObject($scope.orgUserId + '_widget') != null) {
282                         $cookies.remove($scope.orgUserId + '_widget');
283                     }
284                 });
285             };
286               
287             this.updateWidgetName = () => {
288                 for(var i = 0; i < this.widgetsList.length; i++){
289                         if(this.widget.name.toUpperCase() == this.widgetsList[i].toUpperCase()){
290                                 this.duplicatedName = false;
291                                 return;
292                         }
293                 }
294                 this.duplicatedName = true;
295             };
296             
297             this.saveChanges = () => {     
298                 
299                 if(!this.isEditMode)
300                         this.updateWidgetName();
301                 
302                 if(this.duplicatedName == false 
303                    || this.widget.name == ''
304                    || this.widget.name == undefined){
305                         this.emptyWidgetName = true;
306                         return;
307                 }
308                 
309                 if((this.widget.file == undefined && !this.isEditMode) ||
310                 (!this.widget.allUser && this.appCounter == 0) ||
311                 this.widget.name == null ||
312                 (!this.widget.allUser && !this.allRoleSelected) ||
313                 this.widget.saving == true)
314                         return; 
315                 
316                 
317                         this.widget.saving = true;
318                 var selectedRoles = [];
319                 if(!this.widget.allUser){
320                         for(var i = 0; i < this.availableApps.length; i++){
321                                 if(this.availableApps[i].isSelected){
322                                                 for(var n = 0; n < this.availableApps[i].roles.length; n++) {
323                                                         if(this.availableApps[i].roles[n].isSelected){
324                                                         var role = {
325                                                                 app: {
326                                                                         appId: this.availableApps[i].id
327                                                                 },
328                                                                 roleId: this.availableApps[i].roles[n].id,
329                                                                 roleName: this.availableApps[i].roles[n].name,
330                                                                 };
331                                                         selectedRoles.push(role);
332                                                         }
333                                         }
334                                 }
335                         }
336                 }
337                 
338                 var allowAllUser = 0;
339                 if(this.widget.allUser)
340                         allowAllUser = 1;       
341                 
342                 var serviceId = null;
343                 if(this.widget.serviceURL != null &&
344                 this.widget.serviceURL != undefined){
345                         serviceId = parseInt(this.widget.serviceURL);
346                 }
347                 
348                 
349                 var file_loc = this.widget.name + ".zip";
350                 var newWidget = {
351                                 name: this.widget.name,
352                                 desc: this.widget.desc,
353                                 widgetRoles: selectedRoles,
354                                 fileLocation: file_loc,
355                                 allowAllUser: allowAllUser,
356                                 serviceId: serviceId
357                 };
358                 
359                 if(this.isEditMode){
360                         
361                         if(this.widget.file != undefined){
362                                 widgetsCatalogService.updateWidgetWithFile(this.widget.file, this.widget.id, newWidget).then(res => {
363                                         if(!res.valid){
364                                                 if(!res.error){
365                                                         confirmBoxService.showInformation("Could not save. Please retry.");
366                                                         this.widget.saving = false;
367                                                         return;
368                                                 }
369                                                 confirmBoxService.showInformation(res.error);
370                                                 this.widget.saving = false;
371                                                 return;
372                                         }
373                                         $scope.$dismiss('cancel');
374                                 this.widget.saving = false;
375                                 });     
376                         }
377                         else{
378                                 widgetsCatalogService.updateWidget(this.widget.id, newWidget)
379                                 .then(() => {
380                                         $scope.$dismiss('cancel');
381
382                             });
383                         }
384                 }
385                 else{
386                         widgetsCatalogService.createWidget(newWidget, this.widget.file).then(res => {
387                                 if(!res.valid){
388                                                 if(!res.error)
389                                                         confirmBoxService.showInformation("Could not save. Please retry.");
390                                                 else
391                                                         confirmBoxService.showInformation(res.error);
392                                                 this.widget.saving = false;
393                                                 return;
394                                         }
395                                         $scope.$dismiss('cancel');
396
397                                 this.widget.saving = false;
398                         });
399                 }
400             };
401             // Caches the file name supplied by the event handler.
402                 $scope.widgetFileHandler = (event, files) => {
403                         if(files[0]){
404                                 var fileName = files[0].name;
405                     var validFormats = ['zip'];
406                     //Get file extension
407                     var ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase(); 
408                     //Check for valid format
409                     if(validFormats.indexOf(ext) == -1){
410                         document.getElementById('widget-onboarding-details-upload-file').value = null;
411                         $scope.widgetFileTypeError=true;
412                         $timeout(function(){
413                                 $scope.widgetFileTypeError=false;
414                         }, 5000);
415                     }
416                         }
417                 }; // file change handler
418                 
419             init();
420             $scope.$on('$stateChangeStart', e => {
421                 e.preventDefault();
422             });
423         }
424     }
425     WidgetOnboardingDetailsModalCtrl.$inject = ['$scope', '$timeout', '$log', '$interval', 'applicationsService', 'adminsService', 'microserviceService', 'widgetsCatalogService', 'errorMessageByCode', 'ECOMP_URL_REGEX', '$window','userProfileService', 'confirmBoxService', '$cookies','items'];
426     angular.module('ecompApp').controller('WidgetOnboardingDetailsModalCtrl', WidgetOnboardingDetailsModalCtrl);
427     
428     angular.module('ecompApp').directive('fileChange', ['$parse', function($parse){
429         return {
430                 require: 'ngModel',
431             restrict: 'A',
432             link : function($scope, element, attrs, ngModel) {
433                 var attrHandler = $parse(attrs['fileChange']);
434                 var handler=function(e) {
435                         $scope.$apply(function() {
436                                 attrHandler($scope, { $event:e, files:e.target.files } );
437                         });
438                 };
439                 element[0].addEventListener('change',handler,false);
440            }
441         }
442     }]);
443 })();