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