aboutsummaryrefslogtreecommitdiffstats
path: root/3rd_party/static/onap-ui/components/results/resultsController.js
blob: e8187f3092a556fcf8c1831c28531a3885457c92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function () {
    'use strict';

    angular
        .module('testapiApp')
        .controller('ResultsController', ResultsController);

    angular
        .module('testapiApp')
        .directive('fileModel', ['$parse', function ($parse) {
            return {
                restrict: 'A',
                link: function(scope, element, attrs) {
                    var model = $parse(attrs.fileModel);
                    var modelSetter = model.assign;

                    element.bind('change', function(){
                        scope.$apply(function(){
                            modelSetter(scope, element[0].files[0]);
                        });
                    });
                }
            };
        }]);

    angular
        .module('testapiApp')
        .directive('modalFileModel', ['$parse', function ($parse) {
            return {
                restrict: 'A',
                link: function(scope, element, attrs) {
                    var model = $parse(attrs.modalFileModel);
                    var modelSetter = model.assign;

                    element.bind('change', function(){
                        scope.$apply(function(){
                            modelSetter(scope.$parent, element[0].files[0]);
                        });
                    });
                }
            };
        }]);

    ResultsController.$inject = [
        '$scope', '$http', '$filter', '$state', 'testapiApiUrl','raiseAlert', 'ngDialog', '$resource'
    ];

    /**
     * TestAPI Results Controller
     * This controller is for the '/results' page where a user can browse
     * a listing of community uploaded results.
     */
    function ResultsController($scope, $http, $filter, $state, testapiApiUrl, raiseAlert, ngDialog, $resource) {
        var ctrl = this;

        ctrl.uploadFile=uploadFile;
        ctrl.update = update;
        ctrl.open = open;
        ctrl.clearFilters = clearFilters;
        ctrl.associateMeta = associateMeta;
        ctrl.gotoResultDetail = gotoResultDetail;
        ctrl.toggleCheck = toggleCheck;
        ctrl.changeLabel = changeLabel;
        ctrl.toApprove = toApprove;
        ctrl.toDisapprove = toDisapprove;
        ctrl.toUndo = toUndo;
        ctrl.toReview = toReview;
        ctrl.toPrivate = toPrivate;
        ctrl.removeSharedUser = removeSharedUser;
        ctrl.addSharedUser = addSharedUser;
        ctrl.openSharedModal = openSharedModal;
        ctrl.downloadLogs = downloadLogs;
        ctrl.deleteApplication = deleteApplication;
        ctrl.deleteTest = deleteTest;
        ctrl.openApplicationModal = openApplicationModal;
        ctrl.openApplicationView = openApplicationView;
        ctrl.submitApplication = submitApplication;
        ctrl.openConfirmModal = openConfirmModal;
        ctrl.openReviewsModal = openReviewsModal;

        /** Mappings of Interop WG components to marketing program names. */
        ctrl.targetMappings = {
            'platform': 'Openstack Powered Platform',
            'compute': 'OpenStack Powered Compute',
            'object': 'OpenStack Powered Object Storage'
        };

        /** Initial page to be on. */
        ctrl.currentPage = 1;

        /**
         * How many results should display on each page. Since pagination
         * is server-side implemented, this value should match the
         * 'results_per_page' configuration of the TestAPI server which
         * defaults to 20.
         */
        ctrl.itemsPerPage = 20;

        /**
         * How many page buttons should be displayed at max before adding
         * the '...' button.
         */
        ctrl.maxSize = 5;

        /** The upload date lower limit to be used in filtering results. */
        ctrl.startDate = '';

        /** The upload date upper limit to be used in filtering results. */
        ctrl.endDate = '';

        /** The date format for the date picker. */
        ctrl.format = 'yyyy-MM-dd';

        ctrl.userName = null;

        /** Check to see if this page should display user-specific results. */
        ctrl.isUserResults = $state.current.name === 'userResults';

        /** Check to see if this page should display community results. */
        ctrl.isReviewer = $scope.auth.currentUser.role.indexOf('reviewer') != -1;
        ctrl.isAdministrator = $scope.auth.currentUser.role.indexOf('administrator') != -1;

        ctrl.currentUser = $scope.auth.currentUser ? $scope.auth.currentUser.openid : null;

        // Should only be on user-results-page if authenticated.
        if (!$scope.auth.isAuthenticated) {
            $state.go('home');
        }
        // Should only be on community-results if reviewer
        if (!ctrl.isUserResults && !ctrl.isReviewer) {
            $state.go('home');
        }

        ctrl.pageHeader = ctrl.isUserResults ?
            'Private test results' : 'Community test results';

        ctrl.pageParagraph = ctrl.isUserResults ?
            'Your most recently uploaded test results are listed here.' :
            'The most recently uploaded community test results are listed ' +
            'here.';

        ctrl.uploadState = '';

        ctrl.authRequest = $scope.auth.doSignCheck().then(ctrl.update);

        function downloadLogs(id) {
            // var logsUrl = testapiApiUrl + "/logs/log_" + id+".tar.gz";
            var logsUrl = "/logs/" + id + "/results/";
            window.location.href = logsUrl;
            // $http.get(logsUrl);
        }

        function deleteTest(inner_id) {
          var resp = confirm('Are you sure to delete this test?');
          if (!resp)
            return;

          var delUrl = testapiApiUrl + "/onap/tests/" + inner_id;
          $http.get(delUrl)
            .then( function(resp) {
              var results = resp.data.results;
              $http.delete(delUrl)
                .then( function(ret) {
                  if(ret.data.code && ret.data.code != 0) {
                    alert(ret.data.msg);
                    return;
                  }
                  ctrl.update();
                  angular.forEach(results, function(ele) {
                    delUrl = testapiApiUrl + "/results/" + ele;
                    $http.delete(delUrl);
                  });
                });
            });
        }

        function deleteApplication (result) {
            var resp = confirm('Are you sure you want to delete this application?');
            if (!resp)
                return;

            $http.get(testapiApiUrl + "/onap/cvp/applications?test_id=" + result.id).then(function(response) {
                    ctrl.application = response.data.applications[0];
                    var app_id = ctrl.application._id;
                    var delUrl = testapiApiUrl + "/cvp/applications/" + app_id;
                    $http.delete(delUrl)
                        .then(function(ret) {
                        if (ret.data.code && ret.data.code != 0) {
                            alert(ret.data.msg);
                            return;
                        }
                        result['status'] = 'private';
                    });

                }, function(error) {
                    /* do nothing */
                });

        }

        function submitApplication(result) {
            var file = $scope.logoFile;
            var logo_name = null;
            if (typeof file !== 'undefined') {

                var fd = new FormData();
                fd.append('file', file);
                fd.append('company_name', ctrl.company_name)

                $http.post(testapiApiUrl + "/cvp/applications/uploadlogo", fd, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                }).then(function(resp) {
                    if (resp.data.code && resp.data.code != 0) {
                        alert(resp.data.msg);
                        return;
                    } else {
                        logo_name = resp.data.filename;
                        var data = {
                            "description": ctrl.description,
                            "onap_version": result.version,
                            "company_name": ctrl.company_name,
                            "company_logo": logo_name,
                            "company_website": ctrl.company_website,
                            "approve_date": "",
                            "approved": "false",
                            "test_id": result.id,
                            "lab_location": ctrl.lab_location,
                            "lab_email": ctrl.lab_email,
                            "lab_address": ctrl.lab_address,
                            "lab_phone": ctrl.lab_phone,
                            "xnf_version": ctrl.xnf_version,
                            "certification_type": ctrl.certification_type,
                            "xnf_name": ctrl.xnf_name,
                            "xnf_type": ctrl.xnf_type,
                            "xnf_description": ctrl.xnf_description,
                            "xnfd_id": ctrl.xnfd_id,
                            "xnfd_model_lang": result.vnf_type.toUpperCase(),
                            "xnf_checksum": result.vnf_checksum,
                            "xnf_test_period": ctrl.xnf_test_period,
                            "primary_contact_name": ctrl.primary_contact_name,
                            "primary_phone_number": ctrl.primary_phone_number,
                            "primary_business_email": ctrl.primary_business_email
                        };

                        if (ctrl.company_name == null ||
                        ctrl.company_website == null ||
                        ctrl.primary_contact_name == null ||
                        ctrl.primary_phone_number == null ||
                        ctrl.primary_business_email== null ||
                        ctrl.xnf_version == null ||
                        ctrl.xnf_name == null ||
                        ctrl.xnf_description == null ||
                        ctrl.xnfd_id == null) {

                            alert('There are empty required fields in the application form');

                        } else if (ctrl.lab_location == 'third') {
                            if (ctrl.lab_name == null ||
                            ctrl.lab_email == null ||
                            ctrl.lab_address == null ||
                            ctrl.lab_phone == null) {

                            alert('There are empty required fields in the application form');

                            } else {
                                $http.post(testapiApiUrl + "/onap/cvp/applications", data).then(function(resp) {
                                    if (resp.data.code && resp.data.code != 0) {
                                        alert(resp.data.msg);
                                        return;
                                    }
                                    toggleCheck(result, 'status', 'review');
                                }, function(error) {
                                    /* do nothing */
                                });
                            }
                        } else {
                            $http.post(testapiApiUrl + "/onap/cvp/applications", data).then(function(resp) {
                                if (resp.data.code && resp.data.code != 0) {
                                    alert(resp.data.msg);
                                    return;
                                }
                                toggleCheck(result, 'status', 'review');
                            }, function(error) {
                                /* do nothing */
                            });
                        }
                    }
                }, function(error) {
                    /* do nothing */
                });
                logo_name = file.name;
            }

            if (typeof file === 'undefined') {
                alert('There are empty required fields in the application form');
            }
            ngDialog.close();
        }

        function openConfirmModal(result) {
            var resp = confirm("Are you sure to submit?");
            if (resp) {
                ctrl.submitApplication(result);
            }
        }

        function openApplicationModal(result) {
            ctrl.tempResult = result;
                ngDialog.open({
                    preCloseCallback: function(value) {
                    },
                    template: 'onap-ui/components/results/modal/applicationModal.html',
                    scope: $scope,
                    className: 'ngdialog-theme-default custom-background',
                    width: 950,
                    showClose: true,
                    closeByDocument: true
                });
        }

        function openApplicationView(result) {

           $http.get(testapiApiUrl + "/onap/cvp/applications?test_id=" + result.id).then(function(response) {
                    ctrl.application = response.data.applications[0];
                }, function(error) {
                    /* do nothing */
                });

            ctrl.tempResult = result;
                ngDialog.open({
                    preCloseCallback: function(value) {
                    },
                    template: 'onap-ui/components/results/modal/applicationView.html',
                    scope: $scope,
                    className: 'ngdialog-theme-default custom-background',
                    width: 950,
                    showClose: true,
                    closeByDocument: true
                });
        }

        function getReviews(test) {
            var reviews_url = testapiApiUrl + '/onap/reviews?test_id=' + test;
            ctrl.reviewsRequest =
                $http.get(reviews_url).success(function (data) {
                    ctrl.reviews = data.reviews;
                }).error(function (error) {
                    ctrl.reviews = null;
                });
        }

        function openReviewsModal(test) {
            getReviews(test);
            ngDialog.open({
                preCloseCallback: function(value) {
                },
                template: 'onap-ui/components/results/modal/reviewsModal.html',
                scope: $scope,
                className: 'ngdialog-theme-default custom-background',
                width: 950,
                showClose: true,
                closeByDocument: true
            });
        }

        function toggleCheck(result, item, newValue) {
            var id = result._id;
            var updateUrl = testapiApiUrl + "/onap/tests/"+ id;

            var data = {};
            data['item'] = item;
            data[item] = newValue;

            $http.put(updateUrl, JSON.stringify(data), {
                transformRequest: angular.identity,
                headers: {'Content-Type': 'application/json'}}).then(function(ret) {
                    if(ret.data.code && ret.data.code != 0) {
                        alert(ret.data.msg);
                    } else {
                        result[item] = newValue;
                    }
            }, function(error) {
                alert('Error when update data');
            });
        }

        function changeLabel(result, key, data){
            if (result[key] !== data) {
                toggleCheck(result, key, data);
            }
        }

        function doReview(test, outcome) {
            var createUrl = testapiApiUrl + "/onap/reviews";
            var data = {
                'test_id': test.id,
                'outcome': outcome
            };

            $http.post(createUrl, JSON.stringify(data), {
                transformRequest: angular.identity,
                headers: {'Content-Type': 'application/json'}}).then(function(ret) {
                    if (ret.data.code && ret.data.code != 0) {
                        alert(ret.data.msg);
                    } else {
                        if (outcome === null) {
                            test.voted = 'false';
                        } else {
                            test.voted = 'true';
                        }
                    }
            }, function(error) {
                alert('Error when creating review');
            });
        }

        function toApprove(test) {
            var resp = confirm('Once you approve a test result, your action will become visible. Do you want to proceed?');
            if (resp) {
                doReview(test, 'positive');
            }
        }

        function toDisapprove(test) {
            var resp = confirm('Once you disapprove a test result, your action will become visible. Do you want to proceed?');
            if (resp) {
                doReview(test, 'negative');
            }
        }

        function toUndo(test) {
            var resp = confirm('Once you undo your previous vote, your action will become visible. Do you want to proceed?');
            if (resp) {
                doReview(test, null);
            }
        }

        function toReview(result, value){
            var resp = confirm('Once you submit a test result for review, it will become readable to all ONAPVP reviewers. Do you want to proceed?');
            if(resp){
                toggleCheck(result, 'status', value);
            }
        }

        function toPrivate(result, value){
            var resp = confirm('Do you want to proceed?');
            if(resp){
                toggleCheck(result, 'status', value);
            }
        }

        function openSharedModal(result){
            ctrl.tempResult = result;
                ngDialog.open({
                    preCloseCallback: function(value) {
                    },
                    template: 'onap-ui/components/results/modal/sharedModal.html',
                    scope: $scope,
                    className: 'ngdialog-theme-default',
                    width: 950,
                    showClose: true,
                    closeByDocument: true
                });
        }

        function addSharedUser(result, userId){
            var tempList = copy(result.shared);
            tempList.push(userId);
            toggleCheck(result, 'shared', tempList);
            ngDialog.close();
        }

        function removeSharedUser(result, userId){
            var tempList = copy(result.shared);
            var idx = tempList.indexOf(userId);
            if(idx != -1){
                tempList.splice(idx, 1);
                toggleCheck(result, 'shared', tempList);
            }
        }

        function copy(arrList){
            var tempList = [];
            angular.forEach(arrList, function(ele){
                tempList.push(ele);
            });
            return tempList;
        }

        function uploadFileToUrl(file, uploadUrl){
            var fd = new FormData();
            fd.append('file', file);

            $http.post(uploadUrl, fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            }).then(function(data){

                if(data.data.code && data.data.code != 0){
                    alert(data.data.msg);
                    return;
                }

                ctrl.uploadState = "";
                data.data.filename = file.name;
                var createTestUrl = testapiApiUrl + "/onap/tests"

                $http.post(createTestUrl, data.data).then(function(data){
                    if (data.data.code && data.data.code != 0) {
                        alert(data.data.msg);
                    } else {
                        ctrl.update();
                    }
                }, function(error){
                });

             }, function(error){
                ctrl.uploadState = "Upload failed. Error code is " + error.status;
            });
        }

        function uploadFile(){
           var file = $scope.resultFile;

           var uploadUrl = testapiApiUrl + "/onap/results/upload";
           uploadFileToUrl(file, uploadUrl);
        };

        /**
         * This will contact the TestAPI API to get a listing of test run
         * results.
         */
        function update() {
            ctrl.showError = false;
            // Construct the API URL based on user-specified filters.
            var content_url = testapiApiUrl + '/onap/tests';
            var start = $filter('date')(ctrl.startDate, 'yyyy-MM-dd');
            var end = $filter('date')(ctrl.endDate, 'yyyy-MM-dd');

            ctrl.PageName = null;
            content_url += '?page=' + ctrl.currentPage;
            content_url += '&per_page=' + ctrl.itemsPerPage;
            if (start) {
                content_url += '&from=' + start + ' 00:00:00';
            }
            if (end) {
                content_url += '&to=' + end + ' 23:59:59';
            }
            if (ctrl.isUserResults) {
                content_url += '&signed';
                ctrl.PageName = 'MyResults';
            } else {
                content_url += '&status={"$ne":"private"}&review';
            }

            ctrl.resultsRequest =
                $http.get(content_url).success(function (data) {
                    ctrl.data = data;
                    ctrl.totalItems = ctrl.data.pagination.total_pages * ctrl.itemsPerPage;
                    ctrl.currentPage = ctrl.data.pagination.current_page;
                    ctrl.numPages = ctrl.data.pagination.total_pages;
                    if (ctrl.PageName === 'MyResults') {
                        for (var i=0; i<data.tests.length; i++) {
                            if (data.tests[i].owner !== ctrl.currentUser) {
                                var sharing = false;
                                if (data.tests[i].shared !== null){
                                    for (var j=0; j<data.tests[i].shared.length; j++) {
                                        if (data.tests[i].shared[j] === ctrl.currentUser){
                                            sharing = true;
                                            }
                                        }
                                }
                                if (sharing == false){
                                    data.tests.splice(i,1);
                                    i = i - 1;
                                }
                            }
                        }
                        ctrl.data = data;
                    }
                }).error(function (error) {
                    ctrl.data = null;
                    ctrl.totalItems = 0;
                    ctrl.showError = true;
                    ctrl.error =
                        'Error retrieving results listing from server: ' +
                        angular.toJson(error);
                });
        }

        /**
         * This is called when the date filter calendar is opened. It
         * does some event handling, and sets a scope variable so the UI
         * knows which calendar was opened.
         * @param {Object} $event - The Event object
         * @param {String} openVar - Tells which calendar was opened
         */
        function open($event, openVar) {
            $event.preventDefault();
            $event.stopPropagation();
            ctrl[openVar] = true;
        }

        /**
         * This function will clear all filters and update the results
         * listing.
         */
        function clearFilters() {
            ctrl.startDate = null;
            ctrl.endDate = null;
            ctrl.update();
        }

        /**
         * This will send an API request in order to associate a metadata
         * key-value pair with the given testId
         * @param {Number} index - index of the test object in the results list
         * @param {String} key - metadata key
         * @param {String} value - metadata value
         */
        function associateMeta(index, key, value) {
            var testId = ctrl.data.results[index].id;
            var metaUrl = [
                testapiApiUrl, '/results/', testId, '/meta/', key
            ].join('');

            var editFlag = key + 'Edit';
            if (value) {
                ctrl.associateRequest = $http.post(metaUrl, value)
                    .success(function () {
                        ctrl.data.results[index][editFlag] = false;
                    }).error(function (error) {
                        raiseAlert('danger', error.title, error.detail);
                    });
            }
            else {
                ctrl.unassociateRequest = $http.delete(metaUrl)
                    .success(function () {
                        ctrl.data.results[index][editFlag] = false;
                    }).error(function (error) {
                        if (error.code == 404) {
                            // Key doesn't exist, so count it as a success,
                            // and don't raise an alert.
                            ctrl.data.results[index][editFlag] = false;
                        }
                        else {
                            raiseAlert('danger', error.title, error.detail);
                        }
                    });
            }
        }

        function gotoResultDetail(testId, innerID) {
            $state.go('resultsDetail', {'testID': testId, 'innerID': innerID});
        }
    }
})();