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, 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 interface IEnvironmentContext {
58 validValues:Array<string>;
61 export interface IGeneralScope extends IWorkspaceViewModelScope {
62 validation:Validation;
63 editForm:ng.IFormController;
64 categories:Array<IMainCategory>;
65 environmentContextObj:IEnvironmentContext;
66 latestCategoryId:string;
67 latestVendorName:string;
68 importedFileExtension:any;
70 isShowFileBrowse:boolean;
71 isShowOnboardingSelectionBrowse:boolean;
72 importedToscaBrowseFileText:string;
73 importCsarProProgressKey:string;
74 browseFileLabel:string;
75 componentCategories:componentCategories;
76 instantiationTypes:Array<instantiationType>;
77 isHiddenCategorySelected: boolean;
81 onImportFileChange():void;
82 validateField(field:any):boolean;
83 validateName(isInit:boolean):void;
84 calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
85 onVendorNameChange(oldVendorName:string):void;
86 convertCategoryStringToOneArray(category:string, subcategory:string):Array<IMainCategory>;
87 onCategoryChange():void;
88 onEcompGeneratedNamingChange():void;
89 onBaseTypeChange():void;
90 openOnBoardingModal():void;
91 initCategoreis():void;
92 initEnvironmentContext():void;
93 initInstantiationTypes():void;
95 onInstantiationTypeChange():void;
97 possibleToUpdateIcon():boolean;
100 // tslint:disable-next-line:max-classes-per-file
101 export class GeneralViewModel {
105 'Sdc.Services.CacheService',
106 'ComponentNameValidationPattern',
107 'ContactIdValidationPattern',
108 'TagValidationPattern',
109 'VendorReleaseValidationPattern',
110 'VendorNameValidationPattern',
111 'VendorModelNumberValidationPattern',
112 'CommentValidationPattern',
117 'EventListenerService',
119 'Sdc.Services.ProgressService',
130 constructor(private $scope:IGeneralScope,
131 private cacheService:CacheService,
132 private ComponentNameValidationPattern:RegExp,
133 private ContactIdValidationPattern:RegExp,
134 private TagValidationPattern:RegExp,
135 private VendorReleaseValidationPattern:RegExp,
136 private VendorNameValidationPattern:RegExp,
137 private VendorModelNumberValidationPattern:RegExp,
138 private CommentValidationPattern:RegExp,
139 private ValidationUtils:ValidationUtils,
140 private sdcConfig:IAppConfigurtaion,
141 private $state:ng.ui.IStateService,
142 private ModalsHandler:ModalsHandler,
143 private EventListenerService:EventListenerService,
144 private Notification:any,
145 private progressService:ProgressService,
146 protected $interval:any,
147 private $filter:ng.IFilterService,
148 private $timeout:ng.ITimeoutService,
149 private onBoardingService: OnboardingService,
150 private ComponentFactory:ComponentFactory,
151 private importVSPService: ImportVSPService,
152 private elementService: ElementService,
153 private $stateParams: any) {
155 this.initScopeValidation();
156 this.initScopeMethods();
163 private initScopeValidation = ():void => {
164 this.$scope.validation = new Validation();
165 this.$scope.validation.componentNameValidationPattern = this.ComponentNameValidationPattern;
166 this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
167 this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
168 this.$scope.validation.VendorReleaseValidationPattern = this.VendorReleaseValidationPattern;
169 this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern;
170 this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern;
171 this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
174 private loadOnboardingFileCache = (): Observable<Dictionary<Dictionary<string>>> => {
175 let onboardCsarFilesMap:Dictionary<Dictionary<string>>;
176 let onSuccess = (vsps:Array<ICsarComponent>) => {
177 onboardCsarFilesMap = {};
178 _.each(vsps, (vsp:ICsarComponent)=>{
179 onboardCsarFilesMap[vsp.packageId] = onboardCsarFilesMap[vsp.packageId] || {};
180 onboardCsarFilesMap[vsp.packageId][vsp.version] = vsp.vspName + " (" + vsp.version + ")";
182 this.cacheService.set('onboardCsarFilesMap', onboardCsarFilesMap);
183 return onboardCsarFilesMap;
185 let onError = (): void =>{
186 console.log("Error getting onboarding list");
188 return this.onBoardingService.getOnboardingVSPs().map(onSuccess, onError);
191 private setImportedFileText = ():void => {
193 if(!this.$scope.isShowOnboardingSelectionBrowse) return;
195 //these variables makes it easier to read this logic
196 let csarUUID:string = (<Resource>this.$scope.component).csarUUID;
197 let csarVersion:string = (<Resource>this.$scope.component).csarVersion;
199 let onboardCsarFilesMap:Dictionary<Dictionary<string>> = this.cacheService.get('onboardCsarFilesMap');
200 let assignFileName = ():void => {
201 if(this.$scope.component.vspArchived){
202 this.$scope.importedToscaBrowseFileText = 'VSP is archived';
204 if(this.$stateParams.componentCsar && this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN' && !this.$scope.isCreateMode()) {
205 this.$scope.importedToscaBrowseFileText = this.$scope.originComponent.name + ' (' + (this.$scope.originComponent as Resource).csarVersion + ')';
207 this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[csarUUID][csarVersion];
213 if(this.$scope.component.vspArchived || (onboardCsarFilesMap && onboardCsarFilesMap[csarUUID] && onboardCsarFilesMap[csarUUID][csarVersion])){ //check that the file name is already in cache
216 this.loadOnboardingFileCache().subscribe((onboardingFiles) => {
217 onboardCsarFilesMap = onboardingFiles;
218 this.cacheService.set('onboardCsarFilesMap', onboardingFiles);
225 isCreateModeAvailable(verifyObj:string): boolean {
226 var isCheckout:boolean = ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState;
227 return this.$scope.isCreateMode() || (isCheckout && !verifyObj)
230 private initScope = ():void => {
232 this.$scope.importCsarProgressKey = "importCsarProgressKey";
234 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:';
235 this.$scope.progressService = this.progressService;
236 this.$scope.componentCategories = new componentCategories();
237 this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
241 this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
244 this.$scope.initCategoreis();
246 // Init Environment Context
247 this.$scope.initEnvironmentContext();
249 // Init the decision if to show file browse.
250 this.$scope.isShowFileBrowse = false;
251 if (this.$scope.component.isResource()) {
252 let resource:Resource = <Resource>this.$scope.component;
253 console.log(resource.name + ": " + resource.csarUUID);
254 if (resource.importedFile) { // Component has imported file.
255 this.$scope.isShowFileBrowse = true;
257 if (resource.resourceType === ResourceType.VF && !resource.csarUUID) {
258 this.$scope.isShowFileBrowse = true;
260 } else if(this.$scope.component.isService()){
261 let service: Service = <Service>this.$scope.component;
262 console.log(service.name + ": " + service.csarUUID);
263 if (service.importedFile) { // Component has imported file.
264 this.$scope.isShowFileBrowse = true;
265 (<Service>this.$scope.component).serviceType = 'Service';
267 if (this.$scope.isEditMode() && service.serviceType == 'Service' && !service.csarUUID) {
268 this.$scope.isShowFileBrowse = true;
270 // Init Instantiation types
271 this.$scope.initInstantiationTypes();
272 this.$scope.initBaseTypes();
275 if (this.cacheService.get(PREVIOUS_CSAR_COMPONENT)) { //keep the old component in the cache until checkout, so we dont need to pass it around
276 this.$scope.setOriginComponent(this.cacheService.get(PREVIOUS_CSAR_COMPONENT));
277 this.cacheService.remove(PREVIOUS_CSAR_COMPONENT);
280 if (this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
281 this.$scope.updateUnsavedFileFlag(true);
285 if (this.$scope.component.isResource() &&
286 (this.$scope.component as Resource).resourceType === ResourceType.VF ||
287 (this.$scope.component as Resource).resourceType === ResourceType.PNF && (this.$scope.component as Resource).csarUUID) {
288 this.$scope.isShowOnboardingSelectionBrowse = true;
289 this.setImportedFileText();
291 this.$scope.isShowOnboardingSelectionBrowse = false;
295 //init file extensions based on the file that was imported.
296 if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
297 let fileName:string = (<Resource>this.$scope.component).importedFile.filename;
298 let fileExtension:string = fileName.split(".").pop();
299 if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
300 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
301 (<Resource>this.$scope.component).importedFile.filetype = "csar";
302 } else if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
303 (<Resource>this.$scope.component).importedFile.filetype = "yaml";
304 this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
306 this.$scope.restoreFile = angular.copy((<Resource>this.$scope.originComponent).importedFile); //create backup
307 } else if (this.$scope.isEditMode() && (<Resource>this.$scope.component).resourceType === ResourceType.VF) {
308 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
309 //(<Resource>this.$scope.component).importedFile.filetype="csar";
314 this.$scope.setValidState(true);
316 this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
317 let uniqueId:string = mainCategory;
319 uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
324 //TODO remove this after handling contact in UI
325 if (this.$scope.isCreateMode()) {
326 this.$scope.component.contactId = this.cacheService.get("user").userId;
327 this.$scope.originComponent.contactId = this.$scope.component.contactId;
331 this.$scope.$on('$destroy', () => {
332 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE);
333 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE);
338 // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
339 private convertCategoryStringToOneArray = ():IMainCategory[] => {
340 let tmp = this.$scope.component.selectedCategory.split("_#_");
341 let mainCategory = tmp[0];
342 let subCategory = tmp[1];
344 // Find the selected category and add the relevant sub category.
345 let selectedMainCategory:IMainCategory = <IMainCategory>_.find(this.$scope.categories, function (item) {
346 return item["name"] === mainCategory;
350 let mainCategoryClone = angular.copy(selectedMainCategory);
352 let selectedSubcategory = <ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
353 return item["name"] === subCategory;
355 mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
357 let tmpSelected = <IMainCategory> mainCategoryClone;
359 let result:IMainCategory[] = [];
360 result.push(tmpSelected);
365 private updateComponentNameInBreadcrumbs = ():void => {
366 // update breadcrum after changing name
367 this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
368 this.$scope.updateMenuComponentName(this.$scope.component.name);
371 //Find if a category is applicable for External API or not
372 private isHiddenCategory = (category: string) => {
373 let items: Array<any> = new Array<any>();
374 items = this.$scope.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()];
375 for(let index = 0; index < items.length; ++index) {
376 if ((items[index].hiddenCategories && items[index].hiddenCategories.indexOf(category) > -1)) {
383 private filteredCategories = () => {
384 let tempCategories: Array<IMainCategory> = new Array<IMainCategory>();
385 this.$scope.categories.forEach((category) => {
386 if (!this.isHiddenCategory(category.name)
387 && this.$scope.isCreateMode()
389 tempCategories.push(category);
390 } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
391 && !this.isHiddenCategory(this.$scope.component.selectedCategory)
392 && !this.isHiddenCategory(category.name)
394 tempCategories.push(category);
395 } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
396 && this.isHiddenCategory(this.$scope.component.selectedCategory)) {
397 tempCategories.push(category);
401 return tempCategories;
404 private initScopeMethods = ():void => {
406 this.$scope.initCategoreis = ():void => {
407 if (this.$scope.componentType === ComponentType.RESOURCE) {
408 this.$scope.categories = this.cacheService.get('resourceCategories');
411 if (this.$scope.componentType === ComponentType.SERVICE) {
412 this.$scope.categories = this.cacheService.get('serviceCategories');
414 //Remove categories from dropdown applicable for External API
415 if (this.$scope.isCreateMode() || (ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)) {
416 this.$scope.categories = this.filteredCategories();
417 //Flag to disbale category if service is created through External API
418 this.$scope.isHiddenCategorySelected = this.isHiddenCategory(this.$scope.component.selectedCategory);
424 this.$scope.initInstantiationTypes = ():void => {
425 if (this.$scope.componentType === ComponentType.SERVICE) {
426 this.$scope.instantiationTypes = new Array();
427 this.$scope.instantiationTypes.push(instantiationType.A_LA_CARTE);
428 this.$scope.instantiationTypes.push(instantiationType.MACRO);
429 var instantiationTypeField:string =(<Service>this.$scope.component).instantiationType;
430 if (instantiationTypeField === ""){
431 this.$scope.instantiationTypes.push("");
433 else if (this.isCreateModeAvailable(instantiationTypeField)) {
434 (<Service>this.$scope.component).instantiationType = instantiationType.A_LA_CARTE;
440 this.$scope.initBaseTypes = ():void => {
441 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component && this.$scope.component.categories) {
442 this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name).subscribe((data: BaseTypeResponse[]) => {
443 this.$scope.baseTypes = []
444 this.$scope.baseTypeVersions = []
445 data.forEach(baseType => {
446 this.$scope.baseTypes.push(baseType.toscaResourceName)
447 if (baseType.toscaResourceName === this.$scope.component.derivedFromGenericType){
448 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
454 this.$scope.initEnvironmentContext = ():void => {
455 if (this.$scope.componentType === ComponentType.SERVICE) {
456 this.$scope.environmentContextObj = this.cacheService.get('UIConfiguration').environmentContext;
457 var environmentContext:string =(<Service>this.$scope.component).environmentContext;
458 // In creation new service OR check outing old service without environmentContext parameter - set default value
459 if(this.isCreateModeAvailable(environmentContext)){
460 (<Service>this.$scope.component).environmentContext = this.$scope.environmentContextObj.defaultValue;
465 this.$scope.validateField = (field:any):boolean => {
466 if (field && field.$dirty && field.$invalid) {
472 this.$scope.openOnBoardingModal = ():void => {
473 if(this.$scope.component.vspArchived) return;
474 let csarUUID = (<Resource>this.$scope.component).csarUUID;
475 let csarVersion = (<Resource>this.$scope.component).csarVersion;
476 this.importVSPService.openOnboardingModal(csarUUID, csarVersion).subscribe((result) => {
477 this.ComponentFactory.getComponentWithMetadataFromServer(result.type.toUpperCase(), result.previousComponent.uniqueId).then(
478 (component:Component)=> {
479 if (result.componentCsar && component.isResource()){
480 this.cacheService.set(PREVIOUS_CSAR_COMPONENT, angular.copy(component));
481 component = this.ComponentFactory.updateComponentFromCsar(result.componentCsar, <Resource>component);
483 this.$scope.setComponent(component);
485 this.setImportedFileText();
492 this.$scope.updateIcon = ():void => {
493 this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
494 if(isDirty && !this.$scope.isCreateMode()){
495 this.setUnsavedChanges(true);
502 this.$scope.possibleToUpdateIcon = ():boolean => {
503 if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName) && !this.$scope.component.isAlreadyCertified()){
510 this.$scope.validateName = (isInit:boolean):void => {
511 if (isInit === undefined) {
515 let name = this.$scope.component.name;
516 if (!name || name === "") {
517 if (this.$scope.editForm
518 && this.$scope.editForm["componentName"]
519 && this.$scope.editForm["componentName"].$error) {
521 // Clear the error name already exists
522 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
528 let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
529 if (subtype == "SRVC") {
533 const onFailed = (response) => {
534 // console.info('onFaild', response);
535 // this.$scope.isLoading = false;
538 const onSuccess = (validation:IValidate) => {
539 this.$scope.editForm['componentName'].$setValidity('nameExist', validation.isValid);
540 if (validation.isValid) {
541 // update breadcrumb after changing name
542 this.updateComponentNameInBreadcrumbs();
547 // When page is init after update
548 if (this.$scope.component.name !== this.$scope.originComponent.name) {
549 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
551 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
555 // Validating on change (has debounce)
556 if (this.$scope.editForm
557 && this.$scope.editForm["componentName"]
558 && this.$scope.editForm["componentName"].$error
559 && !this.$scope.editForm["componentName"].$error.pattern
560 && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase())
562 if (!(this.$scope.componentType === ComponentType.RESOURCE && (this.$scope.component as Resource).csarUUID !== undefined)
564 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
566 } else if (this.$scope.editForm && this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
568 this.$scope.editForm['componentName'].$setValidity('nameExist', true);
574 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, (nextState) => {
575 if (this.$state.current.data.unsavedChanges && this.$scope.isValidForm) {
576 this.$scope.save().then(() => {
577 this.$scope.handleChangeLifecycleState(nextState);
579 console.error('Save failed, unable to change lifecycle state to ' + nextState);
581 } else if(!this.$scope.isValidForm){
582 console.error('Form is not valid');
584 let newCsarVersion:string;
585 if(this.$scope.unsavedFile) {
586 newCsarVersion = (this.$scope.component as Resource).csarVersion;
588 if(this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
589 const onError = (): void => {
590 if (this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN') {
591 this.$scope.revert();
594 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion, onError);
597 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion);
602 this.$scope.revert = ():void => {
603 // in state of import file leave the file in place
605 this.$scope.setComponent(this.ComponentFactory.createComponent(this.$scope.originComponent));
607 if (this.$scope.component.isResource() && this.$scope.restoreFile) {
608 (this.$scope.component as Resource).importedFile = angular.copy(this.$scope.restoreFile);
611 this.setImportedFileText();
612 this.$scope.updateBreadcrumbs(this.$scope.component); // update on workspace
614 this.$scope.componentCategories.selectedCategory = this.$scope.originComponent.selectedCategory;
615 this.setUnsavedChanges(false);
616 this.$scope.updateUnsavedFileFlag(false);
617 this.$scope.editForm.$setPristine();
620 this.$scope.onImportFileChange = () => {
622 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
623 this.$scope.restoreFile && !angular.equals(this.$scope.restoreFile, this.$scope.editForm.fileElement.value)){ // or file was swapped for a new one
624 this.$scope.updateUnsavedFileFlag(true);
626 this.$scope.updateUnsavedFileFlag(false);
627 this.$scope.editForm.fileElement.$setPristine();
631 this.$scope.$watchCollection('component.name', (newData: any): void => {
632 this.$scope.validateName(false);
635 // Notify the parent if this step valid or not.
636 this.$scope.$watch('editForm.$valid', (newVal, oldVal) => {
637 this.$scope.setValidState(newVal);
640 this.$scope.$watch('editForm.$dirty', (newVal, oldVal) => {
641 if (newVal && !this.$scope.isCreateMode()) {
642 this.setUnsavedChanges(true);
647 this.$scope.onCategoryChange = (): void => {
648 this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory;
649 this.$scope.component.categories = this.convertCategoryStringToOneArray();
650 this.$scope.component.icon = DEFAULT_ICON;
651 if (this.$scope.component.categories[0].metadataKeys) {
652 for (let metadataKey of this.$scope.component.categories[0].metadataKeys) {
653 if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
654 this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
658 if (this.$scope.component.categories[0].subcategories && this.$scope.component.categories[0].subcategories[0].metadataKeys) {
659 for (let metadataKey of this.$scope.component.categories[0].subcategories[0].metadataKeys) {
660 if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
661 this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
665 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component.categories[0]) {
666 this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name).subscribe((data: BaseTypeResponse[]) => {
668 if(this.$scope.isCreateMode()){
669 this.$scope.baseTypes = []
670 this.$scope.baseTypeVersions = []
671 data.forEach(baseType => this.$scope.baseTypes.push(baseType.toscaResourceName));
672 data[0].versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
673 this.$scope.component.derivedFromGenericType = data[0].toscaResourceName;
674 this.$scope.component.derivedFromGenericVersion = data[0].versions[0];
676 var isValidForBaseType:boolean = false;
677 data.forEach(baseType => {if (!this.$scope.component.derivedFromGenericType || baseType.toscaResourceName === this.$scope.component.derivedFromGenericType){
678 isValidForBaseType = true;
680 this.$scope.editForm['category'].$setValidity('validForBaseType', isValidForBaseType);
686 this.$scope.onEcompGeneratedNamingChange = (): void => {
687 if (!(this.$scope.component as Service).ecompGeneratedNaming) {
688 (this.$scope.component as Service).namingPolicy = '';
692 this.$scope.onBaseTypeChange = (): void => {
693 this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name).subscribe((data: BaseTypeResponse[]) => {
694 this.$scope.baseTypeVersions = []
695 data.forEach(baseType => {
696 if(baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) {
697 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
698 this.$scope.component.derivedFromGenericVersion = baseType.versions[0];
704 this.$scope.onVendorNameChange = (oldVendorName: string): void => {
705 if (this.$scope.component.icon === oldVendorName) {
706 this.$scope.component.icon = DEFAULT_ICON;
709 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload);
712 this.$scope.isMetadataKeyMandatory = (key: string): boolean => {
713 let metadataKey = this.getMetadataKey(this.$scope.component.categories, key);
714 return metadataKey && metadataKey.mandatory;
717 this.$scope.getMetadataKeyValidValues = (key: string): string[] => {
718 let metadataKey = this.getMetadataKey(this.$scope.component.categories, key);
720 return metadataKey.validValues;
725 this.$scope.isMetadataKeyForComponentCategory = (key: string): boolean => {
726 return this.getMetadataKey(this.$scope.component.categories, key) != null;
729 this.$scope.isCategoryServiceMetadataKey = (key: string): boolean => {
730 return this.isServiceMetadataKey(key);
733 this.$scope.isMetadataKeyForComponentCategoryService = (key: string, attribute: string): boolean => {
734 let metadatakey = this.getMetadataKey(this.$scope.component.categories, key);
735 if (metadatakey && (!this.$scope.component[attribute] || !metadatakey.validValues.find(v => v === this.$scope.component[attribute]))) {
736 this.$scope.component[attribute] = metadatakey.defaultValue;
738 return metadatakey != null;
742 private setUnsavedChanges = (hasChanges: boolean): void => {
743 this.$state.current.data.unsavedChanges = hasChanges;
746 private getMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
747 let metadataKey = this.getSubcategoryMetadataKey(this.$scope.component.categories, key);
749 return this.getCategoryMetadataKey(this.$scope.component.categories, key);
754 private getSubcategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
755 if (categories[0].subcategories && categories[0].subcategories[0].metadataKeys && categories[0].subcategories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
756 return categories[0].subcategories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
761 private getCategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
762 if (categories[0].metadataKeys && categories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
763 return categories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
768 private isServiceMetadataKey(key: string) : boolean {
769 return CATEGORY_SERVICE_METADATA_KEYS.indexOf(key) > -1;