cb914ffad7a2de31096a08a533476c6115dc420a
[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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
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             $scope.sort_type = userAppSortTypePref;
150
151             applicationsService
152                 .getAppsOrderBySortPref(userAppSortTypePref)
153                 .then(function(res) {
154                     _this.apps = res;
155                     $scope.applyPresentationDetailsToApps(_this.apps);
156                 })
157             applicationsService
158                 .saveAppsSortTypePreference($scope.selectedSortType)
159                 .then(function(res) {
160                     // Nothing to do
161                 })
162
163         }
164         $scope.$watch('selectedSortType.value', (newVal, oldVal) => {
165             for (var i = 0; i < $scope.sort_options.length; i++) {
166                 if ($scope.sort_options[i].value == newVal) {
167                     $scope.selectedSortType = angular.copy($scope.sort_options[i]);;
168                 }
169             }
170         });
171
172         $scope.restoreSortSelected = function() {
173             confirmBoxService.confirm("Restore the default size and position of all widgets?").then(
174                 function(confirmed) {
175                     var checkConfirm = confirmed;
176                     if (checkConfirm === true) {
177                         applicationsService
178                             .delWidgetsSortPref($scope.widgetsViewData).then(function() {
179                                 $state.reload();
180                             });
181                     }
182                 });
183             /*
184              * if(confirm('Restore the default size and position of all widgets?') ==
185              * true) { applicationsService
186              * .delWidgetsSortPref($scope.widgetsViewData).then(function(){
187              * $state.reload(); }) }
188              */
189
190         }
191
192         $scope.applyPresentationDetailsToApps = function(appsReturned) {
193             var rowNo = 0;
194             for (var i = 0; i < _this.apps.length; i++) {
195                 $scope.appsView[i] = {
196                     sizeX: 1,
197                     sizeY: 1,
198                     headerText: '',
199                     subHeaderText: '',
200                     imageLink: '',
201                     order: '',
202                     url: '',
203                     appid: '',
204                 };
205                 $scope.appsView[i].headerText = appsReturned[i].name;
206                 $scope.appsView[i].subHeaderText = appsReturned[i].notes;
207                 let imgLnk = '';
208                 if (appsReturned[i].imageUrl)
209                     imgLnk = conf.api.appThumbnail.replace(':appId', appsReturned[i].id);
210                 // $log.debug('DashboardCtlr::applyPresn: imgLink = ' + imgLnk);
211                 $scope.appsView[i].imageLink = imgLnk;
212                 $scope.appsView[i].order = appsReturned[i].order;
213                 $scope.appsView[i].url = appsReturned[i].url;
214                 $scope.appsView[i].restrictedApp = appsReturned[i].restrictedApp;
215                 $scope.appsView[i].appid = appsReturned[i].id;
216             }
217             $scope.appsView[_this.apps.length] = {
218                 addRemoveApps: true,
219                 sizeX: 1,
220                 sizeY: 1,
221                 headerText: 'Add/Remove Applications',
222                 subHeaderText: '',
223                 imageLink: 'assets/images/cloud.png',
224                 order: '',
225                 restrictedApp: false,
226                 url: '',
227             };
228             if ($scope.appsView.length > 6) {
229                 $(".dashboard-boarder").css({
230                     "height": "400px"
231                 });
232             } else {
233                 $(".dashboard-boarder").css({
234                     "height": "210px"
235                 });
236             }
237
238             if ($scope.appsView != undefined &&
239                 $scope.appsView != null &&
240                 $scope.appsView.length > 0) {
241                 $scope.appsViewData = $scope.appsView;
242             }
243         }
244
245         $scope.widgetsView = [];
246
247         $scope.applyPresentationDetailsToWidgets = function(widgetsReturned) {
248             var rowNo = 0;
249             for (var i = 0; i < widgetsReturned.length; i++) {
250                 $scope.widgetsView[i] = {
251                     sizeX: '',
252                     sizeY: '',
253                     headerText: '',
254                     widgetText: '',
255                     widgetIdentifier: '',
256                     url: '',
257                     widgetid: '',
258                     attrb: '',
259                     row: '',
260                     col: '',
261                 };
262                 $scope.widgetsView[i].widgetid = widgetsReturned[i].id;
263                 $scope.widgetsView[i].headerText = widgetsReturned[i].headerName;
264                 $scope.widgetsView[i].widgetText = widgetsReturned[i].name;
265
266                 if (widgetsReturned[i].headerName.toLowerCase() === 'news') {
267                     $scope.widgetsView[i].widgetIdentifier = 'NEWS';
268                 } else
269                 if (widgetsReturned[i].headerName.toLowerCase() === 'resources') {
270                     $scope.widgetsView[i].widgetIdentifier = 'IMPORTANTRESOURCES';
271                 } else
272                 if (widgetsReturned[i].headerName.toLowerCase() === 'events') {
273                     $scope.widgetsView[i].widgetIdentifier = 'EVENTS';
274                 }
275
276                 $scope.widgetsView[i].url = widgetsReturned[i].url;
277                 $scope.widgetsView[i].attrb = widgetsReturned[i].attrs;
278                 if (widgetsReturned[i].width === null) {
279                     $scope.widgetsView[i].sizeX = 2;
280                 } else {
281                     $scope.widgetsView[i].sizeX = widgetsReturned[i].width;
282                 }
283                 if (widgetsReturned[i].height === null) {
284                     $scope.widgetsView[i].sizeY = 2;
285                 } else {
286                     $scope.widgetsView[i].sizeY = widgetsReturned[i].height;
287                 }
288                 $scope.widgetsView[i].row = widgetsReturned[i].x;
289                 $scope.widgetsView[i].col = widgetsReturned[i].y;
290             }
291             if ($scope.widgetsView != undefined &&
292                 $scope.widgetsView != null &&
293                 $scope.widgetsView.length > 0) {
294                 $scope.widgetsViewData = $scope.widgetsView;
295             }
296         }
297
298         applicationsService
299             .getUserAppsSortTypePreference().then(function(res) {
300                 var resJson = {};
301                 resJson.value = res;
302                 if (resJson.value === "N" || resJson.value === "") {
303                     resJson.index = 0;
304                     resJson.title = 'Name';
305                 } else if (resJson.value === "L") {
306                     resJson.index = 1;
307                     resJson.title = 'Last used';
308                 } else if (resJson.value === "F") {
309                     resJson.index = 2;
310                     resJson.title = 'Most used';
311                 } else {
312                     resJson.index = 3;
313                     resJson.title = 'Manual';
314                 }
315                 $scope.selectedSortType = resJson;
316                 $scope.selectedSortTypeChanged(res);
317
318
319             });
320
321         $scope.widgetsList = [];
322
323         let getUserWidgets = (loginName) => {
324             var conf = this.conf;
325             widgetsCatalogService.getUserWidgets(loginName).then(res => {
326                 if (!(res instanceof Array)) {
327                     this.isCommError = true;
328                     return;
329                 }
330                 for (var i = 0; i < res.length; i++) {
331                     var widget_id = res[i][0];
332                     var widget_name = res[i][1];
333                     let url = this.conf.api.widgetCommon + "/" + widget_id + "/framework.js";
334                     var header_name = widget_name;
335                     if (res[i][7] == 1) {
336                         header_name = (widget_name.length > 9) ? widget_name.substring(0, 8) + '...' : widget_name;
337                     }
338                     if (res[i][4] === "S" || res[i][4] === null) {
339                         $scope.widgetsList.push({
340                             id: widget_id,
341                             headerName: header_name,
342                             name: widget_name,
343                             url: url,
344                             attrs: [{
345                                 attr: 'data-' + res[i][0],
346                                 value: ''
347                             }],
348                             x: res[i][3],
349                             y: res[i][5],
350                             height: res[i][6],
351                             width: res[i][7]
352                         });
353                     }
354                     var script = document
355                         .createElement('script');
356                     script.src = url;
357                     script.async = false;
358                     var entry = document
359                         .getElementsByTagName('script')[0];
360                     entry.parentNode
361                         .insertBefore(script, entry);
362                 }
363                 $scope.applyPresentationDetailsToWidgets($scope.widgetsList);
364             }).catch(err => {
365                 $log.error('WidgetsHomeCtrl::getUserWidgets error: ' + err);
366             }).finally(() => {
367
368             });
369         };
370
371         userProfileService.getUserProfile().then(
372             function(profile) {
373                 $scope.orgUserId = profile.orgUserId;
374                 getUserWidgets($scope.orgUserId);
375             });
376
377         /* Widget Gridster Section */
378         $scope.newsGridsterItem = {
379             sizeX: 1,
380             sizeY: 1,
381             headerText: 'News',
382             subHeaderText: '',
383             imageLink: '',
384             order: '',
385             url: ''
386         };
387
388         $scope.eventsGridsterItem = {
389             sizeX: 1,
390             sizeY: 1,
391             headerText: 'Events',
392             subHeaderText: '',
393             imageLink: '',
394             order: '',
395             url: ''
396         };
397
398         $scope.impoResGridsterItem = {
399             sizeX: 1,
400             sizeY: 1,
401             headerText: 'Resources',
402             subHeaderText: '',
403             imageLink: '',
404             order: '',
405             url: ''
406         };
407
408         this.gridsterAppOpts = {
409             columns: 6,
410             colWidth: 190,
411             rowHeight: 190,
412             margins: [20, 20],
413             outerMargin: true,
414             pushing: true,
415             floating: true,
416             swapping: true,
417             resizable: {
418                 enabled: false,
419             },
420             draggable: {
421                 handle: '.icon-content-gridguide',
422                 stop: function stop() {
423                     $scope.defaultSortBy = function() {
424                         var resJson = {};
425                         resJson.value = 'M';
426                         resJson.index = 3;
427                         resJson.title = 'Manual';
428                         $scope.selectedSortType = resJson;
429                         applicationsService.saveAppsSortTypeManual($scope.appsViewData)
430                         applicationsService.saveAppsSortTypePreference($scope.selectedSortType)
431                     }
432                     $scope.defaultSortBy();
433                 }
434             }
435         };
436
437         this.gridsterWidgetOpts = {
438             columns: 6,
439             colWidth: 190,
440             rowHeight: 190,
441             margins: [20, 20],
442             outerMargin: true,
443             pushing: true,
444             floating: true,
445             swapping: true,
446             resizable: {
447                 enabled: true,
448                 stop: function stop(event, uiWidget, $element) {
449                     if ($element.sizeX == 1)
450                         $element.headerText = ($element.widgetText.length > 9) ? $element.widgetText.substring(0, 8) + '...' : $element.widgetText;
451                     if ($element.sizeX >= 2)
452                         $element.headerText = $element.widgetText;
453
454                     applicationsService
455                         .saveWidgetsSortManual($scope.widgetsViewData)
456
457                 }
458             },
459             draggable: {
460                 handle: '.icon-content-gridguide',
461                 stop: function stop() {
462                     applicationsService
463                         .saveWidgetsSortManual($scope.widgetsViewData)
464
465                 }
466             }
467         };
468
469         this.goToCatalog = function(item) {
470             $state.go('root.appCatalog');
471         }
472
473         this.goToWidgetCatLog = function(item) {
474             $state.go('root.widgetCatalog');
475         }
476
477         // navigate to application url in new tab
478         this.goToPortal = function(item) {
479
480             if (!item.url) {
481                 $log.error('No URL found for this application, doing nothing!');
482                 return;
483             }
484             if (item.restrictedApp) {
485                 // Link-based apps open in their own browser tab
486                 $window.open(item.url, '_blank');
487             } else {
488                 // cache control so browsers load app page every
489                 // time
490                 var ccParam = 'cc=' + new Date().getTime();
491                 var urlParts = item.url.split('#');
492                 var appUrl = null;
493                 if (urlParts.length < 2) {
494                     // no #
495                     let urlLastChar = item.url.charAt(item.url.length - 1);
496                     if (item.url.includes("?"))
497                         appUrl = (urlLastChar === '&' ? item.url + ccParam : item.url + '&' + ccParam);
498                     else
499                         appUrl = item.url + '?' + ccParam;
500                 } else {
501                     // has #
502                     let urlLastChar = urlParts[0].charAt(urlParts[0].length - 1);
503                     if (item.url.includes("?"))
504                         appUrl = (urlLastChar === '&' ? urlParts[0] + ccParam + '#' + urlParts[1] : urlParts[0] + '&' + ccParam + '#' + urlParts[1]);
505                     else
506                         appUrl = urlParts[0] + '?' + ccParam + "#" + urlParts[1];
507                 }
508                 // $log.debug('DashboardCtrlr::goToPortal: opening
509                 // tab with URL
510                 // ' + appUrl);
511                 var tabContent = {
512                     id: new Date(),
513                     title: item.headerText,
514                     url: appUrl,
515                     appId: item.appid
516                 };
517                 $cookies.putObject('addTab', tabContent);
518             }
519
520
521         
522         };
523
524         this.auditLog = function(app) {
525             console.log(app);
526             auditLogService.storeAudit(app.appid, 'app', app.url);
527         };
528
529         if (getParameterByName('noUserError') != null) {
530             if (getParameterByName('noUserError') == "Show") {
531                 $("#errorInfo").show();
532             }
533         }
534     };
535
536     DashboardCtrl.$inject = ['conf', 'applicationsService', '$log', '$window',
537         'userProfileService', '$scope', '$cookies', '$timeout', '$interval',
538         '$modal', '$state', 'beReaderService', 'dashboardService', 'confirmBoxService',
539         'auditLogService', 'ngDialog', '$compile', 'widgetsCatalogService'
540     ];
541     angular.module('ecompApp').controller('DashboardCtrl', DashboardCtrl);
542 })();
543
544 function getParameterByName(name, url) {
545     if (!url)
546         url = window.location.href;
547     name = name.replace(/[\[\]]/g, "\\$&");
548     var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
549         results = regex
550         .exec(url);
551     if (!results)
552         return '';
553     if (!results[2])
554         return '';
555     return results[2].replace(/\+/g, " ");
556 }