Deliver centralized role management feature
[portal.git] / ecomp-portal-FE-common / client / app / views / header / header.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 HeaderCtrl {
23         constructor($log, $window, userProfileService, menusService, $scope, ECOMP_URL_REGEX, $cookies, $state,auditLogService,notificationService,ngDialog,$modal) {
24             this.firstName = '';
25             this.lastName = '';
26             this.$log = $log;
27             this.menusService = menusService;
28             this.$scope = $scope;
29             this.favoritesMenuItems = '';
30             $scope.favoriteItemsCount = 0;
31             $scope.favoritesMenuItems = '';
32             $scope.showFavorites = false;
33             $scope.emptyFavorites = false;
34             $scope.favoritesWindow = false;
35             $scope.notificationCount=0;
36             $scope.showNotification = true;
37
38             $scope.hideMenus = false;
39
40             $scope.menuItems = [];
41             $scope.activeClickSubMenu = {
42                 x: ''
43             }; 
44             $scope.activeClickMenu = {
45                 x: ''
46             };
47             $scope.megaMenuDataObject =[];
48             $scope.notificationCount= notificationService.notificationCount;
49             this.isLoading = true;
50             this.ECOMP_URL_REGEX = ECOMP_URL_REGEX;
51             
52             var unflatten = function( array, parent, tree ){
53             
54                 tree = typeof tree !== 'undefined' ? tree : [];
55                 parent = typeof parent !== 'undefined' ? parent : { menuId: null };
56                 var children = _.filter( array, function(child){ return child.parentMenuId == parent.menuId; });
57                 
58                 if( !_.isEmpty( children )  ){
59                   if( parent.menuId === null ){
60                     tree = children;
61                   }else{
62                     parent['children'] = children
63                   }
64                   _.each( children, function( child ){ unflatten( array, child ) } );
65                 }
66             
67                 return tree;
68             }
69             
70             userProfileService.getFunctionalMenuStaticInfo()
71             .then(res=> {
72                 // $log.debug('HeaderCtrl::getFunctionalMenuStaticInfo: getting Functional Menu Static Info init');
73                 if(res==null || res.firstName==null || res.firstName=='' || res.lastName==null || res.lastName=='' ){
74                         // $log.info('HeaderCtrl::getFunctionalMenuStaticInfo: failed getting userinfo from shared context.. ');
75                         $log.info('HeaderCtrl: failed to get all required data, trying user profile');
76                         userProfileService.getUserProfile()
77                     .then(profile=> {
78                         // $log.debug('HeaderCtrl:: getting userinfo from session success');
79                         this.firstName = profile.firstName;
80                         this.lastName = profile.lastName;                     
81                         // $log.debug('HeaderCtrl::getFunctionalMenuStaticInfo: user has the following roles: ' + profile.roles);
82                     }).catch(err=> {
83                         $log.error('Header Controller:: getUserProfile() failed: ' + err);
84                     });
85                 } else {
86                         // $log.debug('HeaderCtrl: fetched Functional Menu Static Info successfully',res);
87                         this.firstName = res.firstName;
88                         this.lastName = res.lastName;                                     
89                 }
90
91                 menusService.GetFunctionalMenuForUser()
92                 .then(jsonHeaderMenu=> {
93                         $scope.menuItems = unflatten( jsonHeaderMenu );
94                         $scope.megaMenuDataObject = $scope.menuItems;
95                 }).catch(err=> {
96                         $log.error('HeaderCtrl::GetFunctionalMenuForUser: HeaderCtrl json returned: ' + err);
97                 });      
98                 
99             }).catch(err=> {
100                 $log.error('HeaderCtrl::getFunctionalMenuStaticInfo failed: ' + err);
101             });
102             
103           //store audit log
104             $scope.auditLog = function(app,type) {
105                 var comment = 'type: '+type+ ',title: '+app.text+",url: "+app.url;
106                         auditLogService.storeAudit(app.appid,'functional',comment);
107                 };
108
109             $scope.loadFavorites = function () {
110                 $scope.hideMenus = false;
111                 // $log.debug('HeaderCtrl::loadFavorites: loadFavorites has happened.');
112                 if ($scope.favoritesMenuItems == '') {
113                     generateFavoriteItems();
114                     // $log.debug('HeaderCtrl::loadFavorites: loadFavorites is calling generateFavoriteItems()');
115                 } else {
116                     // $log.debug('HeaderCtrl::loadFavorites: loadFavorites is NOT calling generateFavoriteItems()');
117                 }
118             }
119
120             $scope.goToUrl = (item) =>  {
121                //  $log.error('HeaderCtrl::goToUrl has started',item);
122                 let url = item.url;
123                 let restrictedApp = item.restrictedApp;
124                 if (!url) {
125                     $log.warn('HeaderCtrl::goToUrl: No url found for this application, doing nothing..');
126                     return;
127                 }
128                 if (restrictedApp) {
129                     $window.open(url, '_blank');
130                 } else {
131                         if(item.url=="getAccess" || item.url=="contactUs"){
132                             // if (url = window.location.href)
133                                 $state.go("root."+url);
134                         } else {
135                         var tabContent = { id: new Date(), title: item.text, url: item.url,appId:item.appid };
136                         $cookies.putObject('addTab', tabContent );
137                     }
138                     // $log.debug('HeaderCtrl::goToUrl: url = ', url);
139                 }
140                 $scope.hideMenus = true;
141             }
142             
143             
144             
145             $scope.submenuLevelAction = function(index, column) {
146                 if ($scope.favoritesMenuItems == '') {
147                     generateFavoriteItems();
148                     // $log.debug('HeaderCtrl::submenuLevelAction: submenuLevelAction is calling generateFavoriteItems()');
149                 } else {
150                     // $log.debug('submenuLevelAction is NOT calling generateFavoriteItems()');
151                 }
152                 // $log.debug('item hovered: ' + index + '; column = ' + column);
153                 // if (column == 2) {  // 2 is Design
154                 //     // This is an admitted hack. See aw3218 for reasons why
155                 //     $log.debug('submenuLevelAction column == 2');
156                 //     $scope.favoritesWindow = false;
157                 //     $scope.showFavorites = false;
158                 //     $scope.emptyFavorites = false;
159                 // }
160                 if (index=='Favorites' && $scope.favoriteItemsCount != 0) {
161                     // $log.debug('HeaderCtrl::submenuLevelAction: Showing Favorites window');
162                     // generateFavoriteItems();
163                     $scope.favoritesWindow = true;
164                     $scope.showFavorites = true;
165                     $scope.emptyFavorites = false;
166                 }
167                 if (index=='Favorites' && $scope.favoriteItemsCount == 0) {
168                     // $log.debug('HeaderCtrl::submenuLevelAction: Hiding Favorites window in favor of No Favorites Window');
169                     // generateFavoriteItems();
170                     $scope.favoritesWindow = true;
171                     $scope.showFavorites = false;
172                     $scope.emptyFavorites = true;
173                 }
174                 if (index!='Favorites' ) {
175                     $scope.favoritesWindow = false;
176                     $scope.showFavorites = false;
177                     $scope.emptyFavorites = false;
178                 }
179
180             };
181             
182             $scope.hideFavoritesWindow = function() {
183                 $scope.showFavorites = false;
184                 $scope.emptyFavorites = false;
185                 // $scope.thirdFourthMenus = true;
186             }
187             
188             $scope.isUrlFavorite = function (menuId) {
189                 // $log.debug('array objects in menu favorites = ' + $scope.favoriteItemsCount + '; menuId=' + menuId);
190                 var jsonMenu =  JSON.stringify($scope.favoritesMenuItems);
191                 var isMenuFavorite =  jsonMenu.indexOf('menuId\":' + menuId);
192                 // $log.debug('jsonMenu.indexOf(menuId:' + jsonMenu.indexOf('menuId\":'+menuId));
193                 // $log.debug('isMenuFavorite= ' + isMenuFavorite);
194                 if (isMenuFavorite==-1) {
195                     return false;
196                 } else {
197                     return true;
198                 }
199
200             }
201             
202             /*Getting Ecomp portal Title*/
203
204             let getEcompPortalTitle  = () => {
205                 menusService.getEcompPortalTitle()
206                 .then(title=> {
207                         $scope.ecompTitle = title.response;
208                 }).catch(err=> {
209                         $log.error('HeaderCtrl.getEcompPortalTitle:: Error retrieving ECMOP portal title: ' + err);
210                 });
211             }
212             getEcompPortalTitle();
213             
214             let generateFavoriteItems  = () => {
215                 menusService.getFavoriteItems()
216                     .then(favorites=> {
217                         // $log.debug('HeaderCtrl.getFavoriteItems:: ' + JSON.stringify(favorites));
218                         $scope.favoritesMenuItems = favorites;
219                         $scope.favoriteItemsCount = Object.keys(favorites).length;
220                         // $log.info('HeaderCtrl.getFavoriteItems:: number of favorite menus: ' + $scope.favoriteItemsCount);
221                     }).catch(err=> {
222                         $log.error('HeaderCtrl.getFavoriteItems:: Error retrieving Favorites menus: ' + err);
223                 });
224             }
225
226            $scope.setAsFavoriteItem =  function(event, menuId){
227                var jsonMenuID = angular.toJson({'menuId': + menuId });
228                // $log.debug('HeaderCtrl::setFavoriteItems: ' + jsonMenuID  + " - " +  event.target.id);
229
230                menusService.setFavoriteItem(jsonMenuID)
231                .then(() => {
232                    // var elementId = '#'+ event.currentTarget.id;
233                    angular.element('#' + event.target.id).css('color', '#fbb313');
234                    generateFavoriteItems();
235                }).catch(err=> {
236                    $log.error('HeaderCtrl::setFavoriteItems:: API setFavoriteItem error: ' + err);
237                });
238            };
239
240             $scope.removeAsFavoriteItem =  function(event, menuId){
241                 // $log.debug('-----------------------------removeAsFavoriteItem: ' + menuId + " - " +  event.target.id);
242                 menusService.removeFavoriteItem(menuId)
243                 .then(() => {
244                     angular.element('#' + event.target.id).css('color', '#666666');
245                     generateFavoriteItems();
246                 }).catch(err=> {
247                     $log.error('HeaderCtrl::removeAsFavoriteItem: API removeFavoriteItem error: ' + err);
248                 });
249             };
250
251             $scope.goToPortal = (headerText, url) => {
252                 if (!url) {
253                     $log.warn('HeaderCtrl::goToPortal: No url found for this application, doing nothing..');
254                     return;
255                 }
256                 if (!ECOMP_URL_REGEX.test(url)) {
257                     url = 'http://' + url;
258                 }
259
260                 if(headerText.startsWith("vUSP")) {
261                         window.open(url, '_blank');//, '_self'
262                 }
263                 else {
264                         var tabContent = { id: new Date(), title: headerText, url: url };
265                         $cookies.putObject('addTab', tabContent );
266                 }
267             };
268             
269             $scope.editProfile = () => {
270                 let data = null;
271                
272                 ngDialog.open({
273                     templateUrl: 'app/views/header/profile-edit-dialogs/profile-edit.modal.html',
274                     controller: 'EditProfileModalCtrl',
275                     controllerAs: 'profileDetail',
276                     data: ''
277                 }).closePromise.then(needUpdate => {
278                     if(needUpdate.value === true){
279                         // $log.debug('AdminsCtrl:openAddNewAdminModal:: updating table data...');
280                         updateTableData();
281                     }
282                 });
283             };
284         }
285     }
286     class LoginSnippetCtrl {
287         constructor($log, $scope, $cookies, $timeout, userProfileService, sessionService) {
288             $scope.firstName="";
289             $scope.lastName="";
290             $scope.displayUserAppRoles=false; 
291             $scope.allAppsLogout = function(){
292                 
293                 var cookieTabs = $cookies.getObject('visInVisCookieTabs');
294                 if(cookieTabs!=null){
295                         for(var t in cookieTabs){
296                         
297                                 var url = cookieTabs[t].content;
298                                 if(url != "") {
299                                         sessionService.logout(url);
300                         }
301                         }
302                 }
303                 // wait for individual applications to log out before the portal logout
304                 $timeout(function() {
305                         window.location = "logout.htm";
306                 }, 2000);
307             }
308             
309             
310             try {
311                 userProfileService.getFunctionalMenuStaticInfo()
312                 .then(res=> {
313                   // $log.info('HeaderCtrl::LoginSnippetCtrl: Login information: ' + JSON.stringify(res));
314                   $scope.firstName = res.firstName;
315                   $scope.lastName = res.lastName;
316                   $scope.loginSnippetEmail = res.email;
317                   $scope.loginSnippetUserid = res.userId;
318                   $scope.lastLogin = res.last_login;
319                 }).catch(err=> {
320                   $log.error('HeaderCtrl::LoginSnippetCtrl: failed in getFunctionalMenuStaticInfo: ' + err);
321                 });
322             } catch (err) {
323                 $log.error('HeaderCtrl::LoginSnippetCtrl caught exception: ' + err);
324             }
325             
326             $scope.getUserApplicationRoles= function(){
327                   $scope.userapproles = [];
328                   if($scope.displayUserAppRoles)
329                                 $scope.displayUserAppRoles = false;
330                                  else
331                                         $scope.displayUserAppRoles = true;
332                   
333                         userProfileService.getUserAppRoles($scope.loginSnippetUserid)
334                           .then(res=>{
335                                 
336                  for(var i=0;i<res.length;i++){                                 
337                         var userapprole ={
338                                 App:res[i].appName,
339                                 Roles:res[i].roleNames, 
340                         };
341                         
342                         $scope.userapproles.push(userapprole); 
343                 }
344                  
345                 });
346                 
347           }
348         }        
349     }
350     class NotificationCtrl{
351         constructor($log, $scope, $cookies, $timeout, sessionService,notificationService,$interval,ngDialog,$modal) {
352                  $scope.notifications=[];   
353                  var intervalPromise = null;
354              $scope.notificationCount= notificationService.notificationCount;
355              
356              $scope.getNotification = function(){                
357                  notificationService.getNotification()
358                  .then(res=> {
359                         notificationService.decrementRefreshCount();
360                         var count = notificationService.getRefreshCount();
361                         if (res==null || res.data==null || res.data.message!='success') {
362                                 $log.error('NotificationCtrl::updateNotifications: failed to get notifications');
363                                 if (intervalPromise != null)
364                                         $interval.cancel(intervalPromise);
365                         } else if(count<=0){
366                                 if (intervalPromise != null)
367                                         $interval.cancel(intervalPromise);
368                         } else {
369                                 $scope.notifications = [];
370                                 notificationService.setNotificationCount(res.data.response.length);
371                                 for(var i=0;i<res.data.response.length;i++){
372                                         var data = res.data.response[i];                                        
373                                         var notification ={
374                                                 id:data.notificationId,
375                                                 msgHeader:data.msgHeader,
376                                                 message:data.msgDescription,
377                                                 msgSource:data.msgSource,
378                                                 time:data.createdDate,
379                                                 priority:data.priority,
380                                                 notificationHyperlink:data.notificationHyperlink
381                                         };
382                                         $scope.notifications.push(notification);       
383                                      }  
384                         }       
385                  }).catch(err=> {
386                         $log.error('NotificationCtrl::getNotification: caught exception: ' + err);
387                         if (intervalPromise != null)
388                                 $interval.cancel(intervalPromise);
389                  });      
390              }
391              $scope.getNotification();
392              function updateNotifications() {
393                  $scope.getNotification();
394              }
395              $scope.start = function(rate) {
396                                 // stops any running interval to avoid two intervals running at the same time
397                                 $scope.stop();  
398                                 // store the interval promise
399                                 intervalPromise = $interval(updateNotifications, rate);
400                          };
401
402                          $scope.stop = function() {
403                                 $interval.cancel(intervalPromise);
404                          };
405                          
406                          $scope.showDetailedJsonMessage=function (selectedAdminNotification) {
407                          notificationService.getMessageRecipients(selectedAdminNotification.id).then(res =>{
408                      $scope.messageRecipients = res;
409                                  var messageObject=JSON.parse(selectedAdminNotification.message);
410                                  var modalInstance = $modal.open({
411                             templateUrl: 'app/views/user-notifications-admin/user.notifications.json.details.modal.page.html',
412                             controller: 'userNotificationCtrl',
413                             sizeClass: 'modal-large', 
414                             resolve: {
415                                                 items: function () {
416                                                         var items = {
417                                                                    title:    '',
418                                                     selectedAdminNotification:selectedAdminNotification,messageObject:messageObject,messageRecipients:$scope.messageRecipients
419                                                         
420                                                         };
421                                                   return items;
422                                                 }
423                                 }
424                         })
425                      
426          
427          }).catch(err => {
428             $log.error('userNotificationsCtrl:getMessageRecipients:: error ', err);
429             $scope.isLoadingTable = false;
430         });
431                  };
432                          
433                         notificationService.getNotificationRate().then(res=> {
434                 if (res == null || res.response == null) {
435                         $log.error('NotificationCtrl: failed to notification update rate or duration, check system.properties file.');
436                 } else {
437                         var rate = parseInt(res.response.updateRate);
438                                         var duration = parseInt(res.response.updateDuration);
439                                         notificationService.setMaxRefreshCount(parseInt(duration/rate)+1);
440                                         notificationService.setRefreshCount(notificationService.maxCount);
441                                 if (rate != NaN && duration != NaN) {
442                                                 $scope.updateRate=rate;
443                                                 $scope.start($scope.updateRate);
444                                 }                               
445                 }
446             }).catch(err=> {
447                 $log.error('NotificationCtrl: getNotificationRate() failed: ' + err);
448             });
449              
450              $scope.deleteNotification = function(index){
451                  if ($scope.notifications[index].id == null || $scope.notifications[index].id == '') {
452                         $log.error('NotificationCtrl: failed to delete Notification.');
453                         return;
454                  }
455                  notificationService.setNotificationRead($scope.notifications[index].id);
456                  $scope.notifications.splice(index,1);
457                  notificationService.setNotificationCount($scope.notifications.length);          
458              }
459         }
460     }
461     
462     NotificationCtrl.$inject = ['$log', '$scope', '$cookies', '$timeout', 'sessionService','notificationService','$interval','ngDialog','$modal'];
463     LoginSnippetCtrl.$inject = ['$log', '$scope', '$cookies', '$timeout','userProfileService', 'sessionService'];
464     HeaderCtrl.$inject = ['$log', '$window', 'userProfileService', 'menusService', '$scope', 'ECOMP_URL_REGEX','$cookies','$state','auditLogService','notificationService','ngDialog','$modal'];
465     angular.module('ecompApp').controller('HeaderCtrl', HeaderCtrl);
466     angular.module('ecompApp').controller('loginSnippetCtrl', LoginSnippetCtrl);
467     angular.module('ecompApp').controller('notificationCtrl', NotificationCtrl);
468 })();