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