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 * as _ from "lodash";
23 import {Dictionary} from "lodash";
35 import {EventListenerService, ProgressService} from "app/services";
36 import {CacheService, ElementService, ModelService, ImportVSPService, OnboardingService} from "app/services-ng2";
37 import {Component, IAppConfigurtaion, ICsarComponent, IMainCategory, IMetadataKey, ISubCategory, IValidate, Resource, Service} from "app/models";
38 import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
39 import {CATEGORY_SERVICE_METADATA_KEYS, PREVIOUS_CSAR_COMPONENT} from "../../../../utils/constants";
40 import {Observable} from "rxjs";
42 export class Validation {
43 componentNameValidationPattern:RegExp;
44 contactIdValidationPattern:RegExp;
45 tagValidationPattern:RegExp;
46 VendorReleaseValidationPattern:RegExp;
47 VendorNameValidationPattern:RegExp;
48 VendorModelNumberValidationPattern:RegExp;
49 commentValidationPattern:RegExp;
52 export class componentCategories {//categories field bind to this obj in order to solve this bug: DE242059
53 selectedCategory:string;
56 export class componentModel {
60 export interface IEnvironmentContext {
62 validValues:Array<string>;
65 export interface IGeneralScope extends IWorkspaceViewModelScope {
66 validation:Validation;
67 editForm:ng.IFormController;
68 categories:Array<IMainCategory>;
69 environmentContextObj:IEnvironmentContext;
70 latestCategoryId:string;
71 latestVendorName:string;
72 importedFileExtension:any;
74 isShowFileBrowse:boolean;
75 isShowOnboardingSelectionBrowse:boolean;
76 importedToscaBrowseFileText:string;
77 importCsarProProgressKey:string;
78 browseFileLabel:string;
79 componentCategories:componentCategories;
80 componentModel:componentModel;
81 instantiationTypes:Array<instantiationType>;
82 isHiddenCategorySelected: boolean;
86 onImportFileChange():void;
87 validateField(field:any):boolean;
88 validateName(isInit:boolean):void;
89 calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
90 onVendorNameChange(oldVendorName:string):void;
91 convertCategoryStringToOneArray(category:string, subcategory:string):Array<IMainCategory>;
92 onCategoryChange():void;
93 onEcompGeneratedNamingChange():void;
94 onBaseTypeChange():void;
95 openOnBoardingModal():void;
96 initCategoreis():void;
97 initEnvironmentContext():void;
98 initInstantiationTypes():void;
100 onInstantiationTypeChange():void;
102 possibleToUpdateIcon():boolean;
106 // tslint:disable-next-line:max-classes-per-file
107 export class GeneralViewModel {
111 'Sdc.Services.CacheService',
112 'ComponentNameValidationPattern',
113 'ContactIdValidationPattern',
114 'TagValidationPattern',
115 'VendorReleaseValidationPattern',
116 'VendorNameValidationPattern',
117 'VendorModelNumberValidationPattern',
118 'CommentValidationPattern',
123 'EventListenerService',
125 'Sdc.Services.ProgressService',
137 constructor(private $scope:IGeneralScope,
138 private cacheService:CacheService,
139 private ComponentNameValidationPattern:RegExp,
140 private ContactIdValidationPattern:RegExp,
141 private TagValidationPattern:RegExp,
142 private VendorReleaseValidationPattern:RegExp,
143 private VendorNameValidationPattern:RegExp,
144 private VendorModelNumberValidationPattern:RegExp,
145 private CommentValidationPattern:RegExp,
146 private ValidationUtils:ValidationUtils,
147 private sdcConfig:IAppConfigurtaion,
148 private $state:ng.ui.IStateService,
149 private ModalsHandler:ModalsHandler,
150 private EventListenerService:EventListenerService,
151 private Notification:any,
152 private progressService:ProgressService,
153 protected $interval:any,
154 private $filter:ng.IFilterService,
155 private $timeout:ng.ITimeoutService,
156 private onBoardingService: OnboardingService,
157 private ComponentFactory:ComponentFactory,
158 private importVSPService: ImportVSPService,
159 private elementService: ElementService,
160 private modelService: ModelService,
161 private $stateParams: any) {
163 this.initScopeValidation();
164 this.initScopeMethods();
171 private initScopeValidation = ():void => {
172 this.$scope.validation = new Validation();
173 this.$scope.validation.componentNameValidationPattern = this.ComponentNameValidationPattern;
174 this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
175 this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
176 this.$scope.validation.VendorReleaseValidationPattern = this.VendorReleaseValidationPattern;
177 this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern;
178 this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern;
179 this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
182 private loadOnboardingFileCache = (): Observable<Dictionary<Dictionary<string>>> => {
183 let onboardCsarFilesMap:Dictionary<Dictionary<string>>;
184 let onSuccess = (vsps:Array<ICsarComponent>) => {
185 onboardCsarFilesMap = {};
186 _.each(vsps, (vsp:ICsarComponent)=>{
187 onboardCsarFilesMap[vsp.packageId] = onboardCsarFilesMap[vsp.packageId] || {};
188 onboardCsarFilesMap[vsp.packageId][vsp.version] = vsp.vspName + " (" + vsp.version + ")";
190 this.cacheService.set('onboardCsarFilesMap', onboardCsarFilesMap);
191 return onboardCsarFilesMap;
193 let onError = (): void =>{
194 console.log("Error getting onboarding list");
196 return this.onBoardingService.getOnboardingVSPs().map(onSuccess, onError);
199 private setImportedFileText = ():void => {
201 if(!this.$scope.isShowOnboardingSelectionBrowse) return;
203 //these variables makes it easier to read this logic
204 let csarUUID:string = (<Resource>this.$scope.component).csarUUID;
205 let csarVersion:string = (<Resource>this.$scope.component).csarVersion;
207 let onboardCsarFilesMap:Dictionary<Dictionary<string>> = this.cacheService.get('onboardCsarFilesMap');
208 let assignFileName = ():void => {
209 if(this.$scope.component.vspArchived){
210 this.$scope.importedToscaBrowseFileText = 'VSP is archived';
212 if(this.$stateParams.componentCsar && this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN' && !this.$scope.isCreateMode()) {
213 this.$scope.importedToscaBrowseFileText = this.$scope.originComponent.name + ' (' + (this.$scope.originComponent as Resource).csarVersion + ')';
215 this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[csarUUID][csarVersion];
221 if(this.$scope.component.vspArchived || (onboardCsarFilesMap && onboardCsarFilesMap[csarUUID] && onboardCsarFilesMap[csarUUID][csarVersion])){ //check that the file name is already in cache
224 this.loadOnboardingFileCache().subscribe((onboardingFiles) => {
225 onboardCsarFilesMap = onboardingFiles;
226 this.cacheService.set('onboardCsarFilesMap', onboardingFiles);
233 isCreateModeAvailable(verifyObj:string): boolean {
234 var isCheckout:boolean = ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState;
235 return this.$scope.isCreateMode() || (isCheckout && !verifyObj)
238 private initScope = ():void => {
240 this.$scope.importCsarProgressKey = "importCsarProgressKey";
242 this.$scope.browseFileLabel = (this.$scope.component.isResource() && ((<Resource>this.$scope.component).resourceType === ResourceType.VF || (<Resource>this.$scope.component).resourceType === 'SRVC')) || this.$scope.component.isService() ? 'Upload File:' : 'Upload VFC:';
243 this.$scope.progressService = this.progressService;
244 this.$scope.componentCategories = new componentCategories();
245 this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
249 this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
252 this.$scope.initCategoreis();
254 // Init Environment Context
255 this.$scope.initEnvironmentContext();
257 // Init the decision if to show file browse.
258 this.$scope.isShowFileBrowse = false;
259 if (this.$scope.component.isResource()) {
260 let resource:Resource = <Resource>this.$scope.component;
261 console.log(resource.name + ": " + resource.csarUUID);
262 if (resource.importedFile) { // Component has imported file.
263 this.$scope.isShowFileBrowse = true;
265 if (resource.resourceType === ResourceType.VF && !resource.csarUUID) {
266 this.$scope.isShowFileBrowse = true;
268 } else if(this.$scope.component.isService()){
269 let service: Service = <Service>this.$scope.component;
270 console.log(service.name + ": " + service.csarUUID);
271 if (service.importedFile) { // Component has imported file.
272 this.$scope.isShowFileBrowse = true;
273 (<Service>this.$scope.component).serviceType = 'Service';
275 if (this.$scope.isEditMode() && service.serviceType == 'Service' && !service.csarUUID) {
276 this.$scope.isShowFileBrowse = true;
278 // Init Instantiation types
279 this.$scope.initInstantiationTypes();
280 this.$scope.initBaseTypes();
281 this.$scope.initModel();
284 if (this.cacheService.get(PREVIOUS_CSAR_COMPONENT)) { //keep the old component in the cache until checkout, so we dont need to pass it around
285 this.$scope.setOriginComponent(this.cacheService.get(PREVIOUS_CSAR_COMPONENT));
286 this.cacheService.remove(PREVIOUS_CSAR_COMPONENT);
289 if (this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
290 this.$scope.updateUnsavedFileFlag(true);
294 if (this.$scope.component.isResource() &&
295 (this.$scope.component as Resource).resourceType === ResourceType.VF ||
296 (this.$scope.component as Resource).resourceType === ResourceType.PNF && (this.$scope.component as Resource).csarUUID) {
297 this.$scope.isShowOnboardingSelectionBrowse = true;
298 this.setImportedFileText();
300 this.$scope.isShowOnboardingSelectionBrowse = false;
304 //init file extensions based on the file that was imported.
305 if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
306 let fileName:string = (<Resource>this.$scope.component).importedFile.filename;
307 let fileExtension:string = fileName.split(".").pop();
308 if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
309 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
310 (<Resource>this.$scope.component).importedFile.filetype = "csar";
311 } else if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
312 (<Resource>this.$scope.component).importedFile.filetype = "yaml";
313 this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
315 this.$scope.restoreFile = angular.copy((<Resource>this.$scope.originComponent).importedFile); //create backup
316 } else if (this.$scope.isEditMode() && (<Resource>this.$scope.component).resourceType === ResourceType.VF) {
317 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
318 //(<Resource>this.$scope.component).importedFile.filetype="csar";
323 this.$scope.setValidState(true);
325 this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
326 let uniqueId:string = mainCategory;
328 uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
333 //TODO remove this after handling contact in UI
334 if (this.$scope.isCreateMode()) {
335 this.$scope.component.contactId = this.cacheService.get("user").userId;
336 this.$scope.originComponent.contactId = this.$scope.component.contactId;
340 this.$scope.$on('$destroy', () => {
341 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE);
342 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE);
347 // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
348 private convertCategoryStringToOneArray = ():IMainCategory[] => {
349 let tmp = this.$scope.component.selectedCategory.split("_#_");
350 let mainCategory = tmp[0];
351 let subCategory = tmp[1];
353 // Find the selected category and add the relevant sub category.
354 let selectedMainCategory:IMainCategory = <IMainCategory>_.find(this.$scope.categories, function (item) {
355 return item["name"] === mainCategory;
359 let mainCategoryClone = angular.copy(selectedMainCategory);
361 let selectedSubcategory = <ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
362 return item["name"] === subCategory;
364 mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
366 let tmpSelected = <IMainCategory> mainCategoryClone;
368 let result:IMainCategory[] = [];
369 result.push(tmpSelected);
374 private updateComponentNameInBreadcrumbs = ():void => {
375 // update breadcrum after changing name
376 this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
377 this.$scope.updateMenuComponentName(this.$scope.component.name);
380 //Find if a category is applicable for External API or not
381 private isHiddenCategory = (category: string) => {
382 let items: Array<any> = new Array<any>();
383 items = this.$scope.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()];
384 for(let index = 0; index < items.length; ++index) {
385 if ((items[index].hiddenCategories && items[index].hiddenCategories.indexOf(category) > -1)) {
392 private filteredCategories = () => {
393 let tempCategories: Array<IMainCategory> = new Array<IMainCategory>();
394 this.$scope.categories.forEach((category) => {
395 if (!this.isHiddenCategory(category.name)
396 && this.$scope.isCreateMode()
398 tempCategories.push(category);
399 } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
400 && !this.isHiddenCategory(this.$scope.component.selectedCategory)
401 && !this.isHiddenCategory(category.name)
403 tempCategories.push(category);
404 } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
405 && this.isHiddenCategory(this.$scope.component.selectedCategory)) {
406 tempCategories.push(category);
410 return tempCategories;
413 private initScopeMethods = ():void => {
415 this.$scope.initCategoreis = ():void => {
416 if (this.$scope.componentType === ComponentType.RESOURCE) {
417 this.$scope.categories = this.cacheService.get('resourceCategories');
420 if (this.$scope.componentType === ComponentType.SERVICE) {
421 this.$scope.categories = this.cacheService.get('serviceCategories');
423 //Remove categories from dropdown applicable for External API
424 if (this.$scope.isCreateMode() || (ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)) {
425 this.$scope.categories = this.filteredCategories();
426 //Flag to disbale category if service is created through External API
427 this.$scope.isHiddenCategorySelected = this.isHiddenCategory(this.$scope.component.selectedCategory);
433 this.$scope.initInstantiationTypes = ():void => {
434 if (this.$scope.componentType === ComponentType.SERVICE) {
435 this.$scope.instantiationTypes = new Array();
436 this.$scope.instantiationTypes.push(instantiationType.A_LA_CARTE);
437 this.$scope.instantiationTypes.push(instantiationType.MACRO);
438 var instantiationTypeField:string =(<Service>this.$scope.component).instantiationType;
439 if (instantiationTypeField === ""){
440 this.$scope.instantiationTypes.push("");
442 else if (this.isCreateModeAvailable(instantiationTypeField)) {
443 (<Service>this.$scope.component).instantiationType = instantiationType.A_LA_CARTE;
449 this.$scope.initBaseTypes = ():void => {
450 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component && this.$scope.component.categories) {
451 this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name).subscribe((data: BaseTypeResponse[]) => {
452 this.$scope.baseTypes = []
453 this.$scope.baseTypeVersions = []
454 data.forEach(baseType => {
455 this.$scope.baseTypes.push(baseType.toscaResourceName)
456 if (baseType.toscaResourceName === this.$scope.component.derivedFromGenericType){
457 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
463 this.$scope.initModel = ():void => {
464 if (this.$scope.componentType === ComponentType.SERVICE) {
465 this.$scope.models = new Array();
466 this.modelService.getModels().subscribe((modelsFound: Model[]) => {
467 modelsFound.forEach(model => {this.$scope.models.push(model.name)});})
468 this.$scope.models.filter(model => model.name === (<Service>this.$scope.component).model);
472 this.$scope.initEnvironmentContext = ():void => {
473 if (this.$scope.componentType === ComponentType.SERVICE) {
474 this.$scope.environmentContextObj = this.cacheService.get('UIConfiguration').environmentContext;
475 var environmentContext:string =(<Service>this.$scope.component).environmentContext;
476 // In creation new service OR check outing old service without environmentContext parameter - set default value
477 if(this.isCreateModeAvailable(environmentContext)){
478 (<Service>this.$scope.component).environmentContext = this.$scope.environmentContextObj.defaultValue;
483 this.$scope.validateField = (field:any):boolean => {
484 if (field && field.$dirty && field.$invalid) {
490 this.$scope.openOnBoardingModal = ():void => {
491 if(this.$scope.component.vspArchived) return;
492 let csarUUID = (<Resource>this.$scope.component).csarUUID;
493 let csarVersion = (<Resource>this.$scope.component).csarVersion;
494 this.importVSPService.openOnboardingModal(csarUUID, csarVersion).subscribe((result) => {
495 this.ComponentFactory.getComponentWithMetadataFromServer(result.type.toUpperCase(), result.previousComponent.uniqueId).then(
496 (component:Component)=> {
497 if (result.componentCsar && component.isResource()){
498 this.cacheService.set(PREVIOUS_CSAR_COMPONENT, angular.copy(component));
499 component = this.ComponentFactory.updateComponentFromCsar(result.componentCsar, <Resource>component);
501 this.$scope.setComponent(component);
503 this.setImportedFileText();
510 this.$scope.updateIcon = ():void => {
511 this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
512 if(isDirty && !this.$scope.isCreateMode()){
513 this.setUnsavedChanges(true);
520 this.$scope.possibleToUpdateIcon = ():boolean => {
521 if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName) && !this.$scope.component.isAlreadyCertified()){
528 this.$scope.validateName = (isInit:boolean):void => {
529 if (isInit === undefined) {
533 let name = this.$scope.component.name;
534 if (!name || name === "") {
535 if (this.$scope.editForm
536 && this.$scope.editForm["componentName"]
537 && this.$scope.editForm["componentName"].$error) {
539 // Clear the error name already exists
540 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
546 let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
547 if (subtype == "SRVC") {
551 const onFailed = (response) => {
552 // console.info('onFaild', response);
553 // this.$scope.isLoading = false;
556 const onSuccess = (validation:IValidate) => {
557 this.$scope.editForm['componentName'].$setValidity('nameExist', validation.isValid);
558 if (validation.isValid) {
559 // update breadcrumb after changing name
560 this.updateComponentNameInBreadcrumbs();
565 // When page is init after update
566 if (this.$scope.component.name !== this.$scope.originComponent.name) {
567 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
569 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
573 // Validating on change (has debounce)
574 if (this.$scope.editForm
575 && this.$scope.editForm["componentName"]
576 && this.$scope.editForm["componentName"].$error
577 && !this.$scope.editForm["componentName"].$error.pattern
578 && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase())
580 if (!(this.$scope.componentType === ComponentType.RESOURCE && (this.$scope.component as Resource).csarUUID !== undefined)
582 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
584 } else if (this.$scope.editForm && this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
586 this.$scope.editForm['componentName'].$setValidity('nameExist', true);
592 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, (nextState) => {
593 if (this.$state.current.data.unsavedChanges && this.$scope.isValidForm) {
594 this.$scope.save().then(() => {
595 this.$scope.handleChangeLifecycleState(nextState);
597 console.error('Save failed, unable to change lifecycle state to ' + nextState);
599 } else if(!this.$scope.isValidForm){
600 console.error('Form is not valid');
602 let newCsarVersion:string;
603 if(this.$scope.unsavedFile) {
604 newCsarVersion = (this.$scope.component as Resource).csarVersion;
606 if(this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
607 const onError = (): void => {
608 if (this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN') {
609 this.$scope.revert();
612 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion, onError);
615 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion);
620 this.$scope.revert = ():void => {
621 // in state of import file leave the file in place
623 this.$scope.setComponent(this.ComponentFactory.createComponent(this.$scope.originComponent));
625 if (this.$scope.component.isResource() && this.$scope.restoreFile) {
626 (this.$scope.component as Resource).importedFile = angular.copy(this.$scope.restoreFile);
629 this.setImportedFileText();
630 this.$scope.updateBreadcrumbs(this.$scope.component); // update on workspace
632 this.$scope.componentCategories.selectedCategory = this.$scope.originComponent.selectedCategory;
633 this.setUnsavedChanges(false);
634 this.$scope.updateUnsavedFileFlag(false);
635 this.$scope.editForm.$setPristine();
638 this.$scope.onImportFileChange = () => {
640 if( !this.$scope.restoreFile && this.$scope.editForm.fileElement.value && this.$scope.editForm.fileElement.value.filename || // if file started empty but we have added a new one
641 this.$scope.restoreFile && !angular.equals(this.$scope.restoreFile, this.$scope.editForm.fileElement.value)){ // or file was swapped for a new one
642 this.$scope.updateUnsavedFileFlag(true);
644 this.$scope.updateUnsavedFileFlag(false);
645 this.$scope.editForm.fileElement.$setPristine();
649 this.$scope.$watchCollection('component.name', (newData: any): void => {
650 this.$scope.validateName(false);
653 // Notify the parent if this step valid or not.
654 this.$scope.$watch('editForm.$valid', (newVal, oldVal) => {
655 this.$scope.setValidState(newVal);
658 this.$scope.$watch('editForm.$dirty', (newVal, oldVal) => {
659 if (newVal && !this.$scope.isCreateMode()) {
660 this.setUnsavedChanges(true);
665 this.$scope.onCategoryChange = (): void => {
666 this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory;
667 this.$scope.component.categories = this.convertCategoryStringToOneArray();
668 this.$scope.component.icon = DEFAULT_ICON;
669 if (this.$scope.component.categories[0].metadataKeys) {
670 for (let metadataKey of this.$scope.component.categories[0].metadataKeys) {
671 if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
672 this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
676 if (this.$scope.component.categories[0].subcategories && this.$scope.component.categories[0].subcategories[0].metadataKeys) {
677 for (let metadataKey of this.$scope.component.categories[0].subcategories[0].metadataKeys) {
678 if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
679 this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
683 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component.categories[0]) {
684 this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name).subscribe((data: BaseTypeResponse[]) => {
686 if(this.$scope.isCreateMode()){
687 this.$scope.baseTypes = []
688 this.$scope.baseTypeVersions = []
689 data.forEach(baseType => this.$scope.baseTypes.push(baseType.toscaResourceName));
690 data[0].versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
691 this.$scope.component.derivedFromGenericType = data[0].toscaResourceName;
692 this.$scope.component.derivedFromGenericVersion = data[0].versions[0];
694 var isValidForBaseType:boolean = false;
695 data.forEach(baseType => {if (!this.$scope.component.derivedFromGenericType || baseType.toscaResourceName === this.$scope.component.derivedFromGenericType){
696 isValidForBaseType = true;
698 this.$scope.editForm['category'].$setValidity('validForBaseType', isValidForBaseType);
704 this.$scope.onEcompGeneratedNamingChange = (): void => {
705 if (!(this.$scope.component as Service).ecompGeneratedNaming) {
706 (this.$scope.component as Service).namingPolicy = '';
710 this.$scope.onBaseTypeChange = (): void => {
711 this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name).subscribe((data: BaseTypeResponse[]) => {
712 this.$scope.baseTypeVersions = []
713 data.forEach(baseType => {
714 if(baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) {
715 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
716 this.$scope.component.derivedFromGenericVersion = baseType.versions[0];
722 this.$scope.onVendorNameChange = (oldVendorName: string): void => {
723 if (this.$scope.component.icon === oldVendorName) {
724 this.$scope.component.icon = DEFAULT_ICON;
727 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload);
730 this.$scope.isMetadataKeyMandatory = (key: string): boolean => {
731 let metadataKey = this.getMetadataKey(this.$scope.component.categories, key);
732 return metadataKey && metadataKey.mandatory;
735 this.$scope.getMetadataKeyValidValues = (key: string): string[] => {
736 let metadataKey = this.getMetadataKey(this.$scope.component.categories, key);
738 return metadataKey.validValues;
743 this.$scope.isMetadataKeyForComponentCategory = (key: string): boolean => {
744 return this.getMetadataKey(this.$scope.component.categories, key) != null;
747 this.$scope.isCategoryServiceMetadataKey = (key: string): boolean => {
748 return this.isServiceMetadataKey(key);
751 this.$scope.isMetadataKeyForComponentCategoryService = (key: string, attribute: string): boolean => {
752 let metadatakey = this.getMetadataKey(this.$scope.component.categories, key);
753 if (metadatakey && (!this.$scope.component[attribute] || !metadatakey.validValues.find(v => v === this.$scope.component[attribute]))) {
754 this.$scope.component[attribute] = metadatakey.defaultValue;
756 return metadatakey != null;
760 private setUnsavedChanges = (hasChanges: boolean): void => {
761 this.$state.current.data.unsavedChanges = hasChanges;
764 private getMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
765 let metadataKey = this.getSubcategoryMetadataKey(this.$scope.component.categories, key);
767 return this.getCategoryMetadataKey(this.$scope.component.categories, key);
772 private getSubcategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
773 if (categories[0].subcategories && categories[0].subcategories[0].metadataKeys && categories[0].subcategories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
774 return categories[0].subcategories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
779 private getCategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
780 if (categories[0].metadataKeys && categories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
781 return categories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
786 private isServiceMetadataKey(key: string) : boolean {
787 return CATEGORY_SERVICE_METADATA_KEYS.indexOf(key) > -1;