JUnits for coverage
[portal.git] / ecomp-portal-FE-common / client / app / views / dashboard / dashboard.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  * 
37  */
38 'use strict';
39
40 function _classCallCheck(instance, Constructor) {
41     if (!(instance instanceof Constructor)) {
42         throw new TypeError('Cannot call a class as a function');
43     }
44 }
45
46 (function() {
47     var HTTP_PROTOCOL_RGX = /https?:\/\//;
48
49     var DashboardCtrl = function DashboardCtrl(conf, applicationsService, $log,
50         $window, userProfileService, $scope, $cookies, $timeout, $interval,
51         $modal, $state, beReaderService, dashboardService, confirmBoxService,
52         auditLogService, ngDialog, $compile, widgetsCatalogService) {
53
54         this.conf = conf;
55         var _this = this;
56
57         _classCallCheck(this, DashboardCtrl);
58
59         // activate spinner
60         this.isLoading = true;
61         this.isCommError = false;
62         $scope.getUserAppsIsDone = false;
63         this.userProfileService = userProfileService;
64         $scope.demoNum = 1;
65         $scope.event_content_show = false;
66         $scope.widgetData = [];
67         $scope.activateThis = function(ele) {
68             $compile(ele.contents())($scope);
69             $scope.$apply();
70         };
71
72         $scope.editWidgetModalPopup = function(availableData, resourceType) {
73             $scope.editData = JSON.stringify(availableData);
74             $scope.availableDataTemp = $scope.availableData;
75             var modalInstance = $modal.open({
76                 templateUrl: 'app/views/dashboard/dashboard-widget-manage.html',
77                 controller: 'CommonWidgetController',
78                 windowClass: 'modal-docked',
79                 resolve: {
80                     message: function message() {
81                         var message = {
82                             type: resourceType,
83                             availableData: $scope.editData
84                         };
85                         return message;
86                     }
87                 }
88             })
89             
90             modalInstance.result.finally(function (needUpdate){
91                    if (resourceType == 'NEWS') {
92                        $scope.updateNews();
93                    } else if (resourceType == 'EVENTS') {
94                        $scope.updateEvents();
95                    } else if (resourceType == 'IMPORTANTRESOURCES') {
96                        $scope.updateImportRes();
97                    }
98                 });
99         };
100
101         $scope.editWidgetParameters = function(widgetId) {
102             let data = {
103                 widgetId: widgetId
104             }
105             var modalInstance = $modal.open({
106                 templateUrl: 'app/views/dashboard/dashboard-widget-parameter-manage.html',
107                 controller: 'WidgetParameterController',
108                 windowClass: 'modal-docked',
109
110                 resolve: {
111                                         items: function () {
112                           return data;
113                                         }
114                         }
115             })
116             
117             modalInstance.result.then(function (needUpdate) {
118               });
119         };
120
121     
122
123         $scope.sort_options = [{
124                 index: 0,
125                 value: 'N',
126                 title: 'Name'
127             },
128             {
129                 index: 1,
130                 value: 'L',
131                 title: 'Last used'
132             },
133             {
134                 index: 2,
135                 value: 'F',
136                 title: 'Most used'
137             },
138             {
139                 index: 3,
140                 value: 'M',
141                 title: 'Manual'
142             }
143         ];
144
145         $scope.selectedSortTypeChanged = function(userAppSortTypePref) {
146             $scope.appsViewData = [];
147             $scope.appsView = [];
148
149             if(userAppSortTypePref == ""){
150                 $scope.selectedSortType = $scope.sort_options[0];
151             } else {
152                 angular.forEach($scope.sort_options, function(sort_type, key){
153                         if(sort_type.value == userAppSortTypePref)
154                                 $scope.selectedSortType = sort_type;
155                 });
156             }
157
158             applicationsService
159                 .getAppsOrderBySortPref(userAppSortTypePref)
160                 .then(function(res) {
161                     _this.apps = res;
162                     $scope.applyPresentationDetailsToApps(_this.apps);
163                 })
164             applicationsService
165                 .saveAppsSortTypePreference($scope.selectedSortType)
166                 .then(function(res) {
167                     // Nothing to do
168                 })
169
170         }
171         $scope.$watch('selectedSortType.value', (newVal, oldVal) => {
172             for (var i = 0; i < $scope.sort_options.length; i++) {
173                 if ($scope.sort_options[i].value == newVal) {
174                     $scope.selectedSortType = angular.copy($scope.sort_options[i]);;
175                 }
176             }
177         });
178
179         $scope.restoreSortSelected = function() {
180             confirmBoxService.confirm("Restore the default size and position of all widgets?").then(
181                 function(confirmed) {
182                     var checkConfirm = confirmed;
183                     if (checkConfirm === true) {
184                         applicationsService
185                             .delWidgetsSortPref($scope.widgetsViewData).then(function() {
186                                 $state.reload();
187                             });
188                     }
189                 });
190             /*
191              * if(confirm('Restore the default size and position of all widgets?') ==
192              * true) { applicationsService
193              * .delWidgetsSortPref($scope.widgetsViewData).then(function(){
194              * $state.reload(); }) }
195              */
196
197         }
198
199         $scope.applyPresentationDetailsToApps = function(appsReturned) {
200             var rowNo = 0;
201             for (var i = 0; i < _this.apps.length; i++) {
202                 $scope.appsView[i] = {
203                     sizeX: 1,
204                     sizeY: 1,
205                     headerText: '',
206                     subHeaderText: '',
207                     imageLink: '',
208                     order: '',
209                     url: '',
210                     appid: '',
211                 };
212                 $scope.appsView[i].headerText = appsReturned[i].name;
213                 $scope.appsView[i].subHeaderText = appsReturned[i].notes;
214                 let imgLnk = '';
215                 if (appsReturned[i].imageUrl)
216                     imgLnk = conf.api.appThumbnail.replace(':appId', appsReturned[i].id);
217                 // $log.debug('DashboardCtlr::applyPresn: imgLink = ' + imgLnk);
218                 $scope.appsView[i].imageLink = imgLnk;
219                 $scope.appsView[i].order = appsReturned[i].order;
220                 $scope.appsView[i].url = appsReturned[i].url;
221                 $scope.appsView[i].restrictedApp = appsReturned[i].restrictedApp;
222                 $scope.appsView[i].appid = appsReturned[i].id;
223             }
224             $scope.appsView[_this.apps.length] = {
225                 addRemoveApps: true,
226                 sizeX: 1,
227                 sizeY: 1,
228                 headerText: 'Add/Remove Applications',
229                 subHeaderText: '',
230                 imageLink: 'assets/images/cloud.png',
231                 order: '',
232                 restrictedApp: false,
233                 url: '',
234             };
235             if ($scope.appsView.length > 6) {
236                 $(".dashboard-boarder").css({
237                     "height": "400px"
238                 });
239             } else {
240                 $(".dashboard-boarder").css({
241                     "height": "210px"
242                 });
243             }
244
245             if ($scope.appsView != undefined &&
246                 $scope.appsView != null &&
247                 $scope.appsView.length > 0) {
248                 $scope.appsViewData = $scope.appsView;
249             }
250         }
251
252         $scope.widgetsView = [];
253
254         $scope.applyPresentationDetailsToWidgets = function(widgetsReturned) {
255             var rowNo = 0;
256             for (var i = 0; i < widgetsReturned.length; i++) {
257                 $scope.widgetsView[i] = {
258                     sizeX: '',
259                     sizeY: '',
260                     headerText: '',
261                     widgetText: '',
262                     widgetIdentifier: '',
263                     url: '',
264                     widgetid: '',
265                     attrb: '',
266                     row: '',
267                     col: '',
268                 };
269                 $scope.widgetsView[i].widgetid = widgetsReturned[i].id;
270                 $scope.widgetsView[i].headerText = widgetsReturned[i].headerName;
271                 $scope.widgetsView[i].widgetText = widgetsReturned[i].name;
272
273                 if (widgetsReturned[i].headerName.toLowerCase() === 'news') {
274                     $scope.widgetsView[i].widgetIdentifier = 'NEWS';
275                 } else
276                 if (widgetsReturned[i].headerName.toLowerCase() === 'resources') {
277                     $scope.widgetsView[i].widgetIdentifier = 'IMPORTANTRESOURCES';
278                 } else
279                 if (widgetsReturned[i].headerName.toLowerCase() === 'events') {
280                     $scope.widgetsView[i].widgetIdentifier = 'EVENTS';
281                 }
282
283                 $scope.widgetsView[i].url = widgetsReturned[i].url;
284                 $scope.widgetsView[i].attrb = widgetsReturned[i].attrs;
285                 if (widgetsReturned[i].width === null) {
286                     $scope.widgetsView[i].sizeX = 2;
287                 } else {
288                     $scope.widgetsView[i].sizeX = widgetsReturned[i].width;
289                 }
290                 if (widgetsReturned[i].height === null) {
291                     $scope.widgetsView[i].sizeY = 2;
292                 } else {
293                     $scope.widgetsView[i].sizeY = widgetsReturned[i].height;
294                 }
295                 $scope.widgetsView[i].row = widgetsReturned[i].x;
296                 $scope.widgetsView[i].col = widgetsReturned[i].y;
297             }
298             if ($scope.widgetsView != undefined &&
299                 $scope.widgetsView != null &&
300                 $scope.widgetsView.length > 0) {
301                 $scope.widgetsViewData = $scope.widgetsView;
302             }
303         }
304
305         applicationsService
306             .getUserAppsSortTypePreference().then(function(res) {
307                 var resJson = {};
308                 resJson.value = res;
309                 if (resJson.value === "N" || resJson.value === "") {
310                     resJson.index = 0;
311                     resJson.title = 'Name';
312                 } else if (resJson.value === "L") {
313                     resJson.index = 1;
314                     resJson.title = 'Last used';
315                 } else if (resJson.value === "F") {
316                     resJson.index = 2;
317                     resJson.title = 'Most used';
318                 } else {
319                     resJson.index = 3;
320                     resJson.title = 'Manual';
321                 }
322                 $scope.selectedSortType = resJson;
323                 $scope.selectedSortTypeChanged(res);
324
325
326             });
327
328         $scope.widgetsList = [];
329
330         let getUserWidgets = (loginName) => {
331             var conf = this.conf;
332             widgetsCatalogService.getUserWidgets(loginName).then(res => {
333                 if (!(res instanceof Array)) {
334                     this.isCommError = true;
335                     return;
336                 }
337                 for (var i = 0; i < res.length; i++) {
338                     var widget_id = res[i][0];
339                     var widget_name = res[i][1];
340                     let url = this.conf.api.widgetCommon + "/" + widget_id + "/framework.js";
341                     var header_name = widget_name;
342                     if (res[i][7] == 1) {
343                         header_name = (widget_name.length > 9) ? widget_name.substring(0, 8) + '...' : widget_name;
344                     }
345                     if (res[i][4] === "S" || res[i][4] === null) {
346                         $scope.widgetsList.push({
347                             id: widget_id,
348                             headerName: header_name,
349                             name: widget_name,
350                             url: url,
351                             attrs: [{
352                                 attr: 'data-' + res[i][0],
353                                 value: ''
354                             }],
355                             x: res[i][3],
356                             y: res[i][5],
357                             height: res[i][6],
358                             width: res[i][7]
359                         });
360                     }
361                     var script = document
362                         .createElement('script');
363                     script.src = url;
364                     script.async = false;
365                     var entry = document
366                         .getElementsByTagName('script')[0];
367                     entry.parentNode
368                         .insertBefore(script, entry);
369                 }
370                 $scope.applyPresentationDetailsToWidgets($scope.widgetsList);
371             }).catch(err => {
372                 $log.error('WidgetsHomeCtrl::getUserWidgets error: ' + err);
373             }).finally(() => {
374
375             });
376         };
377
378         userProfileService.getUserProfile().then(
379             function(profile) {
380                 $scope.orgUserId = profile.orgUserId;
381                 getUserWidgets($scope.orgUserId);
382             });
383
384         /* Widget Gridster Section */
385         $scope.newsGridsterItem = {
386             sizeX: 1,
387             sizeY: 1,
388             headerText: 'News',
389             subHeaderText: '',
390             imageLink: '',
391             order: '',
392             url: ''
393         };
394
395         $scope.eventsGridsterItem = {
396             sizeX: 1,
397             sizeY: 1,
398             headerText: 'Events',
399             subHeaderText: '',
400             imageLink: '',
401             order: '',
402             url: ''
403         };
404
405         $scope.impoResGridsterItem = {
406             sizeX: 1,
407             sizeY: 1,
408             headerText: 'Resources',
409             subHeaderText: '',
410             imageLink: '',
411             order: '',
412             url: ''
413         };
414
415         this.gridsterAppOpts = {
416             columns: 6,
417             colWidth: 190,
418             rowHeight: 190,
419             margins: [20, 20],
420             outerMargin: true,
421             pushing: true,
422             floating: true,
423             swapping: true,
424             resizable: {
425                 enabled: false,
426             },
427             draggable: {
428                 handle: '.icon-content-gridguide',
429                 stop: function stop() {
430                     $scope.defaultSortBy = function() {
431                         var resJson = {};
432                         resJson.value = 'M';
433                         resJson.index = 3;
434                         resJson.title = 'Manual';
435                         $scope.selectedSortType = resJson;
436                         applicationsService.saveAppsSortTypeManual($scope.appsViewData)
437                         applicationsService.saveAppsSortTypePreference($scope.selectedSortType)
438                     }
439                     $scope.defaultSortBy();
440                 }
441             }
442         };
443
444         this.gridsterWidgetOpts = {
445             columns: 6,
446             colWidth: 190,
447             rowHeight: 190,
448             margins: [20, 20],
449             outerMargin: true,
450             pushing: true,
451             floating: true,
452             swapping: true,
453             resizable: {
454                 enabled: true,
455                 stop: function stop(event, uiWidget, $element) {
456                     if ($element.sizeX == 1)
457                         $element.headerText = ($element.widgetText.length > 9) ? $element.widgetText.substring(0, 8) + '...' : $element.widgetText;
458                     if ($element.sizeX >= 2)
459                         $element.headerText = $element.widgetText;
460
461                     applicationsService
462                         .saveWidgetsSortManual($scope.widgetsViewData)
463
464                 }
465             },
466             draggable: {
467                 handle: '.icon-content-gridguide',
468                 stop: function stop() {
469                     applicationsService
470                         .saveWidgetsSortManual($scope.widgetsViewData)
471
472                 }
473             }
474         };
475
476         this.goToCatalog = function(item) {
477             $state.go('root.appCatalog');
478         }
479
480         this.goToWidgetCatLog = function(item) {
481             $state.go('root.widgetCatalog');
482         }
483
484         // navigate to application url in new tab
485         this.goToPortal = function(item) {
486
487             if (!item.url) {
488                 $log.error('No URL found for this application, doing nothing!');
489                 return;
490             }
491             if (item.restrictedApp) {
492                 // Link-based apps open in their own browser tab
493                 $window.open(item.url, '_blank');
494             } else {
495                 // cache control so browsers load app page every
496                 // time
497                 var ccParam = 'cc=' + new Date().getTime();
498                 var urlParts = item.url.split('#');
499                 var appUrl = null;
500                 if (urlParts.length < 2) {
501                     // no #
502                     let urlLastChar = item.url.charAt(item.url.length - 1);
503                     if (item.url.includes("?"))
504                         appUrl = (urlLastChar === '&' ? item.url + ccParam : item.url + '&' + ccParam);
505                     else
506                         appUrl = item.url + '?' + ccParam;
507                 } else {
508                     // has #
509                     let urlLastChar = urlParts[0].charAt(urlParts[0].length - 1);
510                     if (item.url.includes("?"))
511                         appUrl = (urlLastChar === '&' ? urlParts[0] + ccParam + '#' + urlParts[1] : urlParts[0] + '&' + ccParam + '#' + urlParts[1]);
512                     else
513                         appUrl = urlParts[0] + '?' + ccParam + "#" + urlParts[1];
514                 }
515                 // $log.debug('DashboardCtrlr::goToPortal: opening
516                 // tab with URL
517                 // ' + appUrl);
518                 var tabContent = {
519                     id: new Date(),
520                     title: item.headerText,
521                     url: appUrl,
522                     appId: item.appid
523                 };
524                 $cookies.putObject('addTab', tabContent);
525             }
526
527
528         
529         };
530
531         this.auditLog = function(app) {
532             console.log(app);
533             auditLogService.storeAudit(app.appid, 'app', app.url);
534         };
535
536         if (getParameterByName('noUserError') != null) {
537             if (getParameterByName('noUserError') == "Show") {
538                 $("#errorInfo").show();
539             }
540         }
541     };
542
543     DashboardCtrl.$inject = ['conf', 'applicationsService', '$log', '$window',
544         'userProfileService', '$scope', '$cookies', '$timeout', '$interval',
545         '$modal', '$state', 'beReaderService', 'dashboardService', 'confirmBoxService',
546         'auditLogService', 'ngDialog', '$compile', 'widgetsCatalogService'
547     ];
548     angular.module('ecompApp').controller('DashboardCtrl', DashboardCtrl);
549 })();
550
551 function getParameterByName(name, url) {
552     if (!url)
553         url = window.location.href;
554     name = name.replace(/[\[\]]/g, "\\$&");
555     var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
556         results = regex
557         .exec(url);
558     if (!results)
559         return '';
560     if (!results[2])
561         return '';
562     return results[2].replace(/\+/g, " ");
563 }