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