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