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