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