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