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;
89 functionOption: string;
90 othersRoleFlag: boolean;
95 onImportFileChange():void;
96 validateField(field:any):boolean;
97 validateName(isInit:boolean):void;
98 calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
99 onVendorNameChange(oldVendorName:string):void;
100 convertCategoryStringToOneArray(category:string, subcategory:string):Array<IMainCategory>;
101 onCategoryChange():void;
102 onEcompGeneratedNamingChange():void;
103 onModelChange():void;
104 onBaseTypeChange():void;
105 openOnBoardingModal():void;
106 initCategories():void;
107 initEnvironmentContext():void;
108 initInstantiationTypes():void;
109 initBaseTypes():void;
110 onInstantiationTypeChange():void;
112 possibleToUpdateIcon():boolean;
114 isVspImport(): boolean;
115 setServiceFunction(option:string):void;
116 setServiceRole(option:string):void;
119 // tslint:disable-next-line:max-classes-per-file
120 export class GeneralViewModel {
124 'Sdc.Services.CacheService',
125 'ComponentNameValidationPattern',
126 'ContactIdValidationPattern',
127 'TagValidationPattern',
128 'VendorReleaseValidationPattern',
129 'VendorNameValidationPattern',
130 'VendorModelNumberValidationPattern',
131 'CommentValidationPattern',
138 'EventListenerService',
140 'Sdc.Services.ProgressService',
152 constructor(private $scope:IGeneralScope,
153 private cacheService:CacheService,
154 private ComponentNameValidationPattern:RegExp,
155 private ContactIdValidationPattern:RegExp,
156 private TagValidationPattern:RegExp,
157 private VendorReleaseValidationPattern:RegExp,
158 private VendorNameValidationPattern:RegExp,
159 private VendorModelNumberValidationPattern:RegExp,
160 private CommentValidationPattern:RegExp,
161 private ValidationUtils:ValidationUtils,
162 private FileUtils: FileUtils,
163 private sdcConfig:IAppConfigurtaion,
164 private $state:ng.ui.IStateService,
165 private ModalsHandler:ModalsHandler,
166 private modalServiceSdcUI: SdcUiServices.ModalService,
167 private EventListenerService:EventListenerService,
168 private Notification:any,
169 private progressService:ProgressService,
170 protected $interval:any,
171 private $filter:ng.IFilterService,
172 private $timeout:ng.ITimeoutService,
173 private onBoardingService: OnboardingService,
174 private ComponentFactory:ComponentFactory,
175 private importVSPService: ImportVSPService,
176 private elementService: ElementService,
177 private modelService: ModelService,
178 private $stateParams: any) {
180 this.initScopeValidation();
181 this.initScopeMethods();
185 private initScopeValidation = ():void => {
186 this.$scope.validation = new Validation();
187 this.$scope.validation.componentNameValidationPattern = this.ComponentNameValidationPattern;
188 this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
189 this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
190 this.$scope.validation.VendorReleaseValidationPattern = this.VendorReleaseValidationPattern;
191 this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern;
192 this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern;
193 this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
196 private loadOnboardingFileCache = (): Observable<Dictionary<Dictionary<string>>> => {
197 let onboardCsarFilesMap:Dictionary<Dictionary<string>>;
198 let onSuccess = (vsps:Array<ICsarComponent>) => {
199 onboardCsarFilesMap = {};
200 _.each(vsps, (vsp:ICsarComponent)=>{
201 onboardCsarFilesMap[vsp.packageId] = onboardCsarFilesMap[vsp.packageId] || {};
202 onboardCsarFilesMap[vsp.packageId][vsp.version] = vsp.vspName + " (" + vsp.version + ")";
204 this.cacheService.set('onboardCsarFilesMap', onboardCsarFilesMap);
205 return onboardCsarFilesMap;
207 let onError = (): void =>{
208 console.log("Error getting onboarding list");
210 return this.onBoardingService.getOnboardingVSPs().map(onSuccess, onError);
213 private setImportedFileText = ():void => {
215 if(!this.$scope.isShowOnboardingSelectionBrowse) return;
217 //these variables makes it easier to read this logic
218 let csarUUID:string = (<Resource>this.$scope.component).csarUUID;
219 let csarVersion:string = (<Resource>this.$scope.component).csarVersion;
221 let onboardCsarFilesMap:Dictionary<Dictionary<string>> = this.cacheService.get('onboardCsarFilesMap');
222 let assignFileName = ():void => {
223 if(this.$scope.component.vspArchived){
224 this.$scope.importedToscaBrowseFileText = 'VSP is archived';
226 if(this.$stateParams.componentCsar && this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN' && !this.$scope.isCreateMode()) {
227 this.$scope.importedToscaBrowseFileText = this.$scope.originComponent.name + ' (' + (this.$scope.originComponent as Resource).csarVersion + ')';
229 if (onboardCsarFilesMap && onboardCsarFilesMap[csarUUID]) {
230 this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[csarUUID][csarVersion];
237 if(this.$scope.component.vspArchived || (onboardCsarFilesMap && onboardCsarFilesMap[csarUUID] && onboardCsarFilesMap[csarUUID][csarVersion])){ //check that the file name is already in cache
240 this.loadOnboardingFileCache().subscribe((onboardingFiles) => {
241 onboardCsarFilesMap = onboardingFiles;
242 this.cacheService.set('onboardCsarFilesMap', onboardingFiles);
249 isCreateModeAvailable(verifyObj:string): boolean {
250 var isCheckout:boolean = ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState;
251 return this.$scope.isCreateMode() || (isCheckout && !verifyObj)
254 private initScope = ():void => {
256 this.$scope.importCsarProgressKey = "importCsarProgressKey";
258 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:';
259 this.$scope.progressService = this.progressService;
260 this.$scope.componentCategories = new componentCategories();
261 this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
262 this.$scope.othersFlag = false;
263 this.$scope.othersRoleFlag = false;
266 this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
269 this.$scope.initCategories();
271 // Init Environment Context
272 this.$scope.initEnvironmentContext();
275 this.$scope.initModel();
277 // Init the decision if to show file browse.
278 this.$scope.isShowFileBrowse = false;
279 if (this.$scope.component.isResource()) {
280 let resource:Resource = <Resource>this.$scope.component;
281 console.log(resource.name + ": " + resource.csarUUID);
282 if (resource.importedFile) { // Component has imported file.
283 this.$scope.isShowFileBrowse = true;
285 if (resource.resourceType === ResourceType.VF && !resource.csarUUID) {
286 this.$scope.isShowFileBrowse = true;
288 } else if (this.$scope.component.isService()) {
289 let service: Service = <Service>this.$scope.component;
290 console.log(service.name + ": " + service.csarUUID);
291 if (service.importedFile) {
292 this.$scope.isShowFileBrowse = true;
293 (<Service>this.$scope.component).ecompGeneratedNaming = true;
294 let blob = this.FileUtils.base64toBlob(service.importedFile.base64, "zip");
295 new ServiceCsarReader().read(blob).then(
297 serviceCsar.serviceMetadata.contactId = this.cacheService.get("user").userId;
298 (<Service>this.$scope.component).setComponentMetadata(serviceCsar.serviceMetadata);
299 (<Service>this.$scope.component).model = serviceCsar.serviceMetadata.model;
300 this.$scope.onModelChange();
301 this.$scope.componentCategories.selectedCategory = serviceCsar.serviceMetadata.selectedCategory;
302 this.$scope.onCategoryChange();
303 serviceCsar.extraServiceMetadata.forEach((value: string, key: string) => {
304 if (this.getMetadataKey(key)) {
305 (<Service>this.$scope.component).categorySpecificMetadata[key] = value;
308 (<Service>this.$scope.component).derivedFromGenericType = serviceCsar.substitutionNodeType;
309 this.$scope.onBaseTypeChange();
310 this.setFunctionRole(service);
313 const errorMsg = this.$filter('translate')('IMPORT_FAILURE_MESSAGE_TEXT');
314 console.error(errorMsg, error);
315 const errorDetails = {
316 'Error': this.capitalize(error.reason),
317 'Details': this.capitalize(error.message)
319 this.modalServiceSdcUI.openErrorDetailModal('Error', this.$filter('translate')('IMPORT_FAILURE_MESSAGE_TEXT'),
320 'error-modal', errorDetails);
321 this.$state.go('dashboard');
325 this.setFunctionRole(service);
327 if (this.$scope.isEditMode() && service.serviceType == 'Service' && !service.csarUUID) {
328 this.$scope.isShowFileBrowse = true;
330 // Init Instantiation types
331 this.$scope.initInstantiationTypes();
332 this.$scope.initBaseTypes();
335 if (this.cacheService.get(PREVIOUS_CSAR_COMPONENT)) { //keep the old component in the cache until checkout, so we dont need to pass it around
336 this.$scope.setOriginComponent(this.cacheService.get(PREVIOUS_CSAR_COMPONENT));
337 this.cacheService.remove(PREVIOUS_CSAR_COMPONENT);
340 if (this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
341 this.$scope.updateUnsavedFileFlag(true);
345 if (this.$scope.component.isResource() &&
346 (this.$scope.component as Resource).resourceType === ResourceType.VF ||
347 (this.$scope.component as Resource).resourceType === ResourceType.PNF && (this.$scope.component as Resource).csarUUID) {
348 this.$scope.isShowOnboardingSelectionBrowse = true;
349 this.setImportedFileText();
351 this.$scope.isShowOnboardingSelectionBrowse = false;
354 //init file extensions based on the file that was imported.
355 if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
356 let fileName:string = (<Resource>this.$scope.component).importedFile.filename;
357 let fileExtension:string = fileName.split(".").pop();
358 if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
359 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
360 (<Resource>this.$scope.component).importedFile.filetype = "csar";
361 } else if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
362 (<Resource>this.$scope.component).importedFile.filetype = "yaml";
363 this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
365 this.$scope.restoreFile = angular.copy((<Resource>this.$scope.originComponent).importedFile); //create backup
366 } else if (this.$scope.isEditMode() && (<Resource>this.$scope.component).resourceType === ResourceType.VF) {
367 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
368 //(<Resource>this.$scope.component).importedFile.filetype="csar";
371 this.$scope.setValidState(true);
373 this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
374 let uniqueId:string = mainCategory;
376 uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
381 //TODO remove this after handling contact in UI
382 if (this.$scope.isCreateMode()) {
383 this.$scope.component.contactId = this.cacheService.get("user").userId;
384 this.$scope.originComponent.contactId = this.$scope.component.contactId;
387 this.$scope.$on('$destroy', () => {
388 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE);
389 this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE);
394 private capitalize(s) {
395 return s && s[0].toUpperCase() + s.slice(1);
398 private setFunctionRole = (service : Service) : void => {
399 if (service.serviceFunction) {
400 const functionList : string[] = this.$scope.getMetadataKeyValidValues('Service Function');
401 if (functionList.find(value => value == service.serviceFunction) != undefined) {
402 this.$scope.functionOption = service.serviceFunction;
404 this.$scope.functionOption = 'Others';
405 this.$scope.othersFlag = true;
409 if (service.serviceRole) {
410 const roleList : string[] = this.$scope.getMetadataKeyValidValues('Service Role');
411 if (roleList.find(value => value == service.serviceRole) != undefined) {
412 this.$scope.roleOption = service.serviceRole;
414 this.$scope.roleOption = 'Others';
415 this.$scope.othersRoleFlag = true;
420 // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
421 private convertCategoryStringToOneArray = ():IMainCategory[] => {
422 let tmp = this.$scope.component.selectedCategory.split("_#_");
423 let mainCategory = tmp[0];
424 let subCategory = tmp[1];
426 // Find the selected category and add the relevant sub category.
427 let selectedMainCategory:IMainCategory = <IMainCategory>_.find(this.$scope.categories, function (item) {
428 return item["name"] === mainCategory;
432 let mainCategoryClone = angular.copy(selectedMainCategory);
434 let selectedSubcategory = <ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
435 return item["name"] === subCategory;
437 mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
439 let tmpSelected = <IMainCategory> mainCategoryClone;
441 let result:IMainCategory[] = [];
442 result.push(tmpSelected);
447 private updateComponentNameInBreadcrumbs = ():void => {
448 // update breadcrum after changing name
449 this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
450 this.$scope.updateMenuComponentName(this.$scope.component.name);
453 //Find if a category is applicable for External API or not
454 private isHiddenCategory = (category: string) => {
455 let items: Array<any> = new Array<any>();
456 items = this.$scope.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()];
457 for(let index = 0; index < items.length; ++index) {
458 if ((items[index].hiddenCategories && items[index].hiddenCategories.indexOf(category) > -1)) {
465 private filteredCategories = () => {
466 let tempCategories: Array<IMainCategory> = new Array<IMainCategory>();
467 this.$scope.categories.forEach((category) => {
468 if (!this.isHiddenCategory(category.name)
469 && this.$scope.isCreateMode()
471 tempCategories.push(category);
472 } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
473 && !this.isHiddenCategory(this.$scope.component.selectedCategory)
474 && !this.isHiddenCategory(category.name)
476 tempCategories.push(category);
477 } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
478 && this.isHiddenCategory(this.$scope.component.selectedCategory)) {
479 tempCategories.push(category);
483 return tempCategories;
486 private initScopeMethods = ():void => {
488 this.$scope.initCategories = ():void => {
489 if (this.$scope.componentType === ComponentType.RESOURCE) {
490 this.$scope.categories = this.cacheService.get('resourceCategories');
493 if (this.$scope.componentType === ComponentType.SERVICE) {
494 this.$scope.categories = this.cacheService.get('serviceCategories');
496 //Remove categories from dropdown applicable for External API
497 if (this.$scope.isCreateMode() || (ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)) {
498 this.$scope.categories = this.filteredCategories();
499 //Flag to disbale category if service is created through External API
500 this.$scope.isHiddenCategorySelected = this.isHiddenCategory(this.$scope.component.selectedCategory);
506 this.$scope.initInstantiationTypes = ():void => {
507 if (this.$scope.componentType === ComponentType.SERVICE) {
508 this.$scope.instantiationTypes = new Array();
509 this.$scope.instantiationTypes.push(instantiationType.A_LA_CARTE);
510 this.$scope.instantiationTypes.push(instantiationType.MACRO);
511 var instantiationTypeField:string =(<Service>this.$scope.component).instantiationType;
512 if (instantiationTypeField === ""){
513 this.$scope.instantiationTypes.push("");
515 else if (this.isCreateModeAvailable(instantiationTypeField)) {
516 (<Service>this.$scope.component).instantiationType = instantiationType.A_LA_CARTE;
522 this.$scope.initBaseTypes = ():void => {
523 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component && this.$scope.component.categories) {
524 if (!this.$scope.component.derivedFromGenericType) {
525 this.$scope.component.derivedFromGenericVersion = undefined;
526 this.$scope.showBaseTypeVersions = false;
529 let modelName = this.$scope.component.model ? this.$scope.component.model : null;
530 const categoryName = this.$scope.component.categories[0].name;
531 this.elementService.getCategoryBaseTypes(categoryName, modelName).subscribe((data: ListBaseTypesResponse) => {
532 this.$scope.baseTypes = []
533 this.$scope.baseTypeVersions = []
534 this.$scope.isBaseTypeRequired = data.required;
535 data.baseTypes.forEach(baseType => {
536 this.$scope.baseTypes.push(baseType.toscaResourceName);
537 if (baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) {
538 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
541 this.$scope.showBaseTypeVersions = true;
546 this.$scope.initModel = ():void => {
547 this.$scope.isModelRequired = false;
548 this.$scope.models = [];
549 this.$scope.defaultModelOption = DEFAULT_MODEL_NAME;
550 this.$scope.showDefaultModelOption = true;
551 if (this.$scope.componentType === ComponentType.SERVICE) {
552 this.filterCategoriesByModel(this.$scope.component.model);
554 if (this.$scope.isCreateMode() && this.$scope.isVspImport()) {
555 if (this.$scope.component.componentMetadata.models) {
556 this.$scope.isModelRequired = true;
557 const modelOptions = this.$scope.component.componentMetadata.models;
558 if (modelOptions.length == 1) {
559 this.$scope.models = modelOptions;
560 this.$scope.component.model = modelOptions[0];
561 this.$scope.showDefaultModelOption = false;
563 this.$scope.models = modelOptions.sort();
564 this.$scope.defaultModelOption = 'Select';
570 if (!this.$scope.isCreateMode() && this.$scope.isVspImport()) {
571 this.modelService.getModels().subscribe((modelsFound: Model[]) => {
572 modelsFound.sort().forEach(model => {
573 if (this.$scope.component.model != undefined) {
574 if (model.modelType == "NORMATIVE_EXTENSION") {
575 if (this.$scope.component.model === model.name) {
576 this.$scope.component.model = model.derivedFrom;
578 this.$scope.models.push(model.derivedFrom)
580 this.$scope.models.push(model.name)
586 this.modelService.getModelsOfType("normative").subscribe((modelsFound: Model[]) => {
587 modelsFound.sort().forEach(model => {
588 this.$scope.models.push(model.name)
594 this.$scope.isVspImport = (): boolean => {
595 if (!this.$scope.component || !this.$scope.component.isResource()) {
599 const resource = <Resource>this.$scope.component;
600 return resource.isCsarComponent();
603 this.$scope.initEnvironmentContext = ():void => {
604 if (this.$scope.componentType === ComponentType.SERVICE) {
605 this.$scope.environmentContextObj = this.cacheService.get('UIConfiguration').environmentContext;
606 var environmentContext:string =(<Service>this.$scope.component).environmentContext;
607 // In creation new service OR check outing old service without environmentContext parameter - set default value
608 if(this.isCreateModeAvailable(environmentContext)){
609 (<Service>this.$scope.component).environmentContext = this.$scope.environmentContextObj.defaultValue;
614 this.$scope.validateField = (field:any):boolean => {
615 if (field && field.$dirty && field.$invalid) {
621 this.$scope.openOnBoardingModal = ():void => {
622 if(this.$scope.component.vspArchived) return;
623 let csarUUID = (<Resource>this.$scope.component).csarUUID;
624 let csarVersion = (<Resource>this.$scope.component).csarVersion;
625 this.importVSPService.openOnboardingModal(csarUUID, csarVersion).subscribe((result) => {
626 this.ComponentFactory.getComponentWithMetadataFromServer(result.type.toUpperCase(), result.previousComponent.uniqueId).then(
627 (component:Component)=> {
628 if (result.componentCsar && component.isResource()){
629 this.cacheService.set(PREVIOUS_CSAR_COMPONENT, angular.copy(component));
630 component = this.ComponentFactory.updateComponentFromCsar(result.componentCsar, <Resource>component);
632 this.$scope.setComponent(component);
634 this.setImportedFileText();
641 this.$scope.updateIcon = ():void => {
642 this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
643 if(isDirty && !this.$scope.isCreateMode()){
644 this.setUnsavedChanges(true);
651 this.$scope.possibleToUpdateIcon = ():boolean => {
652 if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName) && !this.$scope.component.isAlreadyCertified()){
659 this.$scope.validateName = (isInit:boolean):void => {
660 if (isInit === undefined) {
664 let name = this.$scope.component.name;
665 if (!name || name === "") {
666 if (this.$scope.editForm
667 && this.$scope.editForm["componentName"]
668 && this.$scope.editForm["componentName"].$error) {
670 // Clear the error name already exists
671 this.$scope.editForm["componentName"].$setValidity('nameExist', true);
677 let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
678 if (subtype == "SRVC") {
682 const onFailed = (response) => {
683 // console.info('onFaild', response);
684 // this.$scope.isLoading = false;
687 const onSuccess = (validation:IValidate) => {
688 this.$scope.editForm['componentName'].$setValidity('nameExist', validation.isValid);
689 if (validation.isValid) {
690 this.updateComponentNameInBreadcrumbs(); // update breadcrumb after changing name
692 this.$scope.editForm['componentName'].$setDirty();
697 // When page is init after update
698 if (this.$scope.component.name !== this.$scope.originComponent.name) {
699 if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
701 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
705 // Validating on change (has debounce)
706 if (this.$scope.editForm
707 && this.$scope.editForm["componentName"]
708 && this.$scope.editForm["componentName"].$error
709 && !this.$scope.editForm["componentName"].$error.pattern
710 && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase())
712 if (!(this.$scope.componentType === ComponentType.RESOURCE && (this.$scope.component as Resource).csarUUID !== undefined)
714 this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
716 } else if (this.$scope.editForm && this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
718 this.$scope.editForm['componentName'].$setValidity('nameExist', true);
723 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, (nextState) => {
724 if (this.$state.current.data.unsavedChanges && this.$scope.isValidForm) {
725 this.$scope.save().then(() => {
726 this.$scope.handleChangeLifecycleState(nextState);
728 console.error('Save failed, unable to change lifecycle state to ' + nextState);
730 } else if(!this.$scope.isValidForm){
731 console.error('Form is not valid');
733 let newCsarVersion:string;
734 if(this.$scope.unsavedFile) {
735 newCsarVersion = (this.$scope.component as Resource).csarVersion;
737 if(this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
738 const onError = (): void => {
739 if (this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN') {
740 this.$scope.revert();
743 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion, onError);
746 this.$scope.handleChangeLifecycleState(nextState, newCsarVersion);
751 this.$scope.revert = ():void => {
752 // in state of import file leave the file in place
754 this.$scope.setComponent(this.ComponentFactory.createComponent(this.$scope.originComponent));
756 if (this.$scope.component.isResource() && this.$scope.restoreFile) {
757 (this.$scope.component as Resource).importedFile = angular.copy(this.$scope.restoreFile);
760 this.setImportedFileText();
761 this.$scope.updateBreadcrumbs(this.$scope.component); // update on workspace
763 this.$scope.componentCategories.selectedCategory = this.$scope.originComponent.selectedCategory;
764 this.setUnsavedChanges(false);
765 this.$scope.updateUnsavedFileFlag(false);
766 this.$scope.editForm.$setPristine();
769 this.$scope.onImportFileChange = () => {
771 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
772 this.$scope.restoreFile && !angular.equals(this.$scope.restoreFile, this.$scope.editForm.fileElement.value)){ // or file was swapped for a new one
773 this.$scope.updateUnsavedFileFlag(true);
775 this.$scope.updateUnsavedFileFlag(false);
776 this.$scope.editForm.fileElement.$setPristine();
780 this.$scope.$watchCollection('component.name', (newData: any): void => {
781 this.$scope.validateName(false);
784 // Notify the parent if this step valid or not.
785 this.$scope.$watch('editForm.$valid', (newVal, oldVal) => {
786 this.$scope.setValidState(newVal);
789 this.$scope.$watch('editForm.$dirty', (newVal, oldVal) => {
790 if (newVal && !this.$scope.isCreateMode()) {
791 this.setUnsavedChanges(true);
796 this.$scope.onCategoryChange = (): void => {
797 if (!this.$scope.component.selectedCategory) {
798 this.$scope.editForm['category'].$setDirty();
800 if (!this.$scope.component.description) {
801 this.$scope.editForm['description'].$setDirty();
803 this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory;
804 if (this.$scope.component.selectedCategory) {
805 this.$scope.component.categories = this.convertCategoryStringToOneArray();
806 this.$scope.component.icon = DEFAULT_ICON;
807 if (this.$scope.component.categories[0].metadataKeys) {
808 for (let metadataKey of this.$scope.component.categories[0].metadataKeys) {
809 if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
810 this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
812 if (metadataKey.name === 'Service Role') {
813 this.$scope.roleOption = this.$scope.component.categorySpecificMetadata[metadataKey.name];
815 if (metadataKey.name === 'Service Function') {
816 this.$scope.functionOption = this.$scope.component.categorySpecificMetadata[metadataKey.name];
820 if (this.$scope.component.categories[0].subcategories && this.$scope.component.categories[0].subcategories[0].metadataKeys) {
821 for (let metadataKey of this.$scope.component.categories[0].subcategories[0].metadataKeys) {
822 if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
823 this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
827 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component.categories[0]) {
828 const modelName : string = this.$scope.component.model ? this.$scope.component.model : null;
829 this.elementService.getCategoryBaseTypes(this.$scope.component.categories[0].name, modelName)
830 .subscribe((data: ListBaseTypesResponse) => {
831 if (this.$scope.isCreateMode()) {
832 this.loadBaseTypes(data);
834 let isValidForBaseType:boolean = data.baseTypes.some(baseType => {
835 return !this.$scope.component.derivedFromGenericType ||
836 baseType.toscaResourceName === this.$scope.component.derivedFromGenericType;
838 this.$scope.editForm['category'].$setValidity('validForBaseType', isValidForBaseType);
843 this.clearBaseTypes();
847 this.$scope.onEcompGeneratedNamingChange = (): void => {
848 if (!(this.$scope.component as Service).ecompGeneratedNaming) {
849 (this.$scope.component as Service).namingPolicy = '';
853 this.$scope.getCategoryDisplayNameOrName = (mainCategory: any): string => {
854 return mainCategory.displayName ? mainCategory.displayName : mainCategory.name ;
857 this.$scope.onBaseTypeChange = (): void => {
858 if (!this.$scope.component.derivedFromGenericType) {
859 this.$scope.component.derivedFromGenericVersion = undefined;
860 this.$scope.showBaseTypeVersions = false;
864 const modelName : string = this.$scope.component.model ? this.$scope.component.model : null;
865 const categoryName = this.$scope.component.categories[0].name;
866 this.elementService.getCategoryBaseTypes(categoryName, modelName).subscribe((baseTypeResponseList: ListBaseTypesResponse) => {
867 this.$scope.baseTypeVersions = []
868 baseTypeResponseList.baseTypes.forEach(baseType => {
869 if (baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) {
870 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
871 this.$scope.component.derivedFromGenericVersion = baseType.versions[0];
874 this.$scope.showBaseTypeVersions = true;
878 this.$scope.onModelChange = (): void => {
879 if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component && this.$scope.categories) {
880 let modelName = this.$scope.component.model ? this.$scope.component.model : null;
881 this.$scope.component.categories = undefined;
882 this.$scope.component.selectedCategory = undefined;
883 this.$scope.componentCategories.selectedCategory = undefined;
884 this.filterCategoriesByModel(modelName);
885 this.filterBaseTypesByModelAndCategory(modelName)
889 this.$scope.onVendorNameChange = (oldVendorName: string): void => {
890 if (this.$scope.component.icon === oldVendorName) {
891 this.$scope.component.icon = DEFAULT_ICON;
895 this.$scope.setServiceFunction = (option:string): void => {
896 if (option === 'Others') {
897 this.$scope.othersFlag = true;
898 (<Service>this.$scope.component).serviceFunction = '';
900 this.$scope.othersFlag = false;
901 (<Service>this.$scope.component).serviceFunction = option;
906 this.$scope.setServiceRole = (option:string): void => {
907 if (option === 'Others') {
908 this.$scope.othersRoleFlag = true;
909 (<Service>this.$scope.component).serviceRole = '';
911 this.$scope.othersRoleFlag = false;
912 (<Service>this.$scope.component).serviceRole = option;
917 this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload);
919 this.$scope.isMetadataKeyMandatory = (key: string): boolean => {
920 let metadataKey = this.getMetadataKey(key);
921 return metadataKey && metadataKey.mandatory;
924 this.$scope.getMetadataKeyValidValues = (key: string): string[] => {
925 let metadataKey = this.getMetadataKey(key);
927 if (key == 'Service Function' || key == 'Service Role') {
928 return metadataKey.validValues.concat("Others");
930 return metadataKey.validValues;
936 this.$scope.getMetadataDisplayName = (key: string): string => {
937 let metadataKey = this.getMetadataKey(key);
939 return metadataKey.displayName ? metadataKey.displayName : metadataKey.name;
944 this.$scope.isMetadataKeyForComponentCategory = (key: string): boolean => {
945 return this.getMetadataKey(key) != null;
948 this.$scope.isCategoryServiceMetadataKey = (key: string): boolean => {
949 return this.isServiceMetadataKey(key);
952 this.$scope.isMetadataKeyForComponentCategoryService = (key: string, attribute: string): boolean => {
953 let metadatakey = this.getMetadataKey(key);
954 if (metadatakey && (!this.$scope.component[attribute] || !metadatakey.validValues.find(v => v === this.$scope.component[attribute]))) {
955 this.$scope.component[attribute] = metadatakey.defaultValue;
957 return metadatakey != null;
960 this.$scope.isNotApplicableMetadataKeys = (key: string): boolean => {
961 return this.$scope.component.categories && this.$scope.component.categories[0].notApplicableMetadataKeys && this.$scope.component.categories[0].notApplicableMetadataKeys.some(item => item === key);
965 private filterCategoriesByModel(modelName:string) {
967 this.$scope.initCategories();
968 this.$scope.categories = this.$scope.categories.filter(category =>
969 !modelName ? !category.models || category.models.indexOf(DEFAULT_MODEL_NAME) !== -1 : category.models !== null && category.models.indexOf(modelName) !== -1);
972 private filterBaseTypesByModelAndCategory(modelName:string) {
973 let categories = this.$scope.component.categories;
975 this.elementService.getCategoryBaseTypes(categories[0].name, modelName).subscribe((data: ListBaseTypesResponse) => {
976 this.loadBaseTypes(data);
980 this.clearBaseTypes();
983 private loadBaseTypes(baseTypeResponseList: ListBaseTypesResponse) {
984 this.$scope.isBaseTypeRequired = baseTypeResponseList.required;
985 this.$scope.baseTypes = [];
986 this.$scope.baseTypeVersions = [];
987 let defaultBaseType = baseTypeResponseList.defaultBaseType;
988 baseTypeResponseList.baseTypes.forEach(baseType => this.$scope.baseTypes.push(baseType.toscaResourceName));
989 if (this.$scope.isBaseTypeRequired || defaultBaseType != null) {
990 let baseType = baseTypeResponseList.baseTypes[0];
991 if(defaultBaseType != null){
992 baseTypeResponseList.baseTypes.forEach(baseTypeObj => {
993 if(baseTypeObj.toscaResourceName == defaultBaseType) {
994 baseType = baseTypeObj;
998 if((<Service>this.$scope.component).derivedFromGenericType) {
999 baseTypeResponseList.baseTypes.forEach(baseTypeObj => {
1000 if(baseTypeObj.toscaResourceName == (<Service>this.$scope.component).derivedFromGenericType) {
1001 baseType = baseTypeObj;
1005 baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
1006 this.$scope.component.derivedFromGenericType = baseType.toscaResourceName;
1007 this.$scope.component.derivedFromGenericVersion = this.$scope.baseTypeVersions[0];
1008 this.$scope.showBaseTypeVersions = true;
1011 this.$scope.component.derivedFromGenericType = undefined;
1012 this.$scope.component.derivedFromGenericVersion = undefined;
1013 this.$scope.showBaseTypeVersions = false;
1016 private clearBaseTypes() {
1017 this.$scope.isBaseTypeRequired = false;
1018 this.$scope.baseTypes = [];
1019 this.$scope.baseTypeVersions = [];
1020 this.$scope.component.derivedFromGenericType = undefined;
1021 this.$scope.component.derivedFromGenericVersion = undefined;
1022 this.$scope.showBaseTypeVersions = false;
1025 private setUnsavedChanges = (hasChanges: boolean): void => {
1026 this.$state.current.data.unsavedChanges = hasChanges;
1029 private getMetadataKey(key: string) : IMetadataKey {
1030 if (this.$scope.component.categories) {
1031 let metadataKey = this.getSubcategoryMetadataKey(this.$scope.component.categories, key);
1033 return this.getCategoryMetadataKey(this.$scope.component.categories, key);
1040 private getSubcategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
1041 if (categories[0].subcategories && categories[0].subcategories[0].metadataKeys && categories[0].subcategories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
1042 return categories[0].subcategories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
1047 private getCategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
1048 if (categories[0].metadataKeys && categories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
1049 return categories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
1054 private isServiceMetadataKey(key: string) : boolean {
1055 return CATEGORY_SERVICE_METADATA_KEYS.indexOf(key) > -1;