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, DEFAULT_MODEL_NAME} 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;
84 isModelRequired: boolean;
88 onImportFileChange():void;
89 validateField(field:any):boolean;
90 validateName(isInit:boolean):void;
91 calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
92 onVendorNameChange(oldVendorName:string):void;
93 convertCategoryStringToOneArray(category:string, subcategory:string):Array<IMainCategory>;
94 onCategoryChange():void;
95 onEcompGeneratedNamingChange():void;
97 onBaseTypeChange():void;
98 openOnBoardingModal():void;
99 initCategories():void;
100 initEnvironmentContext():void;
101 initInstantiationTypes():void;
102 initBaseTypes():void;
103 onInstantiationTypeChange():void;
105 possibleToUpdateIcon():boolean;
107 isVspImport(): boolean;
110 // tslint:disable-next-line:max-classes-per-file
111 export class GeneralViewModel {
115 'Sdc.Services.CacheService',
116 'ComponentNameValidationPattern',
117 'ContactIdValidationPattern',
118 'TagValidationPattern',
119 'VendorReleaseValidationPattern',
120 'VendorNameValidationPattern',
121 'VendorModelNumberValidationPattern',
122 'CommentValidationPattern',
127 'EventListenerService',
129 'Sdc.Services.ProgressService',
141 constructor(private $scope:IGeneralScope,
142 private cacheService:CacheService,
143 private ComponentNameValidationPattern:RegExp,
144 private ContactIdValidationPattern:RegExp,
145 private TagValidationPattern:RegExp,
146 private VendorReleaseValidationPattern:RegExp,
147 private VendorNameValidationPattern:RegExp,
148 private VendorModelNumberValidationPattern:RegExp,
149 private CommentValidationPattern:RegExp,
150 private ValidationUtils:ValidationUtils,
151 private sdcConfig:IAppConfigurtaion,
152 private $state:ng.ui.IStateService,
153 private ModalsHandler:ModalsHandler,
154 private EventListenerService:EventListenerService,
155 private Notification:any,
156 private progressService:ProgressService,
157 protected $interval:any,
158 private $filter:ng.IFilterService,
159 private $timeout:ng.ITimeoutService,
160 private onBoardingService: OnboardingService,
161 private ComponentFactory:ComponentFactory,
162 private importVSPService: ImportVSPService,
163 private elementService: ElementService,
164 private modelService: ModelService,
165 private $stateParams: any) {
167 this.initScopeValidation();
168 this.initScopeMethods();
175 private initScopeValidation = ():void => {
176 this.$scope.validation = new Validation();
177 this.$scope.validation.componentNameValidationPattern = this.ComponentNameValidationPattern;
178 this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
179 this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
180 this.$scope.validation.VendorReleaseValidationPattern = this.VendorReleaseValidationPattern;
181 this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern;
182 this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern;
183 this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
186 private loadOnboardingFileCache = (): Observable<Dictionary<Dictionary<string>>> => {
187 let onboardCsarFilesMap:Dictionary<Dictionary<string>>;
188 let onSuccess = (vsps:Array<ICsarComponent>) => {
189 onboardCsarFilesMap = {};
190 _.each(vsps, (vsp:ICsarComponent)=>{
191 onboardCsarFilesMap[vsp.packageId] = onboardCsarFilesMap[vsp.packageId] || {};
192 onboardCsarFilesMap[vsp.packageId][vsp.version] = vsp.vspName + " (" + vsp.version + ")";
194 this.cacheService.set('onboardCsarFilesMap', onboardCsarFilesMap);
195 return onboardCsarFilesMap;
197 let onError = (): void =>{
198 console.log("Error getting onboarding list");
200 return this.onBoardingService.getOnboardingVSPs().map(onSuccess, onError);
203 private setImportedFileText = ():void => {
205 if(!this.$scope.isShowOnboardingSelectionBrowse) return;
207 //these variables makes it easier to read this logic
208 let csarUUID:string = (<Resource>this.$scope.component).csarUUID;
209 let csarVersion:string = (<Resource>this.$scope.component).csarVersion;
211 let onboardCsarFilesMap:Dictionary<Dictionary<string>> = this.cacheService.get('onboardCsarFilesMap');
212 let assignFileName = ():void => {
213 if(this.$scope.component.vspArchived){
214 this.$scope.importedToscaBrowseFileText = 'VSP is archived';
216 if(this.$stateParams.componentCsar && this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN' && !this.$scope.isCreateMode()) {
217 this.$scope.importedToscaBrowseFileText = this.$scope.originComponent.name + ' (' + (this.$scope.originComponent as Resource).csarVersion + ')';
219 if (onboardCsarFilesMap && onboardCsarFilesMap[csarUUID]) {
220 this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[csarUUID][csarVersion];
227 if(this.$scope.component.vspArchived || (onboardCsarFilesMap && onboardCsarFilesMap[csarUUID] && onboardCsarFilesMap[csarUUID][csarVersion])){ //check that the file name is already in cache
230 this.loadOnboardingFileCache().subscribe((onboardingFiles) => {
231 onboardCsarFilesMap = onboardingFiles;
232 this.cacheService.set('onboardCsarFilesMap', onboardingFiles);
239 isCreateModeAvailable(verifyObj:string): boolean {
240 var isCheckout:boolean = ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState;
241 return this.$scope.isCreateMode() || (isCheckout && !verifyObj)
244 private initScope = ():void => {
246 this.$scope.importCsarProgressKey = "importCsarProgressKey";
248 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:';
249 this.$scope.progressService = this.progressService;
250 this.$scope.componentCategories = new componentCategories();
251 this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
254 this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
257 this.$scope.initCategories();
259 // Init Environment Context
260 this.$scope.initEnvironmentContext();
263 this.$scope.initModel();
265 // Init the decision if to show file browse.
266 this.$scope.isShowFileBrowse = false;
267 if (this.$scope.component.isResource()) {
268 let resource:Resource = <Resource>this.$scope.component;
269 console.log(resource.name + ": " + resource.csarUUID);
270 if (resource.importedFile) { // Component has imported file.
271 this.$scope.isShowFileBrowse = true;
273 if (resource.resourceType === ResourceType.VF && !resource.csarUUID) {
274 this.$scope.isShowFileBrowse = true;
276 } else if(this.$scope.component.isService()){
277 let service: Service = <Service>this.$scope.component;
278 console.log(service.name + ": " + service.csarUUID);
279 if (service.importedFile) { // Component has imported file.
280 this.$scope.isShowFileBrowse = true;
281 (<Service>this.$scope.component).serviceType = 'Service';
283 if (this.$scope.isEditMode() && service.serviceType == 'Service' && !service.csarUUID) {
284 this.$scope.isShowFileBrowse = true;
286 // Init Instantiation types
287 this.$scope.initInstantiationTypes();
288 this.$scope.initBaseTypes();
291 if (this.cacheService.get(PREVIOUS_CSAR_COMPONENT)) { //keep the old component in the cache until checkout, so we dont need to pass it around
292 this.$scope.setOriginComponent(this.cacheService.get(PREVIOUS_CSAR_COMPONENT));
293 this.cacheService.remove(PREVIOUS_CSAR_COMPONENT);
296 if (this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
297 this.$scope.updateUnsavedFileFlag(true);
301 if (this.$scope.component.isResource() &&
302 (this.$scope.component as Resource).resourceType === ResourceType.VF ||
303 (this.$scope.component as Resource).resourceType === ResourceType.PNF && (this.$scope.component as Resource).csarUUID) {
304 this.$scope.isShowOnboardingSelectionBrowse = true;
305 this.setImportedFileText();
307 this.$scope.isShowOnboardingSelectionBrowse = false;
311 //init file extensions based on the file that was imported.
312 if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
313 let fileName:string = (<Resource>this.$scope.component).importedFile.filename;
314 let fileExtension:string = fileName.split(".").pop();
315 if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
316 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
317 (<Resource>this.$scope.component).importedFile.filetype = "csar";
318 } else if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
319 (<Resource>this.$scope.component).importedFile.filetype = "yaml";
320 this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
322 this.$scope.restoreFile = angular.copy((<Resource>this.$scope.originComponent).importedFile); //create backup
323 } else if (this.$scope.isEditMode() && (<Resource>this.$scope.component).resourceType === ResourceType.VF) {
324 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
325 //(<Resource>this.$scope.component).importedFile.filetype="csar";
330 this.$scope.setValidState(true);
332 this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
333 let uniqueId:string = mainCategory;
335 uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
340 //TODO remove this after handling contact in UI
341 if (this.$scope.isCreateMode()) {
342 this.$scope.component.contactId = this.cacheService.get("user").userId;
343 this.$scope.originComponent.contactId = this.$scope.component.contactId;
347 this.$scope.$on('$destroy', () => {
348 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE);
349 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE);
354 // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
355 private convertCategoryStringToOneArray = ():IMainCategory[] => {
356 let tmp = this.$scope.component.selectedCategory.split("_#_");
357 let mainCategory = tmp[0];
358 let subCategory = tmp[1];
360 // Find the selected category and add the relevant sub category.
361 let selectedMainCategory:IMainCategory = <IMainCategory>_.find(this.$scope.categories, function (item) {
362 return item["name"] === mainCategory;
366 let mainCategoryClone = angular.copy(selectedMainCategory);
368 let selectedSubcategory = <ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
369 return item["name"] === subCategory;
371 mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
373 let tmpSelected = <IMainCategory> mainCategoryClone;
375 let result:IMainCategory[] = [];
376 result.push(tmpSelected);
381 private updateComponentNameInBreadcrumbs = ():void => {
382 // update breadcrum after changing name
383 this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
384 this.$scope.updateMenuComponentName(this.$scope.component.name);
387 //Find if a category is applicable for External API or not
388 private isHiddenCategory = (category: string) => {
389 let items: Array<any> = new Array<any>();
390 items = this.$scope.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()];
391 for(let index = 0; index < items.length; ++index) {
392 if ((items[index].hiddenCategories && items[index].hiddenCategories.indexOf(category) > -1)) {
399 private filteredCategories = () => {
400 let tempCategories: Array<IMainCategory> = new Array<IMainCategory>();
401 this.$scope.categories.forEach((category) => {
402 if (!this.isHiddenCategory(category.name)
403 && this.$scope.isCreateMode()
405 tempCategories.push(category);
406 } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
407 && !this.isHiddenCategory(this.$scope.component.selectedCategory)
408 && !this.isHiddenCategory(category.name)
410 tempCategories.push(category);
411 } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
412 && this.isHiddenCategory(this.$scope.component.selectedCategory)) {
413 tempCategories.push(category);
417 return tempCategories;
420 private initScopeMethods = ():void => {
422 this.$scope.initCategories = ():void => {
423 if (this.$scope.componentType === ComponentType.RESOURCE) {
424 this.$scope.categories = this.cacheService.get('resourceCategories');
427 if (this.$scope.componentType === ComponentType.SERVICE) {
428 this.$scope.categories = this.cacheService.get('serviceCategories');
430 //Remove categories from dropdown applicable for External API
431 if (this.$scope.isCreateMode() || (ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)) {
432 this.$scope.categories = this.filteredCategories();
433 //Flag to disbale category if service is created through External API
434 this.$scope.isHiddenCategorySelected = this.isHiddenCategory(this.$scope.component.selectedCategory);
440 this.$scope.initInstantiationTypes = ():void => {
441 if (this.$scope.componentType === ComponentType.SERVICE) {
442 this.$scope.instantiationTypes = new Array();
443 this.$scope.instantiationTypes.push(instantiationType.A_LA_CARTE);
444 this.$scope.instantiationTypes.push(instantiationType.MACRO);
445 var instantiationTypeField:string =(<Service>this.$scope.component).instantiationType;
446 if (instantiationTypeField === ""){
447 this.$scope.instantiationTypes.push("");
449 else if (this.isCreateModeAvailable(instantiationTypeField)) {
450 (<Service>this.$scope.component).instantiationType = instantiationType.A_LA_CARTE;
456 this.$scope.initBaseTypes = ():void => {
457 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component && this.$scope.component.categories) {
458 if (!this.$scope.component.derivedFromGenericType) {
459 this.$scope.component.derivedFromGenericVersion = undefined;
460 this.$scope.showBaseTypeVersions = false;
463 let modelName = this.$scope.component.model ? this.$scope.component.model : null;
464 const categoryName = this.$scope.component.categories[0].name;
465 this.elementService.getCategoryBaseTypes(categoryName, modelName).subscribe((data: ListBaseTypesResponse) => {
466 this.$scope.baseTypes = []
467 this.$scope.baseTypeVersions = []
468 this.$scope.isBaseTypeRequired = data.required;
469 data.baseTypes.forEach(baseType => {
470 this.$scope.baseTypes.push(baseType.toscaResourceName);
471 if (baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) {
472 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
475 this.$scope.showBaseTypeVersions = true;
480 this.$scope.initModel = ():void => {
481 this.$scope.isModelRequired = false;
482 this.$scope.models = [];
483 this.$scope.defaultModelOption = DEFAULT_MODEL_NAME;
484 this.$scope.showDefaultModelOption = true;
485 if (this.$scope.componentType === ComponentType.SERVICE) {
486 this.filterCategoriesByModel(this.$scope.component.model);
488 if (this.$scope.isCreateMode() && this.$scope.isVspImport()) {
489 if (this.$scope.component.componentMetadata.models) {
490 this.$scope.isModelRequired = true;
491 const modelOptions = this.$scope.component.componentMetadata.models;
492 if (modelOptions.length == 1) {
493 this.$scope.models = modelOptions;
494 this.$scope.component.model = modelOptions[0];
495 this.$scope.showDefaultModelOption = false;
497 this.$scope.models = modelOptions.sort();
498 this.$scope.defaultModelOption = 'Select';
504 if (!this.$scope.isCreateMode() && this.$scope.isVspImport()){
505 this.modelService.getModels().subscribe((modelsFound: Model[]) => {
506 modelsFound.sort().forEach(model => {
507 if (this.$scope.component.model != undefined) {
508 if (model.modelType == "NORMATIVE_EXTENSION") {
509 this.$scope.component.model = model.derivedFrom;
510 this.$scope.models.push(model.derivedFrom)
512 this.$scope.component.model = model.name;
513 this.$scope.models.push(model.name)
519 this.modelService.getModelsOfType("normative").subscribe((modelsFound: Model[]) => {
520 modelsFound.sort().forEach(model => {this.$scope.models.push(model.name)});
525 this.$scope.isVspImport = (): boolean => {
526 if (!this.$scope.component || !this.$scope.component.isResource()) {
530 const resource = <Resource>this.$scope.component;
531 return resource.isCsarComponent();
534 this.$scope.initEnvironmentContext = ():void => {
535 if (this.$scope.componentType === ComponentType.SERVICE) {
536 this.$scope.environmentContextObj = this.cacheService.get('UIConfiguration').environmentContext;
537 var environmentContext:string =(<Service>this.$scope.component).environmentContext;
538 // In creation new service OR check outing old service without environmentContext parameter - set default value
539 if(this.isCreateModeAvailable(environmentContext)){
540 (<Service>this.$scope.component).environmentContext = this.$scope.environmentContextObj.defaultValue;
545 this.$scope.validateField = (field:any):boolean => {
546 if (field && field.$dirty && field.$invalid) {
552 this.$scope.openOnBoardingModal = ():void => {
553 if(this.$scope.component.vspArchived) return;
554 let csarUUID = (<Resource>this.$scope.component).csarUUID;
555 let csarVersion = (<Resource>this.$scope.component).csarVersion;
556 this.importVSPService.openOnboardingModal(csarUUID, csarVersion).subscribe((result) => {
557 this.ComponentFactory.getComponentWithMetadataFromServer(result.type.toUpperCase(), result.previousComponent.uniqueId).then(
558 (component:Component)=> {
559 if (result.componentCsar && component.isResource()){
560 this.cacheService.set(PREVIOUS_CSAR_COMPONENT, angular.copy(component));
561 component = this.ComponentFactory.updateComponentFromCsar(result.componentCsar, <Resource>component);
563 this.$scope.setComponent(component);
565 this.setImportedFileText();
572 this.$scope.updateIcon = ():void => {
573 this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
574 if(isDirty && !this.$scope.isCreateMode()){
575 this.setUnsavedChanges(true);
582 this.$scope.possibleToUpdateIcon = ():boolean => {
583 if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName) && !this.$scope.component.isAlreadyCertified()){
590 this.$scope.validateName = (isInit:boolean):void => {
591 if (isInit === undefined) {
595 let name = this.$scope.component.name;
596 if (!name || name === "") {
597 if (this.$scope.editForm
598 && this.$scope.editForm["componentName"]
599 && this.$scope.editForm["componentName"].$error) {
601 // Clear the error name already exists
602 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
608 let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
609 if (subtype == "SRVC") {
613 const onFailed = (response) => {
614 // console.info('onFaild', response);
615 // this.$scope.isLoading = false;
618 const onSuccess = (validation:IValidate) => {
619 this.$scope.editForm['componentName'].$setValidity('nameExist', validation.isValid);
620 if (validation.isValid) {
621 // update breadcrumb after changing name
622 this.updateComponentNameInBreadcrumbs();
627 // When page is init after update
628 if (this.$scope.component.name !== this.$scope.originComponent.name) {
629 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
631 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
635 // Validating on change (has debounce)
636 if (this.$scope.editForm
637 && this.$scope.editForm["componentName"]
638 && this.$scope.editForm["componentName"].$error
639 && !this.$scope.editForm["componentName"].$error.pattern
640 && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase())
642 if (!(this.$scope.componentType === ComponentType.RESOURCE && (this.$scope.component as Resource).csarUUID !== undefined)
644 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
646 } else if (this.$scope.editForm && this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
648 this.$scope.editForm['componentName'].$setValidity('nameExist', true);
654 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, (nextState) => {
655 if (this.$state.current.data.unsavedChanges && this.$scope.isValidForm) {
656 this.$scope.save().then(() => {
657 this.$scope.handleChangeLifecycleState(nextState);
659 console.error('Save failed, unable to change lifecycle state to ' + nextState);
661 } else if(!this.$scope.isValidForm){
662 console.error('Form is not valid');
664 let newCsarVersion:string;
665 if(this.$scope.unsavedFile) {
666 newCsarVersion = (this.$scope.component as Resource).csarVersion;
668 if(this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
669 const onError = (): void => {
670 if (this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN') {
671 this.$scope.revert();
674 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion, onError);
677 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion);
682 this.$scope.revert = ():void => {
683 // in state of import file leave the file in place
685 this.$scope.setComponent(this.ComponentFactory.createComponent(this.$scope.originComponent));
687 if (this.$scope.component.isResource() && this.$scope.restoreFile) {
688 (this.$scope.component as Resource).importedFile = angular.copy(this.$scope.restoreFile);
691 this.setImportedFileText();
692 this.$scope.updateBreadcrumbs(this.$scope.component); // update on workspace
694 this.$scope.componentCategories.selectedCategory = this.$scope.originComponent.selectedCategory;
695 this.setUnsavedChanges(false);
696 this.$scope.updateUnsavedFileFlag(false);
697 this.$scope.editForm.$setPristine();
700 this.$scope.onImportFileChange = () => {
702 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
703 this.$scope.restoreFile && !angular.equals(this.$scope.restoreFile, this.$scope.editForm.fileElement.value)){ // or file was swapped for a new one
704 this.$scope.updateUnsavedFileFlag(true);
706 this.$scope.updateUnsavedFileFlag(false);
707 this.$scope.editForm.fileElement.$setPristine();
711 this.$scope.$watchCollection('component.name', (newData: any): void => {
712 this.$scope.validateName(false);
715 // Notify the parent if this step valid or not.
716 this.$scope.$watch('editForm.$valid', (newVal, oldVal) => {
717 this.$scope.setValidState(newVal);
720 this.$scope.$watch('editForm.$dirty', (newVal, oldVal) => {
721 if (newVal && !this.$scope.isCreateMode()) {
722 this.setUnsavedChanges(true);
727 this.$scope.onCategoryChange = (): void => {
728 this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory;
729 if (this.$scope.component.selectedCategory) {
730 this.$scope.component.categories = this.convertCategoryStringToOneArray();
731 this.$scope.component.icon = DEFAULT_ICON;
732 if (this.$scope.component.categories[0].metadataKeys) {
733 for (let metadataKey of this.$scope.component.categories[0].metadataKeys) {
734 if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
735 this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
739 if (this.$scope.component.categories[0].subcategories && this.$scope.component.categories[0].subcategories[0].metadataKeys) {
740 for (let metadataKey of this.$scope.component.categories[0].subcategories[0].metadataKeys) {
741 if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
742 this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
746 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component.categories[0]) {
747 const modelName : string = this.$scope.component.model ? this.$scope.component.model : null;
748 this.elementService.getCategoryBaseTypes(this.$scope.component.categories[0].name, modelName)
749 .subscribe((data: ListBaseTypesResponse) => {
750 if (this.$scope.isCreateMode()) {
751 this.loadBaseTypes(data);
753 let isValidForBaseType:boolean = data.baseTypes.some(baseType => {
754 return !this.$scope.component.derivedFromGenericType ||
755 baseType.toscaResourceName === this.$scope.component.derivedFromGenericType;
757 this.$scope.editForm['category'].$setValidity('validForBaseType', isValidForBaseType);
762 this.clearBaseTypes();
766 this.$scope.onEcompGeneratedNamingChange = (): void => {
767 if (!(this.$scope.component as Service).ecompGeneratedNaming) {
768 (this.$scope.component as Service).namingPolicy = '';
772 this.$scope.getCategoryDisplayNameOrName = (mainCategory: any): string => {
773 return mainCategory.displayName ? mainCategory.displayName : mainCategory.name ;
776 this.$scope.onBaseTypeChange = (): void => {
777 if (!this.$scope.component.derivedFromGenericType) {
778 this.$scope.component.derivedFromGenericVersion = undefined;
779 this.$scope.showBaseTypeVersions = false;
783 const modelName : string = this.$scope.component.model ? this.$scope.component.model : null;
784 const categoryName = this.$scope.component.categories[0].name;
785 this.elementService.getCategoryBaseTypes(categoryName, modelName).subscribe((baseTypeResponseList: ListBaseTypesResponse) => {
786 this.$scope.baseTypeVersions = []
787 baseTypeResponseList.baseTypes.forEach(baseType => {
788 if (baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) {
789 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
790 this.$scope.component.derivedFromGenericVersion = baseType.versions[0];
793 this.$scope.showBaseTypeVersions = true;
797 this.$scope.onModelChange = (): void => {
798 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component && this.$scope.categories) {
799 let modelName = this.$scope.component.model ? this.$scope.component.model : null;
800 this.$scope.component.categories = undefined;
801 this.$scope.component.selectedCategory = undefined;
802 this.$scope.componentCategories.selectedCategory = undefined;
803 this.filterCategoriesByModel(modelName);
804 this.filterBaseTypesByModelAndCategory(modelName)
808 this.$scope.onVendorNameChange = (oldVendorName: string): void => {
809 if (this.$scope.component.icon === oldVendorName) {
810 this.$scope.component.icon = DEFAULT_ICON;
814 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload);
816 this.$scope.isMetadataKeyMandatory = (key: string): boolean => {
817 let metadataKey = this.getMetadataKey(key);
818 return metadataKey && metadataKey.mandatory;
821 this.$scope.getMetadataKeyValidValues = (key: string): string[] => {
822 let metadataKey = this.getMetadataKey(key);
824 return metadataKey.validValues;
829 this.$scope.getMetadataDisplayName = (key: string): string => {
830 let metadataKey = this.getMetadataKey(key);
832 return metadataKey.displayName ? metadataKey.displayName : metadataKey.name;
837 this.$scope.isMetadataKeyForComponentCategory = (key: string): boolean => {
838 return this.getMetadataKey(key) != null;
841 this.$scope.isCategoryServiceMetadataKey = (key: string): boolean => {
842 return this.isServiceMetadataKey(key);
845 this.$scope.isMetadataKeyForComponentCategoryService = (key: string, attribute: string): boolean => {
846 let metadatakey = this.getMetadataKey(key);
847 if (metadatakey && (!this.$scope.component[attribute] || !metadatakey.validValues.find(v => v === this.$scope.component[attribute]))) {
848 this.$scope.component[attribute] = metadatakey.defaultValue;
850 return metadatakey != null;
854 private filterCategoriesByModel(modelName:string) {
856 this.$scope.initCategories();
857 this.$scope.categories = this.$scope.categories.filter(category =>
858 !modelName ? category.models.indexOf(DEFAULT_MODEL_NAME) !== -1 : category.models !== null && category.models.indexOf(modelName) !== -1);
862 private filterBaseTypesByModelAndCategory(modelName:string) {
863 let categories = this.$scope.component.categories;
865 this.elementService.getCategoryBaseTypes(categories[0].name, modelName).subscribe((data: ListBaseTypesResponse) => {
866 this.loadBaseTypes(data);
870 this.clearBaseTypes();
873 private loadBaseTypes(baseTypeResponseList: ListBaseTypesResponse) {
874 this.$scope.isBaseTypeRequired = baseTypeResponseList.required;
875 this.$scope.baseTypes = [];
876 this.$scope.baseTypeVersions = [];
877 baseTypeResponseList.baseTypes.forEach(baseType => this.$scope.baseTypes.push(baseType.toscaResourceName));
878 if (this.$scope.isBaseTypeRequired) {
879 const baseType = baseTypeResponseList.baseTypes[0];
880 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
881 this.$scope.component.derivedFromGenericType = baseType.toscaResourceName;
882 this.$scope.component.derivedFromGenericVersion = this.$scope.baseTypeVersions[0];
883 this.$scope.showBaseTypeVersions = true;
886 this.$scope.component.derivedFromGenericType = undefined;
887 this.$scope.component.derivedFromGenericVersion = undefined;
888 this.$scope.showBaseTypeVersions = false;
891 private clearBaseTypes() {
892 this.$scope.isBaseTypeRequired = false;
893 this.$scope.baseTypes = [];
894 this.$scope.baseTypeVersions = [];
895 this.$scope.component.derivedFromGenericType = undefined;
896 this.$scope.component.derivedFromGenericVersion = undefined;
897 this.$scope.showBaseTypeVersions = false;
900 private setUnsavedChanges = (hasChanges: boolean): void => {
901 this.$state.current.data.unsavedChanges = hasChanges;
904 private getMetadataKey(key: string) : IMetadataKey {
905 if (this.$scope.component.categories) {
906 let metadataKey = this.getSubcategoryMetadataKey(this.$scope.component.categories, key);
908 return this.getCategoryMetadataKey(this.$scope.component.categories, key);
915 private getSubcategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
916 if (categories[0].subcategories && categories[0].subcategories[0].metadataKeys && categories[0].subcategories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
917 return categories[0].subcategories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
922 private getCategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
923 if (categories[0].metadataKeys && categories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
924 return categories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
929 private isServiceMetadataKey(key: string) : boolean {
930 return CATEGORY_SERVICE_METADATA_KEYS.indexOf(key) > -1;