summaryrefslogtreecommitdiffstats
path: root/ecomp-portal-FE-os/client/src/views/applications/application-details-dialog/application-details.controller.js
blob: d89af17cf961d7e1f146bc6958b6a08d9c720e24 (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
/*-
 * ============LICENSE_START==========================================
 * ONAP Portal
 * ===================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ===================================================================
 *
 * Unless otherwise specified, all software contained herein is licensed
 * under the Apache License, Version 2.0 (the "License");
 * you may not use this software 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.
 *
 * Unless otherwise specified, all documentation contained herein is licensed
 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
 * you may not use this documentation except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             https://creativecommons.org/licenses/by/4.0/
 *
 * Unless required by applicable law or agreed to in writing, documentation
 * 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.
 *
 * ============LICENSE_END============================================
 *
 * 
 */
'use strict';
(function () {
    class AppDetailsModalCtrl {
    	constructor($scope, $log, $timeout, applicationsService, errorMessageByCode,
                    ECOMP_URL_REGEX,userProfileService, $cookies, confirmBoxService,items) {
//            let emptyImg = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
            // empty image should really be empty, or it causes problems for the back end
            let emptyImg = null;
            this.emptyImgForPreview = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
            $scope.ngDialogData=items;
            let newAppModel = {
                'id': null,
                'name': null,
                'imageUrl': null,
                'description': null,
                'notes': null,
                'url': null,
                'alternateUrl': null,
                'restUrl': null,
                'isOpen': false,
                'username': null,
                'appPassword': null,
                'thumbnail': emptyImg,
                'isEnabled': false,
                'restrictedApp': false,
                'nameSpace': null,
                'isCentralAuth': false                
            };

            let init = () => {
                $log.info('AppDetailsModalCtrl::init');
                this.isSaving = false;
                if($scope.ngDialogData && $scope.ngDialogData.app){
                    $log.debug('AppDetailsModalCtrl:init:: Edit app mode for', $scope.ngDialogData.app);
                    this.isEditMode = true;
                    this.app = _.clone($scope.ngDialogData.app);
                }else{
                    $log.debug('AppDetailsModalCtrl:init:: New app mode');
                    this.isEditMode = false;
                    this.app = _.clone(newAppModel);
                }
                this.originalImage = null
            };

            this.ECOMP_URL_REGEX = ECOMP_URL_REGEX;

            this.imageApi = {};
            this.removeImage = () => {
                $log.debug('AppDetailsModalCtrl:removeImage:: entering removeImage');

                confirmBoxService.confirm("Are you sure you want to remove the image?").then(isConfirmed => {
                    if(isConfirmed){
                        this.imageApi.clearFile();
                        this.app.thumbnail = emptyImg;
                        this.originalImage = null;
                        this.app.imageUrl = null;
                        this.app.imageLink = null;
                    }
                }).catch(err => {
                    $log.error('AppDetailsModalCtrl:removeImage error:: ',err);
                });
            };

            //This part handles conflict errors (409)
            this.conflictMessages = {};
            this.scrollApi = {};
            let handleConflictErrors = err => {
                if(!err.data){
                    return;
                }
                if(!err.data.length){ //support objects
                    err.data = [err.data]
                }
                _.forEach(err.data, item => {
                    _.forEach(item.fields, field => {
                        //set conflict message
                        this.conflictMessages[field.name] = errorMessageByCode[item.errorCode];
                        //set field as invalid
                        $scope.appForm[field.name].$setValidity('conflict', false);
                        //set watch once to clear error after user correction
                        watchOnce[field.name]();
                    });
                });
                this.scrollApi.scrollTop();
            };

            let resetConflict = fieldName => {
                delete this.conflictMessages[fieldName];
                if($scope.appForm[fieldName]){
                    $scope.appForm[fieldName].$setValidity('conflict', true);
                }
            };


            let emptyCookies = () => {
                $log.debug('AppDetailsModalCtrl:emptyCookies:: entering emptyCookies');
                userProfileService.getUserProfile()
                    .then(profile=> {
                        // $log.info(profile);
                        $scope.orgUserId = profile.orgUserId;
                        $log.debug('AppDetailsModalCtrl:emptyCookies for the following orgUserId: ' + profile.orgUserId);
                        if ($cookies.getObject($scope.orgUserId + '_apps') != undefined && $cookies.getObject($scope.orgUserId + '_apps') != null) {
                            $cookies.remove($scope.orgUserId + '_apps');
                            $log.debug('AppDetailsModalCtrl:emptyCookies removed: ' + $scope.orgUserId + '_apps');
                        }
                        if ($cookies.getObject($scope.orgUserId + '_widget') != undefined && $cookies.getObject($scope.orgUserId + '_widget') != null) {
                            $cookies.remove($scope.orgUserId + '_widget');
                            $log.debug('AppDetailsModalCtrl:emptyCookies removed: ' + $scope.orgUserId + '_widget');
                        }
                    }).catch(err => {
                        $log.error('AppDetailsModalCtrl:emptyCookies error:: '+ JSON.stringify(err));
                    });
            };


            let watchOnce = {
                name: () => {
                    let unregisterName = $scope.$watch('appDetails.app.name', (newVal, oldVal) => {
                        // $log.debug('newVal, oldVal = ' + newVal.toLowerCase() + " | " + oldVal.toLowerCase())
                        if(newVal.toLowerCase() !== oldVal.toLowerCase()){
                            resetConflict('name');
                            unregisterName();
                        }
                    });
                },
                url: () => {
                    let unregisterUrl = $scope.$watch('appDetails.app.url', (newVal, oldVal) => {
                        if(newVal.toLowerCase() !== oldVal.toLowerCase()) {
                            resetConflict('url');
                            unregisterUrl();
                        }
                    });
                }
            };
            //***************************

            this.saveChanges = () => {
            	 //if valid..
            	if(this.app.isCentralAuth){
                    //if valid.
            		if(!this.app.isEnabled)
            			{
            			if(((angular.isUndefined(this.app.name) || !this.app.name)||(angular.isUndefined(this.app.nameSpace) || !this.app.nameSpace)
                   			 ||(angular.isUndefined(this.app.username) || !this.app.username))) {
                   		    confirmBoxService.showInformation('Please fill in all required fields for centralized application').then(isConfirmed => {});
                            return;
                           }
            			}
            		if(this.app.isEnabled){
            			if(((angular.isUndefined(this.app.myLoginsAppName) || !this.app.myLoginsAppName)||(angular.isUndefined(this.app.myLoginsAppOwner) || !this.app.myLoginsAppOwner)||(angular.isUndefined(this.app.name) || !this.app.name)||(angular.isUndefined(this.app.url) || !this.app.url)
                   			 ||(angular.isUndefined(this.app.username) || !this.app.username)||(angular.isUndefined(this.app.nameSpace) || !this.app.nameSpace))) {
                   		 confirmBoxService.showInformation('Please fill in all required fields for centralized active application').then(isConfirmed => {});
                            return;
                        }
            	   }
                	}else{
                		
                		if(!this.app.isEnabled)
                			{
                			 if((angular.isUndefined(this.app.name) || !this.app.name)){
                				 confirmBoxService.showInformation('Please fill in all required field ApplicationName to Save the applictaion').then(isConfirmed => {});
                                 return; 
                			 }
                			}else if(this.app.isEnabled && !this.app.restrictedApp){
                		    if(((angular.isUndefined(this.app.myLoginsAppName) || !this.app.myLoginsAppName)||(angular.isUndefined(this.app.myLoginsAppOwner) || !this.app.myLoginsAppOwner)||(angular.isUndefined(this.app.name) || !this.app.name)||(angular.isUndefined(this.app.url) || !this.app.url)
                    			 ||(angular.isUndefined(this.app.username) || !this.app.username)||(angular.isUndefined(this.app.appPassword) || !this.app.appPassword))) {
                    		    confirmBoxService.showInformation('Please fill in all required fields along with password as the app is not centralized').then(isConfirmed => {});
                                 return;
                		    } }else if(this.app.isEnabled && this.app.restrictedApp){
                                if((angular.isUndefined(this.app.name) || !this.app.name) ||(angular.isUndefined(this.app.url) || !this.app.url)){
                        	    confirmBoxService.showInformation('Please fill in all required fields').then(isConfirmed => {});
                             return;
                         
                         }
                	   }
                	}
                this.isSaving = true;
                // For a restricted app, null out all irrelevant fields
                if (this.app.restrictedApp) {
                    this.app.restUrl = null;
                    this.app.isOpen = true;
                    this.app.username = null;
                    this.app.appPassword = null;
                    this.app.uebTopicName = null;
                    this.app.uebKey = null;
                    this.app.uebSecret = null;
                }
                if(this.isEditMode){
                    if (this.app.nameSpace=="") {this.app.nameSpace = null;}
                    applicationsService.updateOnboardingApp(this.app)
                        .then(() => {
                            $log.debug('AppDetailsModalCtrl:updateOnboardingApp:: App update succeeded!');
                          //  $scope.closeThisDialog(true);
                            $scope.$dismiss('cancel');
                            emptyCookies();
                        }).catch(err => {
                            switch (err.status) {
                                case '409':         // Conflict
                                    handleConflictErrors(err);
                                    break;
                                case '500':         // Internal Server Error
                                    confirmBoxService.showInformation('There was a problem updating the application changes. ' +
                                        'Please try again later. Error: ' + err.status).then(isConfirmed => {});
                                    break;
                                case '403':         // Forbidden... possible webjunction error to try again
                                    confirmBoxService.showInformation('There was a problem updating the application changes. ' +
                                        'Please try again. If the problem persists, then try again later. Error: ' + err.status).then(isConfirmed => {});
                                    break;
                                default:
                                    confirmBoxService.showInformation('There was a problem updating the application changes. ' +
                                        'Please try again. If the problem persists, then try again later. Error: ' + err.status).then(isConfirmed => {});
                            }
                            $log.error('applicationsService:updateOnboardingApp error:: '+ JSON.stringify(err));
                        }).finally(()=>{
                            this.isSaving = false;
                            // for bug in IE 11
                            var objOffsetVersion = objAgent.indexOf("MSIE");
                            if (objOffsetVersion != -1) {
                                $log.debug('AppDetailsModalCtrl:updateOnboardingApp:: Browser is IE, forcing Refresh');
                                $window.location.reload();            // for bug in IE 11
                            }
                            // for bug in IE 11
                        });
                }else{
                    applicationsService.addOnboardingApp(this.app)
                        .then(() => {
                            $log.debug('App creation succeeded!');
                            //$scope.closeThisDialog(true);
                            $scope.$dismiss('cancel');
                            emptyCookies();
                        }).catch(err => {
                            switch (err.status) {
                                case '409':         // Conflict
                                    handleConflictErrors(err);
                                    break;
                                case '500':         // Internal Server Error
                                    confirmBoxService.showInformation('There was a problem adding the application information. ' +
                                        'Please try again later. Error: ' + err.status).then(isConfirmed => {});
                                    break;
                                default:
                                    confirmBoxService.showInformation('There was a problem updating the application changes. ' +
                                        'Please try again. If the problem persists, then try again later. Error: ' +
                                        err.status).then(isConfirmed => {});
                            }
                            $log.error('applicationsService:addOnboardingApp error:: '+ JSON.stringify(err));
                        }).finally(()=>{
                            this.isSaving = false;
                            // for bug in IE 11
                            var objOffsetVersion = objAgent.indexOf("MSIE");
                            if (objOffsetVersion != -1) {
                                $log.debug('applicationsService:addOnboardingApp:: Browser is IE, forcing Refresh');
                                $window.location.reload();            // for bug in IE 11
                            }
                            // for bug in IE 11
                        });
                }
            	
            };
            
         // Caches the file name supplied by the event handler.
        	$scope.appImageHandler = (event, files) => {
        		if(files[0]){
        			var fileName = files[0].name;
                    var validFormats = ['jpg', 'jpeg', 'bmp', 'gif', 'png'];
                    //Get file extension
                    var ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase(); 
                    //Check for valid format
                    if(validFormats.indexOf(ext) == -1){
                        $scope.appImageTypeError=true;
                        $timeout(function(){
                        	$scope.appImageTypeError=false;
                        }, 5000);
                    }
        		}
        	}; // file change handler


            init();

            $scope.$watch('appDetails.originalImage', (newVal, oldVal) => {
              if((!newVal || !newVal.resized) && !this.app.imageUrl){
                  if (!newVal) {
                      $log.debug('applicationsService:$scope.$watch:: originalImage: newVal is null');
                  } else {
                      $log.debug('applicationsService:$scope.$watch:: originalImage: newVal is not resized and no imageUrl');
                  }
                  this.app.imageUrl = null;
                  this.app.thumbnail = emptyImg;
                  return;
              }

                if(!(_.isEqual(newVal, oldVal))){
                    $log.debug('applicationsService:$scope.$watch:: thumbnail updated!');
                    this.app.imageUrl = null;
                    this.app.imageLink = null;
                    this.app.thumbnail = newVal.resized.dataURL;
                }
            });

            $scope.$on('$stateChangeStart', e => {
                //Disable navigation when modal is opened
                e.preventDefault();
            });
        }
    }
    AppDetailsModalCtrl.$inject = ['$scope', '$log', '$timeout', 'applicationsService', 'errorMessageByCode',
        'ECOMP_URL_REGEX','userProfileService','$cookies', 'confirmBoxService','items'];
    angular.module('ecompApp').controller('AppDetailsModalCtrl', AppDetailsModalCtrl);
})();