Security/ Package Name changes
[portal.git] / ecomp-portal-FE-os / client / src / views / applications / application-details-dialog / application-details.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 (function () {
40     class AppDetailsModalCtrl {
41         constructor($scope, $log, applicationsService, errorMessageByCode,
42                     ECOMP_URL_REGEX,userProfileService, $cookies, confirmBoxService,items) {
43 //            let emptyImg = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
44             // empty image should really be empty, or it causes problems for the back end
45             let emptyImg = null;
46             this.emptyImgForPreview = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
47             $scope.ngDialogData=items;
48             let newAppModel = {
49                 'id': null,
50                 'name': null,
51                 'imageUrl': null,
52                 'description': null,
53                 'notes': null,
54                 'url': null,
55                 'alternateUrl': null,
56                 'restUrl': null,
57                 'isOpen': false,
58                 'username': null,
59                 'appPassword': null,
60                 'thumbnail': emptyImg,
61                 'isEnabled': true,
62                 'restrictedApp': false,
63                 'nameSpace': null,
64                 'isCentralAuth': false                
65             };
66
67             let init = () => {
68                 $log.info('AppDetailsModalCtrl::init');
69                 this.isSaving = false;
70                 if($scope.ngDialogData && $scope.ngDialogData.app){
71                     $log.debug('AppDetailsModalCtrl:init:: Edit app mode for', $scope.ngDialogData.app);
72                     this.isEditMode = true;
73                     this.app = _.clone($scope.ngDialogData.app);
74                 }else{
75                     $log.debug('AppDetailsModalCtrl:init:: New app mode');
76                     this.isEditMode = false;
77                     this.app = _.clone(newAppModel);
78                 }
79                 this.originalImage = null
80             };
81
82             this.ECOMP_URL_REGEX = ECOMP_URL_REGEX;
83
84             this.imageApi = {};
85             this.removeImage = () => {
86                 $log.debug('AppDetailsModalCtrl:removeImage:: entering removeImage');
87
88                 confirmBoxService.confirm("Are you sure you want to remove the image?").then(isConfirmed => {
89                     if(isConfirmed){
90                         this.imageApi.clearFile();
91                         this.app.thumbnail = emptyImg;
92                         this.originalImage = null;
93                         this.app.imageUrl = null;
94                         this.app.imageLink = null;
95                     }
96                 }).catch(err => {
97                     $log.error('AppDetailsModalCtrl:removeImage error:: ',err);
98                 });
99             };
100
101             //This part handles conflict errors (409)
102             this.conflictMessages = {};
103             this.scrollApi = {};
104             let handleConflictErrors = err => {
105                 if(!err.data){
106                     return;
107                 }
108                 if(!err.data.length){ //support objects
109                     err.data = [err.data]
110                 }
111                 _.forEach(err.data, item => {
112                     _.forEach(item.fields, field => {
113                         //set conflict message
114                         this.conflictMessages[field.name] = errorMessageByCode[item.errorCode];
115                         //set field as invalid
116                         $scope.appForm[field.name].$setValidity('conflict', false);
117                         //set watch once to clear error after user correction
118                         watchOnce[field.name]();
119                     });
120                 });
121                 this.scrollApi.scrollTop();
122             };
123
124             let resetConflict = fieldName => {
125                 delete this.conflictMessages[fieldName];
126                 if($scope.appForm[fieldName]){
127                     $scope.appForm[fieldName].$setValidity('conflict', true);
128                 }
129             };
130
131
132             let emptyCookies = () => {
133                 $log.debug('AppDetailsModalCtrl:emptyCookies:: entering emptyCookies');
134                 userProfileService.getUserProfile()
135                     .then(profile=> {
136                         // $log.info(profile);
137                         $scope.orgUserId = profile.orgUserId;
138                         $log.debug('AppDetailsModalCtrl:emptyCookies for the following orgUserId: ' + profile.orgUserId);
139                         if ($cookies.getObject($scope.orgUserId + '_apps') != undefined && $cookies.getObject($scope.orgUserId + '_apps') != null) {
140                             $cookies.remove($scope.orgUserId + '_apps');
141                             $log.debug('AppDetailsModalCtrl:emptyCookies removed: ' + $scope.orgUserId + '_apps');
142                         }
143                         if ($cookies.getObject($scope.orgUserId + '_widget') != undefined && $cookies.getObject($scope.orgUserId + '_widget') != null) {
144                             $cookies.remove($scope.orgUserId + '_widget');
145                             $log.debug('AppDetailsModalCtrl:emptyCookies removed: ' + $scope.orgUserId + '_widget');
146                         }
147                     }).catch(err => {
148                         $log.error('AppDetailsModalCtrl:emptyCookies error:: '+ JSON.stringify(err));
149                     });
150             };
151
152
153             let watchOnce = {
154                 name: () => {
155                     let unregisterName = $scope.$watch('appDetails.app.name', (newVal, oldVal) => {
156                         // $log.debug('newVal, oldVal = ' + newVal.toLowerCase() + " | " + oldVal.toLowerCase())
157                         if(newVal.toLowerCase() !== oldVal.toLowerCase()){
158                             resetConflict('name');
159                             unregisterName();
160                         }
161                     });
162                 },
163                 url: () => {
164                     let unregisterUrl = $scope.$watch('appDetails.app.url', (newVal, oldVal) => {
165                         if(newVal.toLowerCase() !== oldVal.toLowerCase()) {
166                             resetConflict('url');
167                             unregisterUrl();
168                         }
169                     });
170                 }
171             };
172             //***************************
173
174             this.saveChanges = () => {
175                 //if valid..
176                  if(((angular.isUndefined(this.app.name) || !this.app.name)&&(angular.isUndefined(this.app.url) || !this.app.url)
177                                  &&(angular.isUndefined(this.app.username) || !this.app.username)&&(angular.isUndefined(this.app.appPassword) || !this.app.appPassword))) {
178                          confirmBoxService.showInformation('Please fill in all required fields').then(isConfirmed => {});
179                      return;
180                  }else if(!((angular.isUndefined(this.app.name) || !!this.app.name)&&(angular.isUndefined(this.app.url) || !!this.app.url))){
181                      confirmBoxService.showInformation('Please fill in all required fields').then(isConfirmed => {});
182                      return;
183                  }
184                 this.isSaving = true;
185                 // For a restricted app, null out all irrelevant fields
186                 if (this.app.restrictedApp) {
187                     this.app.restUrl = null;
188                     this.app.isOpen = true;
189                     this.app.username = null;
190                     this.app.appPassword = null;
191                     this.app.uebTopicName = null;
192                     this.app.uebKey = null;
193                     this.app.uebSecret = null;
194                 }
195                 if(this.isEditMode){
196                     if (this.app.nameSpace=="") {this.app.nameSpace = null;}
197                     applicationsService.updateOnboardingApp(this.app)
198                         .then(() => {
199                             $log.debug('AppDetailsModalCtrl:updateOnboardingApp:: App update succeeded!');
200                           //  $scope.closeThisDialog(true);
201                             $scope.$dismiss('cancel');
202                             emptyCookies();
203                         }).catch(err => {
204                             switch (err.status) {
205                                 case '409':         // Conflict
206                                     handleConflictErrors(err);
207                                     break;
208                                 case '500':         // Internal Server Error
209                                     confirmBoxService.showInformation('There was a problem updating the application changes. ' +
210                                         'Please try again later. Error: ' + err.status).then(isConfirmed => {});
211                                     break;
212                                 case '403':         // Forbidden... possible webjunction error to try again
213                                     confirmBoxService.showInformation('There was a problem updating the application changes. ' +
214                                         'Please try again. If the problem persists, then try again later. Error: ' + err.status).then(isConfirmed => {});
215                                     break;
216                                 default:
217                                     confirmBoxService.showInformation('There was a problem updating the application changes. ' +
218                                         'Please try again. If the problem persists, then try again later. Error: ' + err.status).then(isConfirmed => {});
219                             }
220                             $log.error('applicationsService:updateOnboardingApp error:: '+ JSON.stringify(err));
221                         }).finally(()=>{
222                             this.isSaving = false;
223                             // for bug in IE 11
224                             var objOffsetVersion = objAgent.indexOf("MSIE");
225                             if (objOffsetVersion != -1) {
226                                 $log.debug('AppDetailsModalCtrl:updateOnboardingApp:: Browser is IE, forcing Refresh');
227                                 $window.location.reload();            // for bug in IE 11
228                             }
229                             // for bug in IE 11
230                         });
231                 }else{
232                     applicationsService.addOnboardingApp(this.app)
233                         .then(() => {
234                             $log.debug('App creation succeeded!');
235                             //$scope.closeThisDialog(true);
236                             $scope.$dismiss('cancel');
237                             emptyCookies();
238                         }).catch(err => {
239                             switch (err.status) {
240                                 case '409':         // Conflict
241                                     handleConflictErrors(err);
242                                     break;
243                                 case '500':         // Internal Server Error
244                                     confirmBoxService.showInformation('There was a problem adding the application information. ' +
245                                         'Please try again later. Error: ' + err.status).then(isConfirmed => {});
246                                     break;
247                                 default:
248                                     confirmBoxService.showInformation('There was a problem updating the application changes. ' +
249                                         'Please try again. If the problem persists, then try again later. Error: ' +
250                                         err.status).then(isConfirmed => {});
251                             }
252                             $log.error('applicationsService:addOnboardingApp error:: '+ JSON.stringify(err));
253                         }).finally(()=>{
254                             this.isSaving = false;
255                             // for bug in IE 11
256                             var objOffsetVersion = objAgent.indexOf("MSIE");
257                             if (objOffsetVersion != -1) {
258                                 $log.debug('applicationsService:addOnboardingApp:: Browser is IE, forcing Refresh');
259                                 $window.location.reload();            // for bug in IE 11
260                             }
261                             // for bug in IE 11
262                         });
263                 }
264                 
265             };
266
267
268             init();
269
270             $scope.$watch('appDetails.originalImage', (newVal, oldVal) => {
271               if((!newVal || !newVal.resized) && !this.app.imageUrl){
272                   if (!newVal) {
273                       $log.debug('applicationsService:$scope.$watch:: originalImage: newVal is null');
274                   } else {
275                       $log.debug('applicationsService:$scope.$watch:: originalImage: newVal is not resized and no imageUrl');
276                   }
277                   this.app.imageUrl = null;
278                   this.app.thumbnail = emptyImg;
279                   return;
280               }
281
282                 if(!(_.isEqual(newVal, oldVal))){
283                     $log.debug('applicationsService:$scope.$watch:: thumbnail updated!');
284                     this.app.imageUrl = null;
285                     this.app.imageLink = null;
286                     this.app.thumbnail = newVal.resized.dataURL;
287                 }
288             });
289
290             $scope.$on('$stateChangeStart', e => {
291                 //Disable navigation when modal is opened
292                 e.preventDefault();
293             });
294         }
295     }
296     AppDetailsModalCtrl.$inject = ['$scope', '$log', 'applicationsService', 'errorMessageByCode',
297         'ECOMP_URL_REGEX','userProfileService','$cookies', 'confirmBoxService','items'];
298     angular.module('ecompApp').controller('AppDetailsModalCtrl', AppDetailsModalCtrl);
299 })();