[SDC] rebase 1710 code
[sdc.git] / catalog-ui / src / app / view-models / workspace / tabs / general / general-view-model.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
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  * ============LICENSE_END=========================================================
19  */
20
21 'use strict';
22 import {ModalsHandler, ValidationUtils, EVENTS, CHANGE_COMPONENT_CSAR_VERSION_FLAG, ComponentType, DEFAULT_ICON,
23     ResourceType} from "app/utils";
24 import {CacheService, EventListenerService, ProgressService} from "app/services";
25 import {IAppConfigurtaion, IValidate, IMainCategory, Resource, ISubCategory,Service} from "app/models";
26 import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
27
28 export class Validation {
29     componentNameValidationPattern:RegExp;
30     contactIdValidationPattern:RegExp;
31     tagValidationPattern:RegExp;
32     VendorReleaseValidationPattern:RegExp;
33     VendorNameValidationPattern:RegExp;
34     VendorModelNumberValidationPattern:RegExp;
35     commentValidationPattern:RegExp;
36     projectCodeValidationPattern:RegExp;
37 }
38
39 export class componentCategories {//categories field bind to this obj in order to solve this bug: DE242059
40     selectedCategory:string;
41 }
42
43 export interface IGeneralScope extends IWorkspaceViewModelScope {
44     validation:Validation;
45     editForm:ng.IFormController;
46     categories:Array<IMainCategory>;
47     latestCategoryId:string;
48     latestVendorName:string;
49     importedFileExtension:any;
50     isCreate:boolean;
51     isShowFileBrowse:boolean;
52     isShowOnboardingSelectionBrowse:boolean;
53     importedToscaBrowseFileText:string;
54     importCsarProgressKey:string;
55     browseFileLabel:string;
56     componentCategories:componentCategories;
57
58     onToscaFileChange():void
59     validateField(field:any):boolean;
60     validateName(isInit:boolean):void;
61     calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
62     onVendorNameChange(oldVendorName:string):void;
63     convertCategoryStringToOneArray(category:string, subcategory:string):Array<IMainCategory>;
64     onCategoryChange():void;
65     onEcompGeneratedNamingChange():void;
66     openOnBoardingModal():void;
67     initCategoreis():void;
68     updateIcon():void;
69     possibleToUpdateIcon():boolean;
70 }
71
72 export class GeneralViewModel {
73
74     static '$inject' = [
75         '$scope',
76         'Sdc.Services.CacheService',
77         'ComponentNameValidationPattern',
78         'ContactIdValidationPattern',
79         'TagValidationPattern',
80         'VendorReleaseValidationPattern',
81         'VendorNameValidationPattern',
82         'VendorModelNumberValidationPattern',
83         'CommentValidationPattern',
84         'ValidationUtils',
85         'sdcConfig',
86         'ProjectCodeValidationPattern',
87         '$state',
88         'ModalsHandler',
89         'EventListenerService',
90         'Notification',
91         'Sdc.Services.ProgressService',
92         '$interval',
93         '$filter',
94         '$timeout'
95     ];
96
97     constructor(private $scope:IGeneralScope,
98                 private cacheService:CacheService,
99                 private ComponentNameValidationPattern:RegExp,
100                 private ContactIdValidationPattern:RegExp,
101                 private TagValidationPattern:RegExp,
102                 private VendorReleaseValidationPattern:RegExp,
103                 private VendorNameValidationPattern:RegExp,
104                 private VendorModelNumberValidationPattern:RegExp,
105                 private CommentValidationPattern:RegExp,
106                 private ValidationUtils:ValidationUtils,
107                 private sdcConfig:IAppConfigurtaion,
108                 private ProjectCodeValidationPattern:RegExp,
109                 private $state:ng.ui.IStateService,
110                 private ModalsHandler:ModalsHandler,
111                 private EventListenerService:EventListenerService,
112                 private Notification:any,
113                 private progressService:ProgressService,
114                 protected $interval:any,
115                 private $filter:ng.IFilterService,
116                 private $timeout:ng.ITimeoutService) {
117
118         this.initScopeValidation();
119         this.initScopeMethods();
120         this.initScope();
121         this.$scope.updateSelectedMenuItem();
122     }
123
124
125
126
127     private initScopeValidation = ():void => {
128         this.$scope.validation = new Validation();
129         this.$scope.validation.componentNameValidationPattern = this.ComponentNameValidationPattern;
130         this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
131         this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
132         this.$scope.validation.VendorReleaseValidationPattern = this.VendorReleaseValidationPattern;
133         this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern;
134         this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern;
135         this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
136         this.$scope.validation.projectCodeValidationPattern = this.ProjectCodeValidationPattern;
137     };
138
139     private initScope = ():void => {
140
141         // Work around to change the csar version
142         if (this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
143             (<Resource>this.$scope.component).csarVersion = this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
144         }
145
146         this.$scope.importedToscaBrowseFileText = this.$scope.component.name + " (" + (<Resource>this.$scope.component).csarVersion + ")";
147         this.$scope.importCsarProgressKey = "importCsarProgressKey";
148         this.$scope.browseFileLabel = this.$scope.component.isResource() && (<Resource>this.$scope.component).resourceType === ResourceType.VF ? "Upload file" : "Upload VFC";
149         this.$scope.progressService = this.progressService;
150         this.$scope.componentCategories = new componentCategories();
151         this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
152
153         // Init UIModel
154         this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
155
156         // Init categories
157         this.$scope.initCategoreis();
158
159         // Init the decision if to show file browse.
160         this.$scope.isShowFileBrowse = false;
161         if (this.$scope.component.isResource()) {
162             let resource:Resource = <Resource>this.$scope.component;
163             console.log(resource.name + ": " + resource.csarUUID);
164             if (resource.importedFile) { // Component has imported file.
165                 this.$scope.isShowFileBrowse = true;
166             }
167             if (this.$scope.isEditMode() && resource.resourceType == ResourceType.VF && !resource.csarUUID) {
168                 this.$scope.isShowFileBrowse = true;
169             }
170         }
171         ;
172
173         // Init the decision if to show onboarding
174         this.$scope.isShowOnboardingSelectionBrowse = false;
175         if (this.$scope.component.isResource() &&
176             this.$scope.isEditMode() &&
177             (<Resource>this.$scope.component).resourceType == ResourceType.VF &&
178             (<Resource>this.$scope.component).csarUUID) {
179             this.$scope.isShowOnboardingSelectionBrowse = true;
180         }
181
182         //init file extensions based on the file that was imported.
183         if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
184             let fileName:string = (<Resource>this.$scope.component).importedFile.filename;
185             let fileExtension:string = fileName.split(".").pop();
186             if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
187                 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
188                 (<Resource>this.$scope.component).importedFile.filetype = "csar";
189             } else if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
190                 (<Resource>this.$scope.component).importedFile.filetype = "yaml";
191                 this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
192             }
193         } else if (this.$scope.isEditMode() && (<Resource>this.$scope.component).resourceType === ResourceType.VF) {
194             this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
195             //(<Resource>this.$scope.component).importedFile.filetype="csar";
196         }
197
198         this.$scope.setValidState(true);
199
200         this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
201             let uniqueId:string = mainCategory;
202             if (subCategory) {
203                 uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
204             }
205             return uniqueId;
206         };
207
208         //TODO remove this after handling contact in UI
209         if (this.$scope.isCreateMode()) {
210             this.$scope.component.contactId = this.cacheService.get("user").userId;
211         }
212
213     };
214
215     // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
216     private convertCategoryStringToOneArray = ():Array<IMainCategory> => {
217         let tmp = this.$scope.component.selectedCategory.split("_#_");
218         let mainCategory = tmp[0];
219         let subCategory = tmp[1];
220
221         // Find the selected category and add the relevant sub category.
222         let selectedMainCategory:IMainCategory = <IMainCategory>_.find(this.$scope.categories, function (item) {
223             return item["name"] === mainCategory;
224
225         });
226
227         let mainCategoryClone = angular.copy(selectedMainCategory);
228         if (subCategory) {
229             let selectedSubcategory = <ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
230                 return item["name"] === subCategory;
231             });
232             mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
233         }
234         let tmpSelected = <IMainCategory> mainCategoryClone;
235
236         let result:Array<IMainCategory> = [];
237         result.push(tmpSelected);
238
239         return result;
240     };
241
242     private updateComponentNameInBreadcrumbs = ():void => {
243         //update breadcrum after changing name
244         this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
245         this.$scope.updateMenuComponentName(this.$scope.component.name);
246     };
247
248     private initScopeMethods = ():void => {
249
250         this.$scope.initCategoreis = ():void => {
251             if (this.$scope.componentType === ComponentType.RESOURCE) {
252                 this.$scope.categories = this.cacheService.get('resourceCategories');
253
254             }
255             if (this.$scope.componentType === ComponentType.SERVICE) {
256                 this.$scope.categories = this.cacheService.get('serviceCategories');
257             }
258         };
259
260         this.$scope.validateField = (field:any):boolean => {
261             if (field && field.$dirty && field.$invalid) {
262                 return true;
263             }
264             return false;
265         };
266
267         this.$scope.openOnBoardingModal = ():void => {
268             let csarUUID = (<Resource>this.$scope.component).csarUUID;
269             this.ModalsHandler.openOnboadrdingModal('Update', csarUUID).then(()=> {
270                 // OK
271                 this.$scope.uploadFileChangedInGeneralTab();
272             }, ()=> {
273                 // ERROR
274             });
275         };
276
277         this.$scope.updateIcon = ():void => {
278             this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
279                 if(!this.$scope.isCreateMode()){
280                     this.$state.current.data.unsavedChanges = this.$state.current.data.unsavedChanges || isDirty;
281                 }
282             }, ()=> {
283                 // ERROR
284             });
285         };
286
287         this.$scope.possibleToUpdateIcon = ():boolean => {
288             if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName)){
289                 return true;
290             }else{
291                 return false;
292             }
293         }
294
295         this.$scope.validateName = (isInit:boolean):void => {
296             if (isInit === undefined) {
297                 isInit = false;
298             }
299
300             let name = this.$scope.component.name;
301             if (!name || name === "") {
302                 if (this.$scope.editForm
303                     && this.$scope.editForm["componentName"]
304                     && this.$scope.editForm["componentName"].$error) {
305
306                     // Clear the error name already exists
307                     this.$scope.editForm["componentName"].$setValidity('nameExist', true);
308                 }
309
310                 return;
311             }
312             //?????????????????????????
313             let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
314
315             let onFailed = (response) => {
316                 //console.info('onFaild', response);
317                 //this.$scope.isLoading = false;
318             };
319
320             let onSuccess = (validation:IValidate) => {
321                 this.$scope.editForm["componentName"].$setValidity('nameExist', validation.isValid);
322                 if (validation.isValid) {
323                     //update breadcrumb after changing name
324                     this.updateComponentNameInBreadcrumbs();
325                 }
326             };
327
328             if (isInit) {
329                 // When page is init after update
330                 if (this.$scope.component.name !== this.$scope.originComponent.name) {
331                     if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
332                     ) {
333                         this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
334                     }
335                 }
336             } else {
337                 // Validating on change (has debounce)
338                 if (this.$scope.editForm
339                     && this.$scope.editForm["componentName"]
340                     && this.$scope.editForm["componentName"].$error
341                     && !this.$scope.editForm["componentName"].$error.pattern
342                     && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase())
343                 ) {
344                     if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
345                     ) {
346                         this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
347                     }
348                 } else if (this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
349                     // Clear the error
350                     this.$scope.editForm["componentName"].$setValidity('nameExist', true);
351                 }
352             }
353         };
354
355         this.$scope.$watchCollection('component.name', (newData:any):void => {
356             this.$scope.validateName(false);
357         });
358
359         // Notify the parent if this step valid or not.
360         this.$scope.$watch("editForm.$valid", (newVal, oldVal) => {
361             this.$scope.setValidState(newVal);
362         });
363
364         this.$scope.$watch("editForm.$dirty", (newVal, oldVal) => {
365             if (newVal !== oldVal) {
366                 this.$state.current.data.unsavedChanges = newVal && !this.$scope.isCreateMode();
367             }
368         });
369
370         this.$scope.onCategoryChange = ():void => {
371             this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory;
372             this.$scope.component.categories = this.convertCategoryStringToOneArray();
373             this.$scope.component.icon = DEFAULT_ICON;
374         };
375
376         this.$scope.onEcompGeneratedNamingChange = ():void =>{
377             if(!(<Service>this.$scope.component).ecompGeneratedNaming){
378                 (<Service>this.$scope.component).namingPolicy = '';
379             }
380         };
381
382         this.$scope.onVendorNameChange = (oldVendorName:string):void => {
383             if (this.$scope.component.icon === oldVendorName) {
384                 this.$scope.component.icon = DEFAULT_ICON;
385             }
386         };
387         this.EventListenerService.registerObserverCallback(EVENTS.ON_CHECKOUT, this.$scope.reload);
388     };
389 }