2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
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";
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;
40 export class componentCategories {//categories field bind to this obj in order to solve this bug: DE242059
41 selectedCategory:string;
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;
53 isShowFileBrowse:boolean;
54 isShowOnboardingSelectionBrowse:boolean;
55 importedToscaBrowseFileText:string;
56 importCsarProgressKey:string;
57 browseFileLabel:string;
58 componentCategories:componentCategories;
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;
71 possibleToUpdateIcon():boolean;
74 export class GeneralViewModel {
78 'Sdc.Services.CacheService',
79 'ComponentNameValidationPattern',
80 'ContactIdValidationPattern',
81 'TagValidationPattern',
82 'VendorReleaseValidationPattern',
83 'VendorNameValidationPattern',
84 'VendorModelNumberValidationPattern',
85 'CommentValidationPattern',
88 'ProjectCodeValidationPattern',
91 'EventListenerService',
93 'Sdc.Services.ProgressService',
97 'Sdc.Services.OnboardingService'
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) {
122 this.initScopeValidation();
123 this.initScopeMethods();
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;
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];
158 if(!onboardCsarFilesMap || !this.$scope.importedToscaBrowseFileText){
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 + ")";
166 this.cacheService.set('onboardCsarFilesMap', onboardCsarFilesMap);
167 this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[(<Resource>this.$scope.component).csarUUID][(<Resource>this.$scope.component).csarVersion];
170 let onError = (): void =>{
171 console.log("Error getting onboarding list");
174 this.onBoardingService.getOnboardingVSPs().then(onSuccess, onError);
179 private initScope = ():void => {
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);
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;
193 this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
196 this.$scope.initCategoreis();
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;
206 if (this.$scope.isEditMode() && resource.resourceType == ResourceType.VF && !resource.csarUUID) {
207 this.$scope.isShowFileBrowse = true;
211 this.initImportedToscaBrowseFile();
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;
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";
229 this.$scope.setValidState(true);
231 this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
232 let uniqueId:string = mainCategory;
234 uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
239 //TODO remove this after handling contact in UI
240 if (this.$scope.isCreateMode()) {
241 this.$scope.component.contactId = this.cacheService.get("user").userId;
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];
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;
258 let mainCategoryClone = angular.copy(selectedMainCategory);
260 let selectedSubcategory = <ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
261 return item["name"] === subCategory;
263 mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
265 let tmpSelected = <IMainCategory> mainCategoryClone;
267 let result:Array<IMainCategory> = [];
268 result.push(tmpSelected);
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);
279 private initScopeMethods = ():void => {
281 this.$scope.initCategoreis = ():void => {
282 if (this.$scope.componentType === ComponentType.RESOURCE) {
283 this.$scope.categories = this.cacheService.get('resourceCategories');
286 if (this.$scope.componentType === ComponentType.SERVICE) {
287 this.$scope.categories = this.cacheService.get('serviceCategories');
291 this.$scope.validateField = (field:any):boolean => {
292 if (field && field.$dirty && field.$invalid) {
298 this.$scope.openOnBoardingModal = ():void => {
299 let csarUUID = (<Resource>this.$scope.component).csarUUID;
300 this.ModalsHandler.openOnboadrdingModal('Update', csarUUID).then(()=> {
302 this.$scope.uploadFileChangedInGeneralTab();
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;
318 this.$scope.possibleToUpdateIcon = ():boolean => {
319 if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName)){
326 this.$scope.validateName = (isInit:boolean):void => {
327 if (isInit === undefined) {
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) {
337 // Clear the error name already exists
338 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
343 //?????????????????????????
344 let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
346 let onFailed = (response) => {
347 //console.info('onFaild', response);
348 //this.$scope.isLoading = false;
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();
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)
364 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
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())
375 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
377 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
379 } else if (this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
381 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
386 this.$scope.$watchCollection('component.name', (newData:any):void => {
387 this.$scope.validateName(false);
390 // Notify the parent if this step valid or not.
391 this.$scope.$watch("editForm.$valid", (newVal, oldVal) => {
392 this.$scope.setValidState(newVal);
395 this.$scope.$watch("editForm.$dirty", (newVal, oldVal) => {
396 if (newVal !== oldVal) {
397 this.$state.current.data.unsavedChanges = newVal && !this.$scope.isCreateMode();
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;
407 this.$scope.onEcompGeneratedNamingChange = ():void =>{
408 if(!(<Service>this.$scope.component).ecompGeneratedNaming){
409 (<Service>this.$scope.component).namingPolicy = '';
413 this.$scope.onVendorNameChange = (oldVendorName:string):void => {
414 if (this.$scope.component.icon === oldVendorName) {
415 this.$scope.component.icon = DEFAULT_ICON;
418 this.EventListenerService.registerObserverCallback(EVENTS.ON_CHECKOUT, this.$scope.reload);