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