f74b167e9e8e8e1f330f0c88023cbb6eac3bdaea
[portal.git] / ecomp-portal-FE-common / client / app / views / users / users.controller.js
1 /*-
2  * ================================================================================
3  * ECOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20 'use strict';
21 (function () {
22     class UsersCtrl {
23         constructor($log, applicationsService, usersService, confirmBoxService, $scope, ngDialog,$modal) {
24             this.$log = $log;
25             $scope.adminAppsIsNull = false;
26             $scope.appsIsDown = false;
27             $scope.noUsersInApp = false;
28             $scope.multiAppAdmin = false;
29
30             $log.info('UsersCtrl:: initializing...');
31             /**
32              * Handle all active HTTP requests
33              * activeRequests @type {Array[requests with cancel option]}
34              */
35             let activeRequests = [];
36             let clearReq = (req) => {
37                 activeRequests.splice(activeRequests.indexOf(req), 1);
38             };
39
40             let init = () => {
41                 this.isLoadingTable = false;
42                 this.selectedApp = null;
43                 this.isAppSelectDisabled = false;
44                 this.selectApp = 'Select application';
45                 this.adminApps = [{index: 0, id: 0, value: this.selectApp, title: this.selectApp}];
46                 getAdminApps();
47
48                 /*Table general configuration params*/
49                 this.searchString = '';
50                 /*Table data*/
51                 this.usersTableHeaders = ['First Name', 'Last Name', 'User ID', 'Roles'];
52                 this.accountUsers = [];
53             };
54
55             let getAdminApps = () => {
56                 $log.debug('UsersCtrl::getAdminApps: - Starting getAdminApps');
57                 try {
58                     this.isLoadingTable = true;
59                     let adminAppsReq = applicationsService.getAdminApps();
60                     adminAppsReq.promise().then(apps => {
61                         if (!apps || !apps.length) {
62                             $log.error('UsersCtrl::getAdminApps:  - no apps found');
63                             return null;
64                         }
65                         $log.debug('UsersCtrl::getAdminApps: Apps for this user are: ' + JSON.stringify(apps));
66                         if (apps.length >= 2) {
67                             $log.info('UsersCtrl::getAdminApps:  - more than one app for this admin:', apps.length, ' apps');
68                             $scope.multiAppAdmin = true;
69                         } else {
70                             this.adminApps = [] ;
71                         }
72                         let sortedApps = apps.sort(getSortOrder("name"));
73                         let realAppIndex = 1;
74                         for(let i=1; i<=sortedApps.length; i++){
75                             this.adminApps.push({
76                                 index: realAppIndex,
77                                 id: sortedApps[i - 1].id,
78                                 value: sortedApps[i - 1].name,
79                                 title: sortedApps[i - 1].name
80                             });
81                             realAppIndex = realAppIndex + 1;
82                         }
83
84                         $log.debug('UsersCtrl::getAdminApps: Apps for this user are: ' + JSON.stringify(this.adminApps));
85
86                         this.selectedApp = this.adminApps[0];
87                         clearReq(adminAppsReq);
88                         $scope.adminAppsIsNull = false;
89                         }).catch(e => {
90                             $scope.adminAppsIsNull = true;
91                             $log.error('UsersCtrl::getAdminApps:  - getAdminApps() failed = '+ e.message);
92                             clearReq(adminAppsReq);
93                             confirmBoxService.showInformation('There was a problem retrieving the applications. ' +
94                                 'Please try again later.').then(isConfirmed => {});
95
96                     }).finally(() => {
97                             this.isLoadingTable = false;
98                         });
99                     } catch (e) {
100                         $scope.adminAppsIsNull = true;
101                         $log.error('UsersCtrl::getAdminApps:  - getAdminApps() failed!');
102                         this.isLoadingTable = false;
103                     }
104             };
105
106             let getSortOrder = (prop) => {
107                 return function(a, b) {
108                     if (a[prop] > b[prop]) {
109                         return 1;
110                     } else if (a[prop] < b[prop]) {
111                         return -1;
112                     }
113                     return 0;
114                 }
115             }
116
117              let updateUsersList = () => {
118                 $scope.appsIsDown = false;
119                 $scope.noUsersInApp = false;
120                 // $log.debug('UsersCtrl::updateUsersList: Starting updateUsersList');
121                 //reset search string
122                 this.searchString = '';
123                 //should i disable this too in case of moving between tabs?
124                 this.isAppSelectDisabled = true;
125                 //activate spinner
126                 this.isLoadingTable = true;
127                 
128                 if(this.adminApps!=null && this.selectedApp!=null){
129                          var tempSelected = null;
130                          for(let i=0; i<=this.adminApps.length; i++){
131                         if(typeof this.adminApps[i] != 'undefined' && this.selectedApp.value==this.adminApps[i].value){
132                                 tempSelected=_.clone(this.adminApps[i]);
133                         }
134                      }
135                      if(tempSelected!=null){
136                         this.selectedApp= tempSelected;
137                      }
138                 }
139                
140                 if (this.selectedApp.title != this.selectApp) { // 'Select Application'
141                     usersService.getAccountUsers(this.selectedApp.id)
142                         .then(accountUsers => {
143                             $log.debug('UsersCtrl::updateUsersList accountUsers: '+ accountUsers);
144                             if (angular.isObject(accountUsers)===false) {
145                                 $log.error('UsersCtrl::updateUsersList accountUsers: App is down!');
146                                 $scope.appsIsDown = true;
147                             }
148                             $log.debug('UsersCtrl::updateUsersList length: '+ Object.keys(accountUsers).length);
149                             this.isAppSelectDisabled = false;
150                             this.accountUsers = accountUsers;
151                             if (angular.isObject(accountUsers) && Object.keys(accountUsers).length === 0) {
152                                 $log.debug('UsersCtrl::updateUsersList accountUsers: App has no users.');
153                                 $scope.noUsersInApp = true;
154                             }
155                         }).catch(err => {
156                             this.isAppSelectDisabled = false;
157                             $log.error('UsersCtrl::updateUsersList error: ' + err);
158                             confirmBoxService.showInformation('There was a problem updating the users List. ' +
159                                 'Please try again later.').then(isConfirmed => {});
160                             $scope.appsIsDown = true;
161                         }).finally(() => {
162                             this.isLoadingTable = false;
163                             $scope.noAppSelected = false;
164                     });
165                 } else {
166                     // this.selectedApp = this.adminApps[0];
167                     this.isAppSelectDisabled = false;
168                     this.isLoadingTable = false;
169                     $scope.noUsersInApp = false;
170                     $scope.noAppSelected = true;
171                 }
172             };
173
174
175             this.openAddNewUserModal = (user) => {
176                 let data = null;
177                 if (user) {
178                     data = {
179                         dialogState: 3,
180                         selectedUser: {
181                             orgUserId: user.orgUserId,
182                             firstName: user.firstName,
183                             lastName: user.lastName,
184
185                         }
186                     }
187                 }
188                 
189                 var modalInstance = $modal.open({
190                     templateUrl: 'app/views/users/new-user-dialogs/new-user.modal.html',
191                     controller: 'NewUserModalCtrl as newUser',
192                     sizeClass: 'modal-medium', 
193                     resolve: {
194                                         items: function () {
195                                                 return data;
196                                 }                
197                         }
198                 })
199                 
200                 modalInstance.result.finally(function () {
201                     $log.debug('UsersCtrl::openAddNewUserModal updating table data...');
202                     updateUsersList();                 
203                 });
204             };
205                             
206             this.openBulkUserUploadModal = (adminApps) => {
207                 let data = null;
208                 if (adminApps) {
209                     data = {
210                         dialogState: 3,
211                         selectedApplication: {
212                             appid: adminApps[0].appid,
213                             appName: adminApps[0].appName
214                         }
215                     }
216                 }
217                 var modalInstance = $modal.open({
218                         templateUrl: 'app/views/users/new-user-dialogs/bulk-user.modal.html',
219                     controller: 'BulkUserModalCtrl as bulkUser',
220                     sizeClass: 'modal-medium', 
221                     resolve: {
222                         items: function () {
223                                 return data;
224                                 }
225                         }
226                 });
227                 
228                 modalInstance.result.finally(function () {
229                         $log.debug('UsersCtrl::openAddNewUserModal updating table data...');
230                         updateUsersList();
231                 });
232             };
233
234
235             $scope.$watch('users.selectedApp.value', (newVal, oldVal) => {
236                 if (!newVal || _.isEqual(newVal, oldVal)) {
237                     return;
238                 }
239                 $log.debug('UsersCtrl::openAddNewUserModal:$watch selectedApp -> Fire with: ', newVal);
240                 this.accountUsers = []; //reset table and show swirl here
241                 updateUsersList();
242             });
243
244             $scope.$on('$destroy', () => {
245                 //cancel all active requests when closing the modal
246                 activeRequests.forEach(req => {
247                     req.cancel();
248                 });
249             });
250
251             init();
252         }
253     }
254     UsersCtrl.$inject = ['$log', 'applicationsService', 'usersService', 'confirmBoxService', '$scope', 'ngDialog','$modal'];
255     angular.module('ecompApp').controller('UsersCtrl', UsersCtrl);
256 })();