33aafe8923decf7aa0dba1366764d631342334c2
[portal.git] / ecomp-portal-FE-common / client / app / views / users / users.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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 'use strict';
39 (function () {
40     class UsersCtrl {
41         constructor($log, applicationsService, usersService, confirmBoxService, $scope, ngDialog,$modal) {
42             this.$log = $log;
43             $scope.adminAppsIsNull = false;
44             $scope.appsIsDown = false;
45             $scope.noUsersInApp = false;
46             $scope.multiAppAdmin = false;
47             $scope.syncRolesApplied = false;
48
49             $log.info('UsersCtrl:: initializing...');
50             /**
51              * Handle all active HTTP requests
52              * activeRequests @type {Array[requests with cancel option]}
53              */
54             let activeRequests = [];
55             let clearReq = (req) => {
56                 activeRequests.splice(activeRequests.indexOf(req), 1);
57             };
58
59             let init = () => {
60                 $scope.app = {
61                         appId : ''      
62                 };
63                 this.isLoadingTable = false;
64                 this.selectedApp = null;
65                 this.isAppSelectDisabled = false;
66                 this.selectApp = 'Select Application';
67                 this.adminApps = [{index: 0, id: 0, value: this.selectApp, title: this.selectApp}];
68                 getAdminApps();
69
70                 /*Table general configuration params*/
71                 this.searchString = '';
72                 /*Table data*/
73                 this.usersTableHeaders = ['First Name', 'Last Name', 'User ID', 'Roles'];
74                 this.accountUsers = [];
75             };
76
77             let getAdminApps = () => {
78                 $log.debug('UsersCtrl::getAdminApps: - Starting getAdminApps');
79                 try {
80                     this.isLoadingTable = true;
81                     let adminAppsReq = applicationsService.getAdminApps();
82                     adminAppsReq.promise().then(apps => {
83                         if (!apps || !apps.length) {
84                             $log.error('UsersCtrl::getAdminApps:  - no apps found');
85                             return null;
86                         }
87                         $log.debug('UsersCtrl::getAdminApps: Apps for this user are: ' + JSON.stringify(apps));
88                         if (apps.length >= 2) {
89                             $log.info('UsersCtrl::getAdminApps:  - more than one app for this admin:', apps.length, ' apps');
90                             $scope.multiAppAdmin = true;
91                         } else {
92                             this.adminApps = [] ;
93                         }
94                         let sortedApps = apps.sort(getSortOrder("name"));
95                         let realAppIndex = 1;
96                         for(let i=1; i<=sortedApps.length; i++){
97                             this.adminApps.push({
98                                 index: realAppIndex,
99                                 id: sortedApps[i - 1].id,
100                                 value: sortedApps[i - 1].name,
101                                 title: sortedApps[i - 1].name
102                             });
103                             realAppIndex = realAppIndex + 1;
104                         }
105
106                         $log.debug('UsersCtrl::getAdminApps: Apps for this user are: ' + JSON.stringify(this.adminApps));
107
108                         this.selectedApp = this.adminApps[0];
109                         clearReq(adminAppsReq);
110                         $scope.adminAppsIsNull = false;
111                         }).catch(e => {
112                             $scope.adminAppsIsNull = true;
113                             $log.error('UsersCtrl::getAdminApps:  - getAdminApps() failed = '+ e.message);
114                             clearReq(adminAppsReq);
115                             confirmBoxService.showInformation('There was a problem retrieving the applications. ' +
116                                 'Please try again later.').then(isConfirmed => {});
117
118                     }).finally(() => {
119                             this.isLoadingTable = false;
120                         });
121                     } catch (e) {
122                         $scope.adminAppsIsNull = true;
123                         $log.error('UsersCtrl::getAdminApps:  - getAdminApps() failed!');
124                         this.isLoadingTable = false;
125                     }
126             };
127
128             let getSortOrder = (prop) => {
129                 return function(a, b) {
130                     if (a[prop] > b[prop]) {
131                         return 1;
132                     } else if (a[prop] < b[prop]) {
133                         return -1;
134                     }
135                     return 0;
136                 }
137             }
138
139              let updateUsersList = () => {
140                 $scope.appsIsDown = false;
141                 $scope.noUsersInApp = false;
142                 // $log.debug('UsersCtrl::updateUsersList: Starting updateUsersList');
143                 //reset search string
144                 this.searchString = '';
145                 //should i disable this too in case of moving between tabs?
146                 this.isAppSelectDisabled = true;
147                 //activate spinner
148                 this.isLoadingTable = true;
149                 
150                 if(this.adminApps!=null && this.selectedApp!=null){
151                          var tempSelected = null;
152                          for(let i=0; i<=this.adminApps.length; i++){
153                         if(typeof this.adminApps[i] != 'undefined' && this.selectedApp.value==this.adminApps[i].value){
154                                 tempSelected=_.clone(this.adminApps[i]);
155                         }
156                      }
157                      if(tempSelected!=null){
158                         this.selectedApp= tempSelected;
159                      }
160                 }
161                
162                 if (this.selectedApp.value != this.selectApp) { // 'Select Application'
163                     usersService.getAccountUsers(this.selectedApp.id)
164                         .then(accountUsers => {
165                             $log.debug('UsersCtrl::updateUsersList accountUsers: '+ accountUsers);
166                             if (angular.isObject(accountUsers)===false) {
167                                 $log.error('UsersCtrl::updateUsersList accountUsers: App is down!');
168                                 $scope.appsIsDown = true;
169                             }
170                             $log.debug('UsersCtrl::updateUsersList length: '+ Object.keys(accountUsers).length);
171                             this.isAppSelectDisabled = false;
172                             this.accountUsers = accountUsers;
173                             if (angular.isObject(accountUsers) && Object.keys(accountUsers).length === 0) {
174                                 $log.debug('UsersCtrl::updateUsersList accountUsers: App has no users.');
175                                 $scope.noUsersInApp = true;
176                             }
177                         }).catch(err => {
178                             this.isAppSelectDisabled = false;
179                             $log.error('UsersCtrl::updateUsersList error: ' + err);
180                             confirmBoxService.showInformation('There was a problem updating the users List. ' +
181                                 'Please try again later.').then(isConfirmed => {});
182                             $scope.appsIsDown = true;
183                         }).finally(() => {
184                             this.isLoadingTable = false;
185                             $scope.noAppSelected = false;
186                     });
187                 } else {
188                     // this.selectedApp = this.adminApps[0];
189                     this.isAppSelectDisabled = false;
190                     this.isLoadingTable = false;
191                     $scope.noUsersInApp = false;
192                     $scope.noAppSelected = true;
193                 }
194             };
195
196
197             this.openAddNewUserModal = (user) => {
198                 let data = null;
199                 if (user) {
200                     data = {
201                         dialogState: 3,
202                         selectedUser: {
203                             orgUserId: user.orgUserId,
204                             firstName: user.firstName,
205                             lastName: user.lastName,
206
207                         }
208                     }
209                 }
210                 
211                 var modalInstance = $modal.open({
212                     templateUrl: 'app/views/users/new-user-dialogs/new-user.modal.html',
213                     controller: 'NewUserModalCtrl as newUser',
214                     sizeClass: 'modal-medium', 
215                     resolve: {
216                                         items: function () {
217                                                 return data;
218                                 }                
219                         }
220                 })
221                 
222                 modalInstance.result.finally(function () {
223                     $log.debug('UsersCtrl::openAddNewUserModal updating table data...');
224                     updateUsersList();                 
225                 });
226             };
227                             
228             this.openBulkUserUploadModal = (adminApps) => {
229                 let data = null;
230                 if (adminApps) {
231                     data = {
232                         dialogState: 3,
233                         selectedApplication: {
234                             appid: adminApps[0].appid,
235                             appName: adminApps[0].appName
236                         }
237                     }
238                 }
239                 var modalInstance = $modal.open({
240                         templateUrl: 'app/views/users/new-user-dialogs/bulk-user.modal.html',
241                     controller: 'BulkUserModalCtrl as bulkUser',
242                     sizeClass: 'modal-medium', 
243                     resolve: {
244                         items: function () {
245                                 return data;
246                                 }
247                         }
248                 });
249                 
250                 modalInstance.result.finally(function () {
251                         $log.debug('UsersCtrl::openAddNewUserModal updating table data...');
252                         updateUsersList();
253                 });
254             };
255
256             this.syncRolesFromExternalAuthSystem = (appId) =>{
257                 applicationsService.syncRolesEcompFromExtAuthSystem(appId).then(function(res){
258                         if(res.status == 200){
259                      confirmBoxService.showInformation('Sync operation completed successfully!').then(isConfirmed => {});                               
260                         } else{
261                                  confirmBoxService.showInformation('Sync operation failed for '+app).then(isConfirmed => {});                           
262                         }
263                 });
264             };
265
266             $scope.$watch('users.selectedApp.value', (newVal, oldVal) => {
267                 if(typeof(newVal) != 'undefined' && !newVal.includes("Select")){
268                   applicationsService.getSingleAppInfo(newVal).then(function(res) {
269                           $scope.app.appId = res.id;
270                           if(res.centralAuth == true){
271                                   $scope.syncRolesApplied = true;
272                           } else{
273                                   $scope.syncRolesApplied = false; 
274                           }
275                             });
276                 }
277                 if (!newVal || _.isEqual(newVal, oldVal)) {
278                     return;
279                 }
280                 $log.debug('UsersCtrl::openAddNewUserModal:$watch selectedApp -> Fire with: ', newVal);
281                 this.accountUsers = []; // reset table and show swirl here
282                 updateUsersList();
283             });
284
285             $scope.$on('$destroy', () => {
286                 //cancel all active requests when closing the modal
287                 activeRequests.forEach(req => {
288                     req.cancel();
289                 });
290             });
291
292             init();
293         }
294     }
295     UsersCtrl.$inject = ['$log', 'applicationsService', 'usersService', 'confirmBoxService', '$scope', 'ngDialog','$modal'];
296     angular.module('ecompApp').controller('UsersCtrl', UsersCtrl);
297 })();