f0a3117268c87dbc98333ee482aff3a6a0c1f0aa
[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                 if(res==null || res.firstName==null || res.firstName=='' || res.lastName==null || res.lastName=='' ){
73                         $log.info('HeaderCtrl: failed to get all required data, trying user profile');
74                         userProfileService.getUserProfile()
75                     .then(profile=> {
76                         this.firstName = profile.firstName;
77                         this.lastName = profile.lastName;                     
78                     }).catch(err=> {
79                         $log.error('Header Controller:: getUserProfile() failed: ' + err);
80                     });
81                 } else {
82                         this.firstName = res.firstName;
83                         this.lastName = res.lastName;                                     
84                 }
85
86                 menusService.GetFunctionalMenuForUser()
87                 .then(jsonHeaderMenu=> {
88                         $scope.menuItems = unflatten( jsonHeaderMenu );
89                         $scope.megaMenuDataObject = $scope.menuItems;
90                 }).catch(err=> {
91                         $log.error('HeaderCtrl::GetFunctionalMenuForUser: HeaderCtrl json returned: ' + err);
92                 });      
93                 
94             }).catch(err=> {
95                 $log.error('HeaderCtrl::getFunctionalMenuStaticInfo failed: ' + err);
96             });
97             
98           //store audit log
99             $scope.auditLog = function(app,type) {
100                 var comment = 'type: '+type+ ',title: '+app.text+",url: "+app.url;
101                         auditLogService.storeAudit(app.appid,'functional',comment);
102                 };
103
104             $scope.loadFavorites = function () {
105                 $scope.hideMenus = false;
106                 if ($scope.favoritesMenuItems == '') {
107                     generateFavoriteItems();
108                 }
109             }
110
111             $scope.goToUrl = (item) =>  {
112                 let url = item.url;
113                 let restrictedApp = item.restrictedApp;
114                 if (!url) {
115                     $log.warn('HeaderCtrl::goToUrl: No url found for this application, doing nothing..');
116                     return;
117                 }
118                 if (restrictedApp) {
119                     $window.open(url, '_blank');
120                 } else {
121                         if(item.url=="getAccess" || item.url=="contactUs"){
122                                 $state.go("root."+url);
123                         } else {
124                         var tabContent = { id: new Date(), title: item.text, url: item.url,appId:item.appid };
125                         $cookies.putObject('addTab', tabContent );
126                     }
127                 }
128                 $scope.hideMenus = true;
129             }
130             
131             
132             
133             $scope.submenuLevelAction = function(index, column) {           
134                 if (index=='Favorites' && $scope.favoriteItemsCount != 0) {
135                     $scope.favoritesWindow = true;
136                     $scope.showFavorites = true;
137                     $scope.emptyFavorites = false;
138                 }
139                 if (index=='Favorites' && $scope.favoriteItemsCount == 0) {
140                     $scope.favoritesWindow = true;
141                     $scope.showFavorites = false;
142                     $scope.emptyFavorites = true;
143                 }
144                 if (index!='Favorites' ) {
145                     $scope.favoritesWindow = false;
146                     $scope.showFavorites = false;
147                     $scope.emptyFavorites = false;
148                 }
149             };
150             
151             $scope.hideFavoritesWindow = function() {
152                 $scope.showFavorites = false;
153                 $scope.emptyFavorites = false;
154             }
155             
156             $scope.isUrlFavorite = function (menuId) {
157                 var jsonMenu =  JSON.stringify($scope.favoritesMenuItems);
158                 var isMenuFavorite =  jsonMenu.indexOf('menuId\":' + menuId);
159                 if (isMenuFavorite==-1) {
160                     return false;
161                 } else {
162                     return true;
163                 }
164             }
165             
166             /*Getting Ecomp portal Title*/
167
168             let getEcompPortalTitle  = () => {
169                 menusService.getEcompPortalTitle()
170                 .then(title=> {
171                         $scope.ecompTitle = title.response;
172                 }).catch(err=> {
173                         $log.error('HeaderCtrl.getEcompPortalTitle:: Error retrieving ECMOP portal title: ' + err);
174                 });
175             }
176             getEcompPortalTitle();
177             
178             let generateFavoriteItems  = () => {
179                 menusService.getFavoriteItems()
180                     .then(favorites=> {
181                         $scope.favoritesMenuItems = favorites;
182                         $scope.favoriteItemsCount = Object.keys(favorites).length;
183                     }).catch(err=> {
184                         $log.error('HeaderCtrl.getFavoriteItems:: Error retrieving Favorites menus: ' + err);
185                 });
186             }
187
188            $scope.setAsFavoriteItem =  function(event, menuId){
189                var jsonMenuID = angular.toJson({'menuId': + menuId });
190                menusService.setFavoriteItem(jsonMenuID)
191                .then(() => {
192                    angular.element('#' + event.target.id).css('color', '#fbb313');
193                    generateFavoriteItems();
194                }).catch(err=> {
195                    $log.error('HeaderCtrl::setFavoriteItems:: API setFavoriteItem error: ' + err);
196                });
197            };
198
199             $scope.removeAsFavoriteItem =  function(event, menuId){
200                 menusService.removeFavoriteItem(menuId)
201                 .then(() => {
202                     angular.element('#' + event.target.id).css('color', '#666666');
203                     generateFavoriteItems();
204                 }).catch(err=> {
205                     $log.error('HeaderCtrl::removeAsFavoriteItem: API removeFavoriteItem error: ' + err);
206                 });
207             };
208
209             $scope.goToPortal = (headerText, url) => {
210                 if (!url) {
211                     $log.warn('HeaderCtrl::goToPortal: No url found for this application, doing nothing..');
212                     return;
213                 }
214                 if (!ECOMP_URL_REGEX.test(url)) {
215                     url = 'http://' + url;
216                 }
217
218                 if(headerText.startsWith("vUSP")) {
219                         window.open(url, '_blank');//, '_self'
220                 }
221                 else {
222                         var tabContent = { id: new Date(), title: headerText, url: url };
223                         $cookies.putObject('addTab', tabContent );
224                 }
225             };
226             
227             $scope.editProfile = () => {
228                 let data = null;
229                
230                 ngDialog.open({
231                     templateUrl: 'app/views/header/profile-edit-dialogs/profile-edit.modal.html',
232                     controller: 'EditProfileModalCtrl',
233                     controllerAs: 'profileDetail',
234                     data: ''
235                 }).closePromise.then(needUpdate => {
236                     if(needUpdate.value === true){
237                         updateTableData();
238                     }
239                 });
240             };
241         }
242     }
243     class LoginSnippetCtrl {
244         constructor($log, $scope, $cookies, $timeout, userProfileService, sessionService) {
245             $scope.firstName="";
246             $scope.lastName="";
247             $scope.displayUserAppRoles=false; 
248             $scope.allAppsLogout = function(){
249                 
250                 var cookieTabs = $cookies.getObject('visInVisCookieTabs');
251                 if(cookieTabs!=null){
252                         for(var t in cookieTabs){
253                         
254                                 var url = cookieTabs[t].content;
255                                 if(url != "") {
256                                         sessionService.logout(url);
257                         }
258                         }
259                 }
260                 // wait for individual applications to log out before the portal logout
261                 $timeout(function() {
262                         window.location = "logout.htm";
263                 }, 2000);
264             }
265             
266             
267             try {
268                 userProfileService.getFunctionalMenuStaticInfo()
269                 .then(res=> {
270                   $scope.firstName = res.firstName;
271                   $scope.lastName = res.lastName;
272                   $scope.loginSnippetEmail = res.email;
273                   $scope.loginSnippetUserid = res.userId;
274                   $scope.lastLogin = res.last_login;
275                 }).catch(err=> {
276                   $log.error('HeaderCtrl::LoginSnippetCtrl: failed in getFunctionalMenuStaticInfo: ' + err);
277                 });
278             } catch (err) {
279                 $log.error('HeaderCtrl::LoginSnippetCtrl caught exception: ' + err);
280             }
281             
282             $scope.getUserApplicationRoles= function(){
283                   $scope.userapproles = [];
284                   if($scope.displayUserAppRoles)
285                                 $scope.displayUserAppRoles = false;
286                                  else
287                                         $scope.displayUserAppRoles = true;
288                   
289                         userProfileService.getUserAppRoles($scope.loginSnippetUserid)
290                           .then(res=>{
291                                 
292                  for(var i=0;i<res.length;i++){                                 
293                         var userapprole ={
294                                 App:res[i].appName,
295                                 Roles:res[i].roleNames, 
296                         };                      
297                         $scope.userapproles.push(userapprole); 
298                  }
299                  
300                 });
301                 
302           }
303         }        
304     }
305     class NotificationCtrl{
306         constructor($log, $scope, $cookies, $timeout, sessionService,notificationService,$interval,ngDialog,$modal) {
307                  $scope.notifications=[];   
308                  var intervalPromise = null;
309              $scope.notificationCount= notificationService.notificationCount;
310              
311              $scope.getNotification = function(){                
312                  notificationService.getNotification()
313                  .then(res=> {
314                         notificationService.decrementRefreshCount();
315                         var count = notificationService.getRefreshCount();
316                         if (res==null || res.data==null || res.data.message!='success') {
317                                 $log.error('NotificationCtrl::updateNotifications: failed to get notifications');
318                                 if (intervalPromise != null)
319                                         $interval.cancel(intervalPromise);
320                         } else if(count<=0){
321                                 if (intervalPromise != null)
322                                         $interval.cancel(intervalPromise);
323                         } else {
324                                 $scope.notifications = [];
325                                 notificationService.setNotificationCount(res.data.response.length);
326                                 for(var i=0;i<res.data.response.length;i++){
327                                         var data = res.data.response[i];                                        
328                                         var notification ={
329                                                 id:data.notificationId,
330                                                 msgHeader:data.msgHeader,
331                                                 message:data.msgDescription,
332                                                 msgSource:data.msgSource,
333                                                 time:data.createdDate,
334                                                 priority:data.priority,
335                                                 notificationHyperlink:data.notificationHyperlink
336                                         };
337                                         $scope.notifications.push(notification);       
338                                      }  
339                         }       
340                  }).catch(err=> {
341                         $log.error('NotificationCtrl::getNotification: caught exception: ' + err);
342                         if (intervalPromise != null)
343                                 $interval.cancel(intervalPromise);
344                  });      
345              }
346              $scope.getNotification();
347              function updateNotifications() {
348                  $scope.getNotification();
349              }
350              $scope.start = function(rate) {
351                                 // stops any running interval to avoid two intervals running at the same time
352                                 $scope.stop();  
353                                 // store the interval promise
354                                 intervalPromise = $interval(updateNotifications, rate);
355                          };
356
357                          $scope.stop = function() {
358                                 $interval.cancel(intervalPromise);
359                          };
360                          
361                          $scope.showDetailedJsonMessage=function (selectedAdminNotification) {
362                          notificationService.getMessageRecipients(selectedAdminNotification.id).then(res =>{
363                      $scope.messageRecipients = res;
364                                  var messageObject=JSON.parse(selectedAdminNotification.message);
365                                  var modalInstance = $modal.open({
366                             templateUrl: 'app/views/user-notifications-admin/user.notifications.json.details.modal.page.html',
367                             controller: 'userNotificationCtrl',
368                             sizeClass: 'modal-large', 
369                             resolve: {
370                                                 items: function () {
371                                                         var items = {
372                                                                    title:    '',
373                                                     selectedAdminNotification:selectedAdminNotification,messageObject:messageObject,messageRecipients:$scope.messageRecipients
374                                                         
375                                                         };
376                                                   return items;
377                                                 }
378                                 }
379                         })
380                      
381          
382          }).catch(err => {
383             $log.error('userNotificationsCtrl:getMessageRecipients:: error ', err);
384             $scope.isLoadingTable = false;
385         });
386                  };
387                          
388                         notificationService.getNotificationRate().then(res=> {
389                 if (res == null || res.response == null) {
390                         $log.error('NotificationCtrl: failed to notification update rate or duration, check system.properties file.');
391                 } else {
392                         var rate = parseInt(res.response.updateRate);
393                                         var duration = parseInt(res.response.updateDuration);
394                                         notificationService.setMaxRefreshCount(parseInt(duration/rate)+1);
395                                         notificationService.setRefreshCount(notificationService.maxCount);
396                                 if (rate != NaN && duration != NaN) {
397                                                 $scope.updateRate=rate;
398                                                 $scope.start($scope.updateRate);
399                                 }                               
400                 }
401             }).catch(err=> {
402                 $log.error('NotificationCtrl: getNotificationRate() failed: ' + err);
403             });
404              
405              $scope.deleteNotification = function(index){
406                  if ($scope.notifications[index].id == null || $scope.notifications[index].id == '') {
407                         $log.error('NotificationCtrl: failed to delete Notification.');
408                         return;
409                  }
410                  notificationService.setNotificationRead($scope.notifications[index].id);
411                  $scope.notifications.splice(index,1);
412                  notificationService.setNotificationCount($scope.notifications.length);          
413              }
414         }
415     }
416     
417     NotificationCtrl.$inject = ['$log', '$scope', '$cookies', '$timeout', 'sessionService','notificationService','$interval','ngDialog','$modal'];
418     LoginSnippetCtrl.$inject = ['$log', '$scope', '$cookies', '$timeout','userProfileService', 'sessionService'];
419     HeaderCtrl.$inject = ['$log', '$window', 'userProfileService', 'menusService', '$scope', 'ECOMP_URL_REGEX','$cookies','$state','auditLogService','notificationService','ngDialog','$modal'];
420     angular.module('ecompApp').controller('HeaderCtrl', HeaderCtrl);
421     angular.module('ecompApp').controller('loginSnippetCtrl', LoginSnippetCtrl);
422     angular.module('ecompApp').controller('notificationCtrl', NotificationCtrl);
423 })();