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";
37 import {EventListenerService, ProgressService} from "app/services";
38 import {CacheService, ElementService, ModelService, ImportVSPService, OnboardingService} from "app/services-ng2";
39 import {Component, IAppConfigurtaion, ICsarComponent, IMainCategory, IMetadataKey, ISubCategory, IValidate, Resource, Service} from "app/models";
40 import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
41 import {CATEGORY_SERVICE_METADATA_KEYS, PREVIOUS_CSAR_COMPONENT, DEFAULT_MODEL_NAME} from "../../../../utils/constants";
42 import {Observable} from "rxjs";
43 import {Model} from "../../../../models/model";
44 import {SdcUiServices} from "onap-ui-angular/dist";
46 export class Validation {
47 componentNameValidationPattern:RegExp;
48 contactIdValidationPattern:RegExp;
49 tagValidationPattern:RegExp;
50 VendorReleaseValidationPattern:RegExp;
51 VendorNameValidationPattern:RegExp;
52 VendorModelNumberValidationPattern:RegExp;
53 commentValidationPattern:RegExp;
56 export class componentCategories {//categories field bind to this obj in order to solve this bug: DE242059
57 selectedCategory:string;
60 export class componentModel {
64 export interface IEnvironmentContext {
66 validValues:Array<string>;
69 export interface IGeneralScope extends IWorkspaceViewModelScope {
70 validation:Validation;
71 editForm:ng.IFormController;
72 categories:Array<IMainCategory>;
73 environmentContextObj:IEnvironmentContext;
74 latestCategoryId:string;
75 latestVendorName:string;
76 importedFileExtension:any;
78 isShowFileBrowse:boolean;
79 isShowOnboardingSelectionBrowse:boolean;
80 importedToscaBrowseFileText:string;
81 importCsarProProgressKey:string;
82 browseFileLabel:string;
83 componentCategories:componentCategories;
84 componentModel:componentModel;
85 instantiationTypes:Array<instantiationType>;
86 isHiddenCategorySelected: boolean;
87 isModelRequired: boolean;
91 onImportFileChange():void;
92 validateField(field:any):boolean;
93 validateName(isInit:boolean):void;
94 calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
95 onVendorNameChange(oldVendorName:string):void;
96 convertCategoryStringToOneArray(category:string, subcategory:string):Array<IMainCategory>;
97 onCategoryChange():void;
98 onEcompGeneratedNamingChange():void;
100 onBaseTypeChange():void;
101 openOnBoardingModal():void;
102 initCategories():void;
103 initEnvironmentContext():void;
104 initInstantiationTypes():void;
105 initBaseTypes():void;
106 onInstantiationTypeChange():void;
108 possibleToUpdateIcon():boolean;
110 isVspImport(): boolean;
113 // tslint:disable-next-line:max-classes-per-file
114 export class GeneralViewModel {
118 'Sdc.Services.CacheService',
119 'ComponentNameValidationPattern',
120 'ContactIdValidationPattern',
121 'TagValidationPattern',
122 'VendorReleaseValidationPattern',
123 'VendorNameValidationPattern',
124 'VendorModelNumberValidationPattern',
125 'CommentValidationPattern',
132 'EventListenerService',
134 'Sdc.Services.ProgressService',
146 constructor(private $scope:IGeneralScope,
147 private cacheService:CacheService,
148 private ComponentNameValidationPattern:RegExp,
149 private ContactIdValidationPattern:RegExp,
150 private TagValidationPattern:RegExp,
151 private VendorReleaseValidationPattern:RegExp,
152 private VendorNameValidationPattern:RegExp,
153 private VendorModelNumberValidationPattern:RegExp,
154 private CommentValidationPattern:RegExp,
155 private ValidationUtils:ValidationUtils,
156 private FileUtils: FileUtils,
157 private sdcConfig:IAppConfigurtaion,
158 private $state:ng.ui.IStateService,
159 private ModalsHandler:ModalsHandler,
160 private modalServiceSdcUI: SdcUiServices.ModalService,
161 private EventListenerService:EventListenerService,
162 private Notification:any,
163 private progressService:ProgressService,
164 protected $interval:any,
165 private $filter:ng.IFilterService,
166 private $timeout:ng.ITimeoutService,
167 private onBoardingService: OnboardingService,
168 private ComponentFactory:ComponentFactory,
169 private importVSPService: ImportVSPService,
170 private elementService: ElementService,
171 private modelService: ModelService,
172 private $stateParams: any) {
174 this.initScopeValidation();
175 this.initScopeMethods();
179 private initScopeValidation = ():void => {
180 this.$scope.validation = new Validation();
181 this.$scope.validation.componentNameValidationPattern = this.ComponentNameValidationPattern;
182 this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
183 this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
184 this.$scope.validation.VendorReleaseValidationPattern = this.VendorReleaseValidationPattern;
185 this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern;
186 this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern;
187 this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
190 private loadOnboardingFileCache = (): Observable<Dictionary<Dictionary<string>>> => {
191 let onboardCsarFilesMap:Dictionary<Dictionary<string>>;
192 let onSuccess = (vsps:Array<ICsarComponent>) => {
193 onboardCsarFilesMap = {};
194 _.each(vsps, (vsp:ICsarComponent)=>{
195 onboardCsarFilesMap[vsp.packageId] = onboardCsarFilesMap[vsp.packageId] || {};
196 onboardCsarFilesMap[vsp.packageId][vsp.version] = vsp.vspName + " (" + vsp.version + ")";
198 this.cacheService.set('onboardCsarFilesMap', onboardCsarFilesMap);
199 return onboardCsarFilesMap;
201 let onError = (): void =>{
202 console.log("Error getting onboarding list");
204 return this.onBoardingService.getOnboardingVSPs().map(onSuccess, onError);
207 private setImportedFileText = ():void => {
209 if(!this.$scope.isShowOnboardingSelectionBrowse) return;
211 //these variables makes it easier to read this logic
212 let csarUUID:string = (<Resource>this.$scope.component).csarUUID;
213 let csarVersion:string = (<Resource>this.$scope.component).csarVersion;
215 let onboardCsarFilesMap:Dictionary<Dictionary<string>> = this.cacheService.get('onboardCsarFilesMap');
216 let assignFileName = ():void => {
217 if(this.$scope.component.vspArchived){
218 this.$scope.importedToscaBrowseFileText = 'VSP is archived';
220 if(this.$stateParams.componentCsar && this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN' && !this.$scope.isCreateMode()) {
221 this.$scope.importedToscaBrowseFileText = this.$scope.originComponent.name + ' (' + (this.$scope.originComponent as Resource).csarVersion + ')';
223 if (onboardCsarFilesMap && onboardCsarFilesMap[csarUUID]) {
224 this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[csarUUID][csarVersion];
231 if(this.$scope.component.vspArchived || (onboardCsarFilesMap && onboardCsarFilesMap[csarUUID] && onboardCsarFilesMap[csarUUID][csarVersion])){ //check that the file name is already in cache
234 this.loadOnboardingFileCache().subscribe((onboardingFiles) => {
235 onboardCsarFilesMap = onboardingFiles;
236 this.cacheService.set('onboardCsarFilesMap', onboardingFiles);
243 isCreateModeAvailable(verifyObj:string): boolean {
244 var isCheckout:boolean = ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState;
245 return this.$scope.isCreateMode() || (isCheckout && !verifyObj)
248 private initScope = ():void => {
250 this.$scope.importCsarProgressKey = "importCsarProgressKey";
252 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:';
253 this.$scope.progressService = this.progressService;
254 this.$scope.componentCategories = new componentCategories();
255 this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
258 this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
261 this.$scope.initCategories();
263 // Init Environment Context
264 this.$scope.initEnvironmentContext();
267 this.$scope.initModel();
269 // Init the decision if to show file browse.
270 this.$scope.isShowFileBrowse = false;
271 if (this.$scope.component.isResource()) {
272 let resource:Resource = <Resource>this.$scope.component;
273 console.log(resource.name + ": " + resource.csarUUID);
274 if (resource.importedFile) { // Component has imported file.
275 this.$scope.isShowFileBrowse = true;
277 if (resource.resourceType === ResourceType.VF && !resource.csarUUID) {
278 this.$scope.isShowFileBrowse = true;
280 } else if (this.$scope.component.isService()) {
281 let service: Service = <Service>this.$scope.component;
282 console.log(service.name + ": " + service.csarUUID);
283 if (service.importedFile) {
284 this.$scope.isShowFileBrowse = true;
285 (<Service>this.$scope.component).ecompGeneratedNaming = true;
286 let blob = this.FileUtils.base64toBlob(service.importedFile.base64, "zip");
287 new ServiceCsarReader().read(blob).then(
289 serviceCsar.serviceMetadata.contactId = this.cacheService.get("user").userId;
290 (<Service>this.$scope.component).setComponentMetadata(serviceCsar.serviceMetadata);
291 (<Service>this.$scope.component).model = serviceCsar.serviceMetadata.model;
292 this.$scope.onModelChange();
293 this.$scope.componentCategories.selectedCategory = serviceCsar.serviceMetadata.selectedCategory;
294 this.$scope.onCategoryChange();
295 serviceCsar.extraServiceMetadata.forEach((value: string, key: string) => {
296 if (this.getMetadataKey(key)) {
297 (<Service>this.$scope.component).categorySpecificMetadata[key] = value;
300 (<Service>this.$scope.component).derivedFromGenericType = serviceCsar.substitutionNodeType;
301 this.$scope.onBaseTypeChange();
304 const errorMsg = this.$filter('translate')('IMPORT_FAILURE_MESSAGE_TEXT');
305 console.error(errorMsg, error);
306 const errorDetails = {
307 'Error': this.capitalize(error.reason),
308 'Details': this.capitalize(error.message)
310 this.modalServiceSdcUI.openErrorDetailModal('Error', this.$filter('translate')('IMPORT_FAILURE_MESSAGE_TEXT'),
311 'error-modal', errorDetails);
312 this.$state.go('dashboard');
315 if (this.$scope.isEditMode() && service.serviceType == 'Service' && !service.csarUUID) {
316 this.$scope.isShowFileBrowse = true;
318 // Init Instantiation types
319 this.$scope.initInstantiationTypes();
320 this.$scope.initBaseTypes();
323 if (this.cacheService.get(PREVIOUS_CSAR_COMPONENT)) { //keep the old component in the cache until checkout, so we dont need to pass it around
324 this.$scope.setOriginComponent(this.cacheService.get(PREVIOUS_CSAR_COMPONENT));
325 this.cacheService.remove(PREVIOUS_CSAR_COMPONENT);
328 if (this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
329 this.$scope.updateUnsavedFileFlag(true);
333 if (this.$scope.component.isResource() &&
334 (this.$scope.component as Resource).resourceType === ResourceType.VF ||
335 (this.$scope.component as Resource).resourceType === ResourceType.PNF && (this.$scope.component as Resource).csarUUID) {
336 this.$scope.isShowOnboardingSelectionBrowse = true;
337 this.setImportedFileText();
339 this.$scope.isShowOnboardingSelectionBrowse = false;
342 //init file extensions based on the file that was imported.
343 if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
344 let fileName:string = (<Resource>this.$scope.component).importedFile.filename;
345 let fileExtension:string = fileName.split(".").pop();
346 if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
347 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
348 (<Resource>this.$scope.component).importedFile.filetype = "csar";
349 } else if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
350 (<Resource>this.$scope.component).importedFile.filetype = "yaml";
351 this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
353 this.$scope.restoreFile = angular.copy((<Resource>this.$scope.originComponent).importedFile); //create backup
354 } else if (this.$scope.isEditMode() && (<Resource>this.$scope.component).resourceType === ResourceType.VF) {
355 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
356 //(<Resource>this.$scope.component).importedFile.filetype="csar";
359 this.$scope.setValidState(true);
361 this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
362 let uniqueId:string = mainCategory;
364 uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
369 //TODO remove this after handling contact in UI
370 if (this.$scope.isCreateMode()) {
371 this.$scope.component.contactId = this.cacheService.get("user").userId;
372 this.$scope.originComponent.contactId = this.$scope.component.contactId;
375 this.$scope.$on('$destroy', () => {
376 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE);
377 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE);
382 private capitalize(s) {
383 return s && s[0].toUpperCase() + s.slice(1);
386 // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
387 private convertCategoryStringToOneArray = ():IMainCategory[] => {
388 let tmp = this.$scope.component.selectedCategory.split("_#_");
389 let mainCategory = tmp[0];
390 let subCategory = tmp[1];
392 // Find the selected category and add the relevant sub category.
393 let selectedMainCategory:IMainCategory = <IMainCategory>_.find(this.$scope.categories, function (item) {
394 return item["name"] === mainCategory;
398 let mainCategoryClone = angular.copy(selectedMainCategory);
400 let selectedSubcategory = <ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
401 return item["name"] === subCategory;
403 mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
405 let tmpSelected = <IMainCategory> mainCategoryClone;
407 let result:IMainCategory[] = [];
408 result.push(tmpSelected);
413 private updateComponentNameInBreadcrumbs = ():void => {
414 // update breadcrum after changing name
415 this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
416 this.$scope.updateMenuComponentName(this.$scope.component.name);
419 //Find if a category is applicable for External API or not
420 private isHiddenCategory = (category: string) => {
421 let items: Array<any> = new Array<any>();
422 items = this.$scope.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()];
423 for(let index = 0; index < items.length; ++index) {
424 if ((items[index].hiddenCategories && items[index].hiddenCategories.indexOf(category) > -1)) {
431 private filteredCategories = () => {
432 let tempCategories: Array<IMainCategory> = new Array<IMainCategory>();
433 this.$scope.categories.forEach((category) => {
434 if (!this.isHiddenCategory(category.name)
435 && this.$scope.isCreateMode()
437 tempCategories.push(category);
438 } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
439 && !this.isHiddenCategory(this.$scope.component.selectedCategory)
440 && !this.isHiddenCategory(category.name)
442 tempCategories.push(category);
443 } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
444 && this.isHiddenCategory(this.$scope.component.selectedCategory)) {
445 tempCategories.push(category);
449 return tempCategories;
452 private initScopeMethods = ():void => {
454 this.$scope.initCategories = ():void => {
455 if (this.$scope.componentType === ComponentType.RESOURCE) {
456 this.$scope.categories = this.cacheService.get('resourceCategories');
459 if (this.$scope.componentType === ComponentType.SERVICE) {
460 this.$scope.categories = this.cacheService.get('serviceCategories');
462 //Remove categories from dropdown applicable for External API
463 if (this.$scope.isCreateMode() || (ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)) {
464 this.$scope.categories = this.filteredCategories();
465 //Flag to disbale category if service is created through External API
466 this.$scope.isHiddenCategorySelected = this.isHiddenCategory(this.$scope.component.selectedCategory);
472 this.$scope.initInstantiationTypes = ():void => {
473 if (this.$scope.componentType === ComponentType.SERVICE) {
474 this.$scope.instantiationTypes = new Array();
475 this.$scope.instantiationTypes.push(instantiationType.A_LA_CARTE);
476 this.$scope.instantiationTypes.push(instantiationType.MACRO);
477 var instantiationTypeField:string =(<Service>this.$scope.component).instantiationType;
478 if (instantiationTypeField === ""){
479 this.$scope.instantiationTypes.push("");
481 else if (this.isCreateModeAvailable(instantiationTypeField)) {
482 (<Service>this.$scope.component).instantiationType = instantiationType.A_LA_CARTE;
488 this.$scope.initBaseTypes = ():void => {
489 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component && this.$scope.component.categories) {
490 if (!this.$scope.component.derivedFromGenericType) {
491 this.$scope.component.derivedFromGenericVersion = undefined;
492 this.$scope.showBaseTypeVersions = false;
495 let modelName = this.$scope.component.model ? this.$scope.component.model : null;
496 const categoryName = this.$scope.component.categories[0].name;
497 this.elementService.getCategoryBaseTypes(categoryName, modelName).subscribe((data: ListBaseTypesResponse) => {
498 this.$scope.baseTypes = []
499 this.$scope.baseTypeVersions = []
500 this.$scope.isBaseTypeRequired = data.required;
501 data.baseTypes.forEach(baseType => {
502 this.$scope.baseTypes.push(baseType.toscaResourceName);
503 if (baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) {
504 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
507 this.$scope.showBaseTypeVersions = true;
512 this.$scope.initModel = ():void => {
513 this.$scope.isModelRequired = false;
514 this.$scope.models = [];
515 this.$scope.defaultModelOption = DEFAULT_MODEL_NAME;
516 this.$scope.showDefaultModelOption = true;
517 if (this.$scope.componentType === ComponentType.SERVICE) {
518 this.filterCategoriesByModel(this.$scope.component.model);
520 if (this.$scope.isCreateMode() && this.$scope.isVspImport()) {
521 if (this.$scope.component.componentMetadata.models) {
522 this.$scope.isModelRequired = true;
523 const modelOptions = this.$scope.component.componentMetadata.models;
524 if (modelOptions.length == 1) {
525 this.$scope.models = modelOptions;
526 this.$scope.component.model = modelOptions[0];
527 this.$scope.showDefaultModelOption = false;
529 this.$scope.models = modelOptions.sort();
530 this.$scope.defaultModelOption = 'Select';
536 if (!this.$scope.isCreateMode() && this.$scope.isVspImport()) {
537 this.modelService.getModels().subscribe((modelsFound: Model[]) => {
538 modelsFound.sort().forEach(model => {
539 if (this.$scope.component.model != undefined) {
540 if (model.modelType == "NORMATIVE_EXTENSION") {
541 if (this.$scope.component.model === model.name) {
542 this.$scope.component.model = model.derivedFrom;
544 this.$scope.models.push(model.derivedFrom)
546 this.$scope.models.push(model.name)
552 this.modelService.getModelsOfType("normative").subscribe((modelsFound: Model[]) => {
553 modelsFound.sort().forEach(model => {
554 this.$scope.models.push(model.name)
560 this.$scope.isVspImport = (): boolean => {
561 if (!this.$scope.component || !this.$scope.component.isResource()) {
565 const resource = <Resource>this.$scope.component;
566 return resource.isCsarComponent();
569 this.$scope.initEnvironmentContext = ():void => {
570 if (this.$scope.componentType === ComponentType.SERVICE) {
571 this.$scope.environmentContextObj = this.cacheService.get('UIConfiguration').environmentContext;
572 var environmentContext:string =(<Service>this.$scope.component).environmentContext;
573 // In creation new service OR check outing old service without environmentContext parameter - set default value
574 if(this.isCreateModeAvailable(environmentContext)){
575 (<Service>this.$scope.component).environmentContext = this.$scope.environmentContextObj.defaultValue;
580 this.$scope.validateField = (field:any):boolean => {
581 if (field && field.$dirty && field.$invalid) {
587 this.$scope.openOnBoardingModal = ():void => {
588 if(this.$scope.component.vspArchived) return;
589 let csarUUID = (<Resource>this.$scope.component).csarUUID;
590 let csarVersion = (<Resource>this.$scope.component).csarVersion;
591 this.importVSPService.openOnboardingModal(csarUUID, csarVersion).subscribe((result) => {
592 this.ComponentFactory.getComponentWithMetadataFromServer(result.type.toUpperCase(), result.previousComponent.uniqueId).then(
593 (component:Component)=> {
594 if (result.componentCsar && component.isResource()){
595 this.cacheService.set(PREVIOUS_CSAR_COMPONENT, angular.copy(component));
596 component = this.ComponentFactory.updateComponentFromCsar(result.componentCsar, <Resource>component);
598 this.$scope.setComponent(component);
600 this.setImportedFileText();
607 this.$scope.updateIcon = ():void => {
608 this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
609 if(isDirty && !this.$scope.isCreateMode()){
610 this.setUnsavedChanges(true);
617 this.$scope.possibleToUpdateIcon = ():boolean => {
618 if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName) && !this.$scope.component.isAlreadyCertified()){
625 this.$scope.validateName = (isInit:boolean):void => {
626 if (isInit === undefined) {
630 let name = this.$scope.component.name;
631 if (!name || name === "") {
632 if (this.$scope.editForm
633 && this.$scope.editForm["componentName"]
634 && this.$scope.editForm["componentName"].$error) {
636 // Clear the error name already exists
637 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
643 let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
644 if (subtype == "SRVC") {
648 const onFailed = (response) => {
649 // console.info('onFaild', response);
650 // this.$scope.isLoading = false;
653 const onSuccess = (validation:IValidate) => {
654 this.$scope.editForm['componentName'].$setValidity('nameExist', validation.isValid);
655 if (validation.isValid) {
656 this.updateComponentNameInBreadcrumbs(); // update breadcrumb after changing name
658 this.$scope.editForm['componentName'].$setDirty();
663 // When page is init after update
664 if (this.$scope.component.name !== this.$scope.originComponent.name) {
665 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
667 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
671 // Validating on change (has debounce)
672 if (this.$scope.editForm
673 && this.$scope.editForm["componentName"]
674 && this.$scope.editForm["componentName"].$error
675 && !this.$scope.editForm["componentName"].$error.pattern
676 && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase())
678 if (!(this.$scope.componentType === ComponentType.RESOURCE && (this.$scope.component as Resource).csarUUID !== undefined)
680 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
682 } else if (this.$scope.editForm && this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
684 this.$scope.editForm['componentName'].$setValidity('nameExist', true);
689 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, (nextState) => {
690 if (this.$state.current.data.unsavedChanges && this.$scope.isValidForm) {
691 this.$scope.save().then(() => {
692 this.$scope.handleChangeLifecycleState(nextState);
694 console.error('Save failed, unable to change lifecycle state to ' + nextState);
696 } else if(!this.$scope.isValidForm){
697 console.error('Form is not valid');
699 let newCsarVersion:string;
700 if(this.$scope.unsavedFile) {
701 newCsarVersion = (this.$scope.component as Resource).csarVersion;
703 if(this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
704 const onError = (): void => {
705 if (this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN') {
706 this.$scope.revert();
709 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion, onError);
712 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion);
717 this.$scope.revert = ():void => {
718 // in state of import file leave the file in place
720 this.$scope.setComponent(this.ComponentFactory.createComponent(this.$scope.originComponent));
722 if (this.$scope.component.isResource() && this.$scope.restoreFile) {
723 (this.$scope.component as Resource).importedFile = angular.copy(this.$scope.restoreFile);
726 this.setImportedFileText();
727 this.$scope.updateBreadcrumbs(this.$scope.component); // update on workspace
729 this.$scope.componentCategories.selectedCategory = this.$scope.originComponent.selectedCategory;
730 this.setUnsavedChanges(false);
731 this.$scope.updateUnsavedFileFlag(false);
732 this.$scope.editForm.$setPristine();
735 this.$scope.onImportFileChange = () => {
737 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
738 this.$scope.restoreFile && !angular.equals(this.$scope.restoreFile, this.$scope.editForm.fileElement.value)){ // or file was swapped for a new one
739 this.$scope.updateUnsavedFileFlag(true);
741 this.$scope.updateUnsavedFileFlag(false);
742 this.$scope.editForm.fileElement.$setPristine();
746 this.$scope.$watchCollection('component.name', (newData: any): void => {
747 this.$scope.validateName(false);
750 // Notify the parent if this step valid or not.
751 this.$scope.$watch('editForm.$valid', (newVal, oldVal) => {
752 this.$scope.setValidState(newVal);
755 this.$scope.$watch('editForm.$dirty', (newVal, oldVal) => {
756 if (newVal && !this.$scope.isCreateMode()) {
757 this.setUnsavedChanges(true);
762 this.$scope.onCategoryChange = (): void => {
763 if (!this.$scope.component.selectedCategory) {
764 this.$scope.editForm['category'].$setDirty();
766 if (!this.$scope.component.description) {
767 this.$scope.editForm['description'].$setDirty();
769 this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory;
770 if (this.$scope.component.selectedCategory) {
771 this.$scope.component.categories = this.convertCategoryStringToOneArray();
772 this.$scope.component.icon = DEFAULT_ICON;
773 if (this.$scope.component.categories[0].metadataKeys) {
774 for (let metadataKey of this.$scope.component.categories[0].metadataKeys) {
775 if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
776 this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
780 if (this.$scope.component.categories[0].subcategories && this.$scope.component.categories[0].subcategories[0].metadataKeys) {
781 for (let metadataKey of this.$scope.component.categories[0].subcategories[0].metadataKeys) {
782 if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
783 this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
787 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component.categories[0]) {
788 const modelName : string = this.$scope.component.model ? this.$scope.component.model : null;
789 this.elementService.getCategoryBaseTypes(this.$scope.component.categories[0].name, modelName)
790 .subscribe((data: ListBaseTypesResponse) => {
791 if (this.$scope.isCreateMode()) {
792 this.loadBaseTypes(data);
794 let isValidForBaseType:boolean = data.baseTypes.some(baseType => {
795 return !this.$scope.component.derivedFromGenericType ||
796 baseType.toscaResourceName === this.$scope.component.derivedFromGenericType;
798 this.$scope.editForm['category'].$setValidity('validForBaseType', isValidForBaseType);
803 this.clearBaseTypes();
807 this.$scope.onEcompGeneratedNamingChange = (): void => {
808 if (!(this.$scope.component as Service).ecompGeneratedNaming) {
809 (this.$scope.component as Service).namingPolicy = '';
813 this.$scope.getCategoryDisplayNameOrName = (mainCategory: any): string => {
814 return mainCategory.displayName ? mainCategory.displayName : mainCategory.name ;
817 this.$scope.onBaseTypeChange = (): void => {
818 if (!this.$scope.component.derivedFromGenericType) {
819 this.$scope.component.derivedFromGenericVersion = undefined;
820 this.$scope.showBaseTypeVersions = false;
824 const modelName : string = this.$scope.component.model ? this.$scope.component.model : null;
825 const categoryName = this.$scope.component.categories[0].name;
826 this.elementService.getCategoryBaseTypes(categoryName, modelName).subscribe((baseTypeResponseList: ListBaseTypesResponse) => {
827 this.$scope.baseTypeVersions = []
828 baseTypeResponseList.baseTypes.forEach(baseType => {
829 if (baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) {
830 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
831 this.$scope.component.derivedFromGenericVersion = baseType.versions[0];
834 this.$scope.showBaseTypeVersions = true;
838 this.$scope.onModelChange = (): void => {
839 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component && this.$scope.categories) {
840 let modelName = this.$scope.component.model ? this.$scope.component.model : null;
841 this.$scope.component.categories = undefined;
842 this.$scope.component.selectedCategory = undefined;
843 this.$scope.componentCategories.selectedCategory = undefined;
844 this.filterCategoriesByModel(modelName);
845 this.filterBaseTypesByModelAndCategory(modelName)
849 this.$scope.onVendorNameChange = (oldVendorName: string): void => {
850 if (this.$scope.component.icon === oldVendorName) {
851 this.$scope.component.icon = DEFAULT_ICON;
855 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload);
857 this.$scope.isMetadataKeyMandatory = (key: string): boolean => {
858 let metadataKey = this.getMetadataKey(key);
859 return metadataKey && metadataKey.mandatory;
862 this.$scope.getMetadataKeyValidValues = (key: string): string[] => {
863 let metadataKey = this.getMetadataKey(key);
865 return metadataKey.validValues;
870 this.$scope.getMetadataDisplayName = (key: string): string => {
871 let metadataKey = this.getMetadataKey(key);
873 return metadataKey.displayName ? metadataKey.displayName : metadataKey.name;
878 this.$scope.isMetadataKeyForComponentCategory = (key: string): boolean => {
879 return this.getMetadataKey(key) != null;
882 this.$scope.isCategoryServiceMetadataKey = (key: string): boolean => {
883 return this.isServiceMetadataKey(key);
886 this.$scope.isMetadataKeyForComponentCategoryService = (key: string, attribute: string): boolean => {
887 let metadatakey = this.getMetadataKey(key);
888 if (metadatakey && (!this.$scope.component[attribute] || !metadatakey.validValues.find(v => v === this.$scope.component[attribute]))) {
889 this.$scope.component[attribute] = metadatakey.defaultValue;
891 return metadatakey != null;
894 this.$scope.isNotApplicableMetadataKeys = (key: string): boolean => {
895 return this.$scope.component.categories && this.$scope.component.categories[0].notApplicableMetadataKeys && this.$scope.component.categories[0].notApplicableMetadataKeys.some(item => item === key);
899 private filterCategoriesByModel(modelName:string) {
901 this.$scope.initCategories();
902 this.$scope.categories = this.$scope.categories.filter(category =>
903 !modelName ? !category.models || category.models.indexOf(DEFAULT_MODEL_NAME) !== -1 : category.models !== null && category.models.indexOf(modelName) !== -1);
906 private filterBaseTypesByModelAndCategory(modelName:string) {
907 let categories = this.$scope.component.categories;
909 this.elementService.getCategoryBaseTypes(categories[0].name, modelName).subscribe((data: ListBaseTypesResponse) => {
910 this.loadBaseTypes(data);
914 this.clearBaseTypes();
917 private loadBaseTypes(baseTypeResponseList: ListBaseTypesResponse) {
918 this.$scope.isBaseTypeRequired = baseTypeResponseList.required;
919 this.$scope.baseTypes = [];
920 this.$scope.baseTypeVersions = [];
921 let defaultBaseType = baseTypeResponseList.defaultBaseType;
922 baseTypeResponseList.baseTypes.forEach(baseType => this.$scope.baseTypes.push(baseType.toscaResourceName));
923 if (this.$scope.isBaseTypeRequired || defaultBaseType != null) {
924 let baseType = baseTypeResponseList.baseTypes[0];
925 if(defaultBaseType != null){
926 baseTypeResponseList.baseTypes.forEach(baseTypeObj => {
927 if(baseTypeObj.toscaResourceName == defaultBaseType) {
928 baseType = baseTypeObj;
932 if((<Service>this.$scope.component).derivedFromGenericType) {
933 baseTypeResponseList.baseTypes.forEach(baseTypeObj => {
934 if(baseTypeObj.toscaResourceName == (<Service>this.$scope.component).derivedFromGenericType) {
935 baseType = baseTypeObj;
939 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
940 this.$scope.component.derivedFromGenericType = baseType.toscaResourceName;
941 this.$scope.component.derivedFromGenericVersion = this.$scope.baseTypeVersions[0];
942 this.$scope.showBaseTypeVersions = true;
945 this.$scope.component.derivedFromGenericType = undefined;
946 this.$scope.component.derivedFromGenericVersion = undefined;
947 this.$scope.showBaseTypeVersions = false;
950 private clearBaseTypes() {
951 this.$scope.isBaseTypeRequired = false;
952 this.$scope.baseTypes = [];
953 this.$scope.baseTypeVersions = [];
954 this.$scope.component.derivedFromGenericType = undefined;
955 this.$scope.component.derivedFromGenericVersion = undefined;
956 this.$scope.showBaseTypeVersions = false;
959 private setUnsavedChanges = (hasChanges: boolean): void => {
960 this.$state.current.data.unsavedChanges = hasChanges;
963 private getMetadataKey(key: string) : IMetadataKey {
964 if (this.$scope.component.categories) {
965 let metadataKey = this.getSubcategoryMetadataKey(this.$scope.component.categories, key);
967 return this.getCategoryMetadataKey(this.$scope.component.categories, key);
974 private getSubcategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
975 if (categories[0].subcategories && categories[0].subcategories[0].metadataKeys && categories[0].subcategories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
976 return categories[0].subcategories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
981 private getCategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
982 if (categories[0].metadataKeys && categories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
983 return categories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
988 private isServiceMetadataKey(key: string) : boolean {
989 return CATEGORY_SERVICE_METADATA_KEYS.indexOf(key) > -1;