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";
41 import {Model} from "../../../../models/model";
43 export class Validation {
44 componentNameValidationPattern:RegExp;
45 contactIdValidationPattern:RegExp;
46 tagValidationPattern:RegExp;
47 VendorReleaseValidationPattern:RegExp;
48 VendorNameValidationPattern:RegExp;
49 VendorModelNumberValidationPattern:RegExp;
50 commentValidationPattern:RegExp;
53 export class componentCategories {//categories field bind to this obj in order to solve this bug: DE242059
54 selectedCategory:string;
57 export class componentModel {
61 export interface IEnvironmentContext {
63 validValues:Array<string>;
66 export interface IGeneralScope extends IWorkspaceViewModelScope {
67 validation:Validation;
68 editForm:ng.IFormController;
69 categories:Array<IMainCategory>;
70 environmentContextObj:IEnvironmentContext;
71 latestCategoryId:string;
72 latestVendorName:string;
73 importedFileExtension:any;
75 isShowFileBrowse:boolean;
76 isShowOnboardingSelectionBrowse:boolean;
77 importedToscaBrowseFileText:string;
78 importCsarProProgressKey:string;
79 browseFileLabel:string;
80 componentCategories:componentCategories;
81 componentModel:componentModel;
82 instantiationTypes:Array<instantiationType>;
83 isHiddenCategorySelected: boolean;
87 onImportFileChange():void;
88 validateField(field:any):boolean;
89 validateName(isInit:boolean):void;
90 calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
91 onVendorNameChange(oldVendorName:string):void;
92 convertCategoryStringToOneArray(category:string, subcategory:string):Array<IMainCategory>;
93 onCategoryChange():void;
94 onEcompGeneratedNamingChange():void;
95 onBaseTypeChange():void;
96 openOnBoardingModal():void;
97 initCategoreis():void;
98 initEnvironmentContext():void;
99 initInstantiationTypes():void;
100 initBaseTypes():void;
101 onInstantiationTypeChange():void;
103 possibleToUpdateIcon():boolean;
107 // tslint:disable-next-line:max-classes-per-file
108 export class GeneralViewModel {
112 'Sdc.Services.CacheService',
113 'ComponentNameValidationPattern',
114 'ContactIdValidationPattern',
115 'TagValidationPattern',
116 'VendorReleaseValidationPattern',
117 'VendorNameValidationPattern',
118 'VendorModelNumberValidationPattern',
119 'CommentValidationPattern',
124 'EventListenerService',
126 'Sdc.Services.ProgressService',
138 constructor(private $scope:IGeneralScope,
139 private cacheService:CacheService,
140 private ComponentNameValidationPattern:RegExp,
141 private ContactIdValidationPattern:RegExp,
142 private TagValidationPattern:RegExp,
143 private VendorReleaseValidationPattern:RegExp,
144 private VendorNameValidationPattern:RegExp,
145 private VendorModelNumberValidationPattern:RegExp,
146 private CommentValidationPattern:RegExp,
147 private ValidationUtils:ValidationUtils,
148 private sdcConfig:IAppConfigurtaion,
149 private $state:ng.ui.IStateService,
150 private ModalsHandler:ModalsHandler,
151 private EventListenerService:EventListenerService,
152 private Notification:any,
153 private progressService:ProgressService,
154 protected $interval:any,
155 private $filter:ng.IFilterService,
156 private $timeout:ng.ITimeoutService,
157 private onBoardingService: OnboardingService,
158 private ComponentFactory:ComponentFactory,
159 private importVSPService: ImportVSPService,
160 private elementService: ElementService,
161 private modelService: ModelService,
162 private $stateParams: any) {
164 this.initScopeValidation();
165 this.initScopeMethods();
172 private initScopeValidation = ():void => {
173 this.$scope.validation = new Validation();
174 this.$scope.validation.componentNameValidationPattern = this.ComponentNameValidationPattern;
175 this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
176 this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
177 this.$scope.validation.VendorReleaseValidationPattern = this.VendorReleaseValidationPattern;
178 this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern;
179 this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern;
180 this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
183 private loadOnboardingFileCache = (): Observable<Dictionary<Dictionary<string>>> => {
184 let onboardCsarFilesMap:Dictionary<Dictionary<string>>;
185 let onSuccess = (vsps:Array<ICsarComponent>) => {
186 onboardCsarFilesMap = {};
187 _.each(vsps, (vsp:ICsarComponent)=>{
188 onboardCsarFilesMap[vsp.packageId] = onboardCsarFilesMap[vsp.packageId] || {};
189 onboardCsarFilesMap[vsp.packageId][vsp.version] = vsp.vspName + " (" + vsp.version + ")";
191 this.cacheService.set('onboardCsarFilesMap', onboardCsarFilesMap);
192 return onboardCsarFilesMap;
194 let onError = (): void =>{
195 console.log("Error getting onboarding list");
197 return this.onBoardingService.getOnboardingVSPs().map(onSuccess, onError);
200 private setImportedFileText = ():void => {
202 if(!this.$scope.isShowOnboardingSelectionBrowse) return;
204 //these variables makes it easier to read this logic
205 let csarUUID:string = (<Resource>this.$scope.component).csarUUID;
206 let csarVersion:string = (<Resource>this.$scope.component).csarVersion;
208 let onboardCsarFilesMap:Dictionary<Dictionary<string>> = this.cacheService.get('onboardCsarFilesMap');
209 let assignFileName = ():void => {
210 if(this.$scope.component.vspArchived){
211 this.$scope.importedToscaBrowseFileText = 'VSP is archived';
213 if(this.$stateParams.componentCsar && this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN' && !this.$scope.isCreateMode()) {
214 this.$scope.importedToscaBrowseFileText = this.$scope.originComponent.name + ' (' + (this.$scope.originComponent as Resource).csarVersion + ')';
216 this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[csarUUID][csarVersion];
222 if(this.$scope.component.vspArchived || (onboardCsarFilesMap && onboardCsarFilesMap[csarUUID] && onboardCsarFilesMap[csarUUID][csarVersion])){ //check that the file name is already in cache
225 this.loadOnboardingFileCache().subscribe((onboardingFiles) => {
226 onboardCsarFilesMap = onboardingFiles;
227 this.cacheService.set('onboardCsarFilesMap', onboardingFiles);
234 isCreateModeAvailable(verifyObj:string): boolean {
235 var isCheckout:boolean = ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState;
236 return this.$scope.isCreateMode() || (isCheckout && !verifyObj)
239 private initScope = ():void => {
241 this.$scope.importCsarProgressKey = "importCsarProgressKey";
243 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:';
244 this.$scope.progressService = this.progressService;
245 this.$scope.componentCategories = new componentCategories();
246 this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
250 this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
253 this.$scope.initCategoreis();
255 // Init Environment Context
256 this.$scope.initEnvironmentContext();
259 this.$scope.initModel();
261 // Init the decision if to show file browse.
262 this.$scope.isShowFileBrowse = false;
263 if (this.$scope.component.isResource()) {
264 let resource:Resource = <Resource>this.$scope.component;
265 console.log(resource.name + ": " + resource.csarUUID);
266 if (resource.importedFile) { // Component has imported file.
267 this.$scope.isShowFileBrowse = true;
269 if (resource.resourceType === ResourceType.VF && !resource.csarUUID) {
270 this.$scope.isShowFileBrowse = true;
272 } else if(this.$scope.component.isService()){
273 let service: Service = <Service>this.$scope.component;
274 console.log(service.name + ": " + service.csarUUID);
275 if (service.importedFile) { // Component has imported file.
276 this.$scope.isShowFileBrowse = true;
277 (<Service>this.$scope.component).serviceType = 'Service';
279 if (this.$scope.isEditMode() && service.serviceType == 'Service' && !service.csarUUID) {
280 this.$scope.isShowFileBrowse = true;
282 // Init Instantiation types
283 this.$scope.initInstantiationTypes();
284 this.$scope.initBaseTypes();
287 if (this.cacheService.get(PREVIOUS_CSAR_COMPONENT)) { //keep the old component in the cache until checkout, so we dont need to pass it around
288 this.$scope.setOriginComponent(this.cacheService.get(PREVIOUS_CSAR_COMPONENT));
289 this.cacheService.remove(PREVIOUS_CSAR_COMPONENT);
292 if (this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
293 this.$scope.updateUnsavedFileFlag(true);
297 if (this.$scope.component.isResource() &&
298 (this.$scope.component as Resource).resourceType === ResourceType.VF ||
299 (this.$scope.component as Resource).resourceType === ResourceType.PNF && (this.$scope.component as Resource).csarUUID) {
300 this.$scope.isShowOnboardingSelectionBrowse = true;
301 this.setImportedFileText();
303 this.$scope.isShowOnboardingSelectionBrowse = false;
307 //init file extensions based on the file that was imported.
308 if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
309 let fileName:string = (<Resource>this.$scope.component).importedFile.filename;
310 let fileExtension:string = fileName.split(".").pop();
311 if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
312 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
313 (<Resource>this.$scope.component).importedFile.filetype = "csar";
314 } else if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
315 (<Resource>this.$scope.component).importedFile.filetype = "yaml";
316 this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
318 this.$scope.restoreFile = angular.copy((<Resource>this.$scope.originComponent).importedFile); //create backup
319 } else if (this.$scope.isEditMode() && (<Resource>this.$scope.component).resourceType === ResourceType.VF) {
320 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
321 //(<Resource>this.$scope.component).importedFile.filetype="csar";
326 this.$scope.setValidState(true);
328 this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
329 let uniqueId:string = mainCategory;
331 uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
336 //TODO remove this after handling contact in UI
337 if (this.$scope.isCreateMode()) {
338 this.$scope.component.contactId = this.cacheService.get("user").userId;
339 this.$scope.originComponent.contactId = this.$scope.component.contactId;
343 this.$scope.$on('$destroy', () => {
344 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE);
345 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE);
350 // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
351 private convertCategoryStringToOneArray = ():IMainCategory[] => {
352 let tmp = this.$scope.component.selectedCategory.split("_#_");
353 let mainCategory = tmp[0];
354 let subCategory = tmp[1];
356 // Find the selected category and add the relevant sub category.
357 let selectedMainCategory:IMainCategory = <IMainCategory>_.find(this.$scope.categories, function (item) {
358 return item["name"] === mainCategory;
362 let mainCategoryClone = angular.copy(selectedMainCategory);
364 let selectedSubcategory = <ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
365 return item["name"] === subCategory;
367 mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
369 let tmpSelected = <IMainCategory> mainCategoryClone;
371 let result:IMainCategory[] = [];
372 result.push(tmpSelected);
377 private updateComponentNameInBreadcrumbs = ():void => {
378 // update breadcrum after changing name
379 this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
380 this.$scope.updateMenuComponentName(this.$scope.component.name);
383 //Find if a category is applicable for External API or not
384 private isHiddenCategory = (category: string) => {
385 let items: Array<any> = new Array<any>();
386 items = this.$scope.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()];
387 for(let index = 0; index < items.length; ++index) {
388 if ((items[index].hiddenCategories && items[index].hiddenCategories.indexOf(category) > -1)) {
395 private filteredCategories = () => {
396 let tempCategories: Array<IMainCategory> = new Array<IMainCategory>();
397 this.$scope.categories.forEach((category) => {
398 if (!this.isHiddenCategory(category.name)
399 && this.$scope.isCreateMode()
401 tempCategories.push(category);
402 } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
403 && !this.isHiddenCategory(this.$scope.component.selectedCategory)
404 && !this.isHiddenCategory(category.name)
406 tempCategories.push(category);
407 } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
408 && this.isHiddenCategory(this.$scope.component.selectedCategory)) {
409 tempCategories.push(category);
413 return tempCategories;
416 private initScopeMethods = ():void => {
418 this.$scope.initCategoreis = ():void => {
419 if (this.$scope.componentType === ComponentType.RESOURCE) {
420 this.$scope.categories = this.cacheService.get('resourceCategories');
423 if (this.$scope.componentType === ComponentType.SERVICE) {
424 this.$scope.categories = this.cacheService.get('serviceCategories');
426 //Remove categories from dropdown applicable for External API
427 if (this.$scope.isCreateMode() || (ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)) {
428 this.$scope.categories = this.filteredCategories();
429 //Flag to disbale category if service is created through External API
430 this.$scope.isHiddenCategorySelected = this.isHiddenCategory(this.$scope.component.selectedCategory);
436 this.$scope.initInstantiationTypes = ():void => {
437 if (this.$scope.componentType === ComponentType.SERVICE) {
438 this.$scope.instantiationTypes = new Array();
439 this.$scope.instantiationTypes.push(instantiationType.A_LA_CARTE);
440 this.$scope.instantiationTypes.push(instantiationType.MACRO);
441 var instantiationTypeField:string =(<Service>this.$scope.component).instantiationType;
442 if (instantiationTypeField === ""){
443 this.$scope.instantiationTypes.push("");
445 else if (this.isCreateModeAvailable(instantiationTypeField)) {
446 (<Service>this.$scope.component).instantiationType = instantiationType.A_LA_CARTE;
452 this.$scope.initBaseTypes = ():void => {
453 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component && this.$scope.component.categories) {
454 let modelName = this.$scope.component.model ? this.$scope.component.model : null;
455 this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name, modelName).subscribe((data: BaseTypeResponse[]) => {
456 this.$scope.baseTypes = []
457 this.$scope.baseTypeVersions = []
458 data.forEach(baseType => {
459 this.$scope.baseTypes.push(baseType.toscaResourceName)
460 if (baseType.toscaResourceName === this.$scope.component.derivedFromGenericType){
461 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
467 this.$scope.initModel = ():void => {
468 this.$scope.models = new Array();
469 this.modelService.getModels().subscribe((modelsFound: Model[]) => {
470 modelsFound.forEach(model => {this.$scope.models.push(model.name)});})
471 this.$scope.models.filter(model => model.name === this.$scope.component).model;
474 this.$scope.initEnvironmentContext = ():void => {
475 if (this.$scope.componentType === ComponentType.SERVICE) {
476 this.$scope.environmentContextObj = this.cacheService.get('UIConfiguration').environmentContext;
477 var environmentContext:string =(<Service>this.$scope.component).environmentContext;
478 // In creation new service OR check outing old service without environmentContext parameter - set default value
479 if(this.isCreateModeAvailable(environmentContext)){
480 (<Service>this.$scope.component).environmentContext = this.$scope.environmentContextObj.defaultValue;
485 this.$scope.validateField = (field:any):boolean => {
486 if (field && field.$dirty && field.$invalid) {
492 this.$scope.openOnBoardingModal = ():void => {
493 if(this.$scope.component.vspArchived) return;
494 let csarUUID = (<Resource>this.$scope.component).csarUUID;
495 let csarVersion = (<Resource>this.$scope.component).csarVersion;
496 this.importVSPService.openOnboardingModal(csarUUID, csarVersion).subscribe((result) => {
497 this.ComponentFactory.getComponentWithMetadataFromServer(result.type.toUpperCase(), result.previousComponent.uniqueId).then(
498 (component:Component)=> {
499 if (result.componentCsar && component.isResource()){
500 this.cacheService.set(PREVIOUS_CSAR_COMPONENT, angular.copy(component));
501 component = this.ComponentFactory.updateComponentFromCsar(result.componentCsar, <Resource>component);
503 this.$scope.setComponent(component);
505 this.setImportedFileText();
512 this.$scope.updateIcon = ():void => {
513 this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
514 if(isDirty && !this.$scope.isCreateMode()){
515 this.setUnsavedChanges(true);
522 this.$scope.possibleToUpdateIcon = ():boolean => {
523 if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName) && !this.$scope.component.isAlreadyCertified()){
530 this.$scope.validateName = (isInit:boolean):void => {
531 if (isInit === undefined) {
535 let name = this.$scope.component.name;
536 if (!name || name === "") {
537 if (this.$scope.editForm
538 && this.$scope.editForm["componentName"]
539 && this.$scope.editForm["componentName"].$error) {
541 // Clear the error name already exists
542 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
548 let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
549 if (subtype == "SRVC") {
553 const onFailed = (response) => {
554 // console.info('onFaild', response);
555 // this.$scope.isLoading = false;
558 const onSuccess = (validation:IValidate) => {
559 this.$scope.editForm['componentName'].$setValidity('nameExist', validation.isValid);
560 if (validation.isValid) {
561 // update breadcrumb after changing name
562 this.updateComponentNameInBreadcrumbs();
567 // When page is init after update
568 if (this.$scope.component.name !== this.$scope.originComponent.name) {
569 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
571 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
575 // Validating on change (has debounce)
576 if (this.$scope.editForm
577 && this.$scope.editForm["componentName"]
578 && this.$scope.editForm["componentName"].$error
579 && !this.$scope.editForm["componentName"].$error.pattern
580 && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase())
582 if (!(this.$scope.componentType === ComponentType.RESOURCE && (this.$scope.component as Resource).csarUUID !== undefined)
584 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
586 } else if (this.$scope.editForm && this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
588 this.$scope.editForm['componentName'].$setValidity('nameExist', true);
594 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, (nextState) => {
595 if (this.$state.current.data.unsavedChanges && this.$scope.isValidForm) {
596 this.$scope.save().then(() => {
597 this.$scope.handleChangeLifecycleState(nextState);
599 console.error('Save failed, unable to change lifecycle state to ' + nextState);
601 } else if(!this.$scope.isValidForm){
602 console.error('Form is not valid');
604 let newCsarVersion:string;
605 if(this.$scope.unsavedFile) {
606 newCsarVersion = (this.$scope.component as Resource).csarVersion;
608 if(this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
609 const onError = (): void => {
610 if (this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN') {
611 this.$scope.revert();
614 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion, onError);
617 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion);
622 this.$scope.revert = ():void => {
623 // in state of import file leave the file in place
625 this.$scope.setComponent(this.ComponentFactory.createComponent(this.$scope.originComponent));
627 if (this.$scope.component.isResource() && this.$scope.restoreFile) {
628 (this.$scope.component as Resource).importedFile = angular.copy(this.$scope.restoreFile);
631 this.setImportedFileText();
632 this.$scope.updateBreadcrumbs(this.$scope.component); // update on workspace
634 this.$scope.componentCategories.selectedCategory = this.$scope.originComponent.selectedCategory;
635 this.setUnsavedChanges(false);
636 this.$scope.updateUnsavedFileFlag(false);
637 this.$scope.editForm.$setPristine();
640 this.$scope.onImportFileChange = () => {
642 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
643 this.$scope.restoreFile && !angular.equals(this.$scope.restoreFile, this.$scope.editForm.fileElement.value)){ // or file was swapped for a new one
644 this.$scope.updateUnsavedFileFlag(true);
646 this.$scope.updateUnsavedFileFlag(false);
647 this.$scope.editForm.fileElement.$setPristine();
651 this.$scope.$watchCollection('component.name', (newData: any): void => {
652 this.$scope.validateName(false);
655 // Notify the parent if this step valid or not.
656 this.$scope.$watch('editForm.$valid', (newVal, oldVal) => {
657 this.$scope.setValidState(newVal);
660 this.$scope.$watch('editForm.$dirty', (newVal, oldVal) => {
661 if (newVal && !this.$scope.isCreateMode()) {
662 this.setUnsavedChanges(true);
667 this.$scope.onCategoryChange = (): void => {
668 this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory;
669 this.$scope.component.categories = this.convertCategoryStringToOneArray();
670 this.$scope.component.icon = DEFAULT_ICON;
671 if (this.$scope.component.categories[0].metadataKeys) {
672 for (let metadataKey of this.$scope.component.categories[0].metadataKeys) {
673 if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
674 this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
678 if (this.$scope.component.categories[0].subcategories && this.$scope.component.categories[0].subcategories[0].metadataKeys) {
679 for (let metadataKey of this.$scope.component.categories[0].subcategories[0].metadataKeys) {
680 if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
681 this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
685 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component.categories[0]) {
686 let modelName : string = this.$scope.component.model ? this.$scope.component.model : null;
687 this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name, modelName).subscribe((data: BaseTypeResponse[]) => {
689 if(this.$scope.isCreateMode()){
690 this.$scope.baseTypes = []
691 this.$scope.baseTypeVersions = []
692 data.forEach(baseType => this.$scope.baseTypes.push(baseType.toscaResourceName));
693 data[0].versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
694 this.$scope.component.derivedFromGenericType = data[0].toscaResourceName;
695 this.$scope.component.derivedFromGenericVersion = data[0].versions[0];
697 var isValidForBaseType:boolean = false;
698 data.forEach(baseType => {if (!this.$scope.component.derivedFromGenericType || baseType.toscaResourceName === this.$scope.component.derivedFromGenericType){
699 isValidForBaseType = true;
701 this.$scope.editForm['category'].$setValidity('validForBaseType', isValidForBaseType);
707 this.$scope.onEcompGeneratedNamingChange = (): void => {
708 if (!(this.$scope.component as Service).ecompGeneratedNaming) {
709 (this.$scope.component as Service).namingPolicy = '';
713 this.$scope.onBaseTypeChange = (): void => {
714 let modelName : string = this.$scope.component.model ? this.$scope.component.model : null;
715 this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name, modelName).subscribe((data: BaseTypeResponse[]) => {
716 this.$scope.baseTypeVersions = []
717 data.forEach(baseType => {
718 if(baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) {
719 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
720 this.$scope.component.derivedFromGenericVersion = baseType.versions[0];
726 this.$scope.onModelChange = (): void => {
727 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component && this.$scope.component.categories) {
728 let modelName = this.$scope.component.model ? this.$scope.component.model : null;
729 this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name, modelName).subscribe((data: BaseTypeResponse[]) => {
730 this.$scope.baseTypes = []
731 this.$scope.baseTypeVersions = []
732 data.forEach(baseType => this.$scope.baseTypes.push(baseType.toscaResourceName));
733 data[0].versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
734 this.$scope.component.derivedFromGenericType = data[0].toscaResourceName;
735 this.$scope.component.derivedFromGenericVersion = data[0].versions[0];
740 this.$scope.onVendorNameChange = (oldVendorName: string): void => {
741 if (this.$scope.component.icon === oldVendorName) {
742 this.$scope.component.icon = DEFAULT_ICON;
745 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload);
748 this.$scope.isMetadataKeyMandatory = (key: string): boolean => {
749 let metadataKey = this.getMetadataKey(this.$scope.component.categories, key);
750 return metadataKey && metadataKey.mandatory;
753 this.$scope.getMetadataKeyValidValues = (key: string): string[] => {
754 let metadataKey = this.getMetadataKey(this.$scope.component.categories, key);
756 return metadataKey.validValues;
761 this.$scope.isMetadataKeyForComponentCategory = (key: string): boolean => {
762 return this.getMetadataKey(this.$scope.component.categories, key) != null;
765 this.$scope.isCategoryServiceMetadataKey = (key: string): boolean => {
766 return this.isServiceMetadataKey(key);
769 this.$scope.isMetadataKeyForComponentCategoryService = (key: string, attribute: string): boolean => {
770 let metadatakey = this.getMetadataKey(this.$scope.component.categories, key);
771 if (metadatakey && (!this.$scope.component[attribute] || !metadatakey.validValues.find(v => v === this.$scope.component[attribute]))) {
772 this.$scope.component[attribute] = metadatakey.defaultValue;
774 return metadatakey != null;
778 private setUnsavedChanges = (hasChanges: boolean): void => {
779 this.$state.current.data.unsavedChanges = hasChanges;
782 private getMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
783 let metadataKey = this.getSubcategoryMetadataKey(this.$scope.component.categories, key);
785 return this.getCategoryMetadataKey(this.$scope.component.categories, key);
790 private getSubcategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
791 if (categories[0].subcategories && categories[0].subcategories[0].metadataKeys && categories[0].subcategories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
792 return categories[0].subcategories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
797 private getCategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
798 if (categories[0].metadataKeys && categories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
799 return categories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
804 private isServiceMetadataKey(key: string) : boolean {
805 return CATEGORY_SERVICE_METADATA_KEYS.indexOf(key) > -1;