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 {FormState, PROPERTY_DATA, PROPERTY_TYPES, PROPERTY_VALUE_CONSTRAINTS, ValidationUtils} from "app/utils";
24 import {DataTypesService} from "app/services";
25 import {DataTypesMap, PropertyModel} from "app/models";
26 import {ComponentInstance} from "../../../../models/componentsInstances/componentInstance";
27 import {ComponentInstanceServiceNg2} from "app/ng2/services/component-instance-services/component-instance.service";
28 import {SdcUiCommon, SdcUiComponents, SdcUiServices} from "onap-ui-angular";
29 import {CompositionService} from "app/ng2/pages/composition/composition.service";
30 import {WorkspaceService} from "app/ng2/pages/workspace/workspace.service";
31 import {Observable} from "rxjs";
32 import {TopologyTemplateService} from "app/ng2/services/component-services/topology-template.service";
33 import {InstanceFeDetails} from "../../../../models/instance-fe-details";
34 import {ToscaGetFunction} from "../../../../models/tosca-get-function";
35 import {ToscaFunctionValidationEvent} from "../../../../ng2/pages/properties-assignment/tosca-function/tosca-function.component";
37 export interface IEditPropertyModel {
38 property:PropertyModel;
40 simpleTypes:Array<string>;
41 hasGetFunctionValue: boolean;
42 isGetFunctionValid: boolean;
45 interface IPropertyFormViewModelScope extends ng.IScope {
47 editForm:ng.IFormController;
48 footerButtons:Array<any>;
51 componentMetadata: { isService: boolean, isVfc: boolean }
52 validationPattern:RegExp;
53 propertyNameValidationPattern:RegExp;
54 commentValidationPattern:RegExp;
55 editPropertyModel: IEditPropertyModel;
56 componentInstanceMap: Map<string, InstanceFeDetails>;
57 modalInstanceProperty:ng.ui.bootstrap.IModalServiceInstance;
58 currentPropertyIndex:number;
59 isLastProperty:boolean;
61 nonPrimitiveTypes:Array<string>;
62 dataTypes:DataTypesMap;
63 isTypeDataType:boolean;
66 isPropertyValueOwner:boolean;
67 isVnfConfiguration:boolean;
69 modelNameFilter:string;
70 isGetFunctionValueType: boolean;
72 validateJson(json:string):boolean;
73 save(doNotCloseModal?:boolean):void;
74 getValidationPattern(type:string):RegExp;
75 validateIntRange(value:string):boolean;
78 onSchemaTypeChange():void;
79 onTypeChange(resetSchema:boolean):void;
81 delete(property:PropertyModel):void;
84 isSimpleType(typeName:string):boolean;
85 getDefaultValue():any;
86 onValueTypeChange(): void;
89 export class PropertyFormViewModel {
93 'Sdc.Services.DataTypesService',
97 'PropertyNameValidationPattern',
98 'CommentValidationPattern',
103 'filteredProperties',
106 'isPropertyValueOwner',
109 'ComponentInstanceServiceNg2',
110 'TopologyTemplateService',
111 'CompositionService',
115 private formState:FormState;
117 constructor(private $scope:IPropertyFormViewModelScope,
118 private DataTypesService:DataTypesService,
119 private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
120 private property:PropertyModel,
121 private ValidationPattern:RegExp,
122 private PropertyNameValidationPattern:RegExp,
123 private CommentValidationPattern:RegExp,
124 private ValidationUtils:ValidationUtils,
125 // private component:Component,
126 private $filter:ng.IFilterService,
127 private modalService:SdcUiServices.ModalService,
128 private filteredProperties:Array<PropertyModel>,
129 private $timeout:ng.ITimeoutService,
130 private isViewOnly:boolean,
131 private isPropertyValueOwner:boolean,
132 private propertyOwnerType:string,
133 private propertyOwnerId:string,
134 private ComponentInstanceServiceNg2: ComponentInstanceServiceNg2,
135 private topologyTemplateService: TopologyTemplateService,
136 private compositionService: CompositionService,
137 private workspaceService: WorkspaceService) {
139 this.formState = angular.isDefined(property.name) ? FormState.UPDATE : FormState.CREATE;
143 private initResource = ():void => {
144 this.$scope.editPropertyModel.property = new PropertyModel(this.property);
145 this.$scope.editPropertyModel.property.type = this.property.type ? this.property.type : null;
146 this.$scope.constraints = this.property.constraints && this.property.constraints[0] ? this.property.constraints[0]["validValues"] : null;
147 this.initToscaGetFunction();
151 private initToscaGetFunction() {
152 this.$scope.editPropertyModel.hasGetFunctionValue = this.$scope.editPropertyModel.property.isToscaFunction();
153 this.$scope.editPropertyModel.isGetFunctionValid = true;
156 private initForNotSimpleType = ():void => {
157 const property = this.$scope.editPropertyModel.property;
158 this.$scope.isTypeDataType = this.DataTypesService.isDataTypeForPropertyType(this.$scope.editPropertyModel.property);
159 if (property.isToscaFunction()) {
160 this.initValueForGetFunction();
164 if (this.isComplexType(property.type)) {
165 if (property.value || property.defaultValue) {
166 this.$scope.myValue = JSON.parse(property.value || property.defaultValue);
168 this.initEmptyComplexValue(property.type);
173 private initValueForGetFunction(): void {
174 const property = this.$scope.editPropertyModel.property;
175 if (property.defaultValue) {
176 this.$scope.myValue = JSON.parse(property.defaultValue);
179 if (this.isComplexType(property.type)) {
180 this.initEmptyComplexValue(property.type);
184 this.$scope.myValue = undefined;
187 private initComponentInstanceMap() {
188 this.$scope.componentInstanceMap = new Map<string, InstanceFeDetails>();
189 if (this.compositionService.componentInstances) {
190 this.compositionService.componentInstances.forEach(value => {
191 this.$scope.componentInstanceMap.set(value.uniqueId, <InstanceFeDetails>{
198 private initEmptyComplexValue(type: string): any {
200 case PROPERTY_TYPES.MAP:
201 this.$scope.myValue = {'': null};
203 case PROPERTY_TYPES.LIST:
204 this.$scope.myValue = [];
207 this.$scope.myValue = {};
211 private isComplexType(type: string): boolean {
215 return PROPERTY_DATA.SIMPLE_TYPES.indexOf(type) == -1;
218 private setMaxLength = ():void => {
219 switch (this.$scope.editPropertyModel.property.type) {
220 case PROPERTY_TYPES.MAP:
221 case PROPERTY_TYPES.LIST:
222 this.$scope.maxLength = this.$scope.editPropertyModel.property.schema.property.type == PROPERTY_TYPES.JSON ?
223 PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH :
224 PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
226 case PROPERTY_TYPES.JSON:
227 this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH;
230 this.$scope.maxLength =PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
235 private initScope = ():void => {
238 this.$scope.isViewOnly = this.isViewOnly;
239 this.$scope.isLoading = true;
240 this.$scope.forms = {};
241 this.$scope.validationPattern = this.ValidationPattern;
242 this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
243 this.$scope.commentValidationPattern = this.CommentValidationPattern;
244 this.$scope.isNew = (this.formState === FormState.CREATE);
245 this.$scope.componentMetadata = {
246 isService: this.workspaceService.metadata.isService(),
247 isVfc: this.workspaceService.metadata.isVfc()
249 this.$scope.modalInstanceProperty = this.$uibModalInstance;
250 this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, i=> i.name == this.property.name);
251 this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
252 const property = new PropertyModel(this.property);
253 this.$scope.editPropertyModel = {
254 'property': property,
255 types: PROPERTY_DATA.TYPES,
256 simpleTypes: PROPERTY_DATA.SIMPLE_TYPES,
257 hasGetFunctionValue: property.isToscaFunction(),
258 isGetFunctionValid: true,
260 this.$scope.isPropertyValueOwner = this.isPropertyValueOwner;
261 this.$scope.propertyOwnerType = this.propertyOwnerType;
262 this.$scope.modelNameFilter = this.workspaceService.metadata.model;
263 //check if property of VnfConfiguration
264 this.$scope.isVnfConfiguration = false;
265 if(this.propertyOwnerType == "component" && angular.isArray(this.compositionService.componentInstances)) {
266 const componentPropertyOwner:ComponentInstance = this.compositionService.componentInstances.find((ci:ComponentInstance) => {
267 return ci.uniqueId === this.property.resourceInstanceUniqueId;
269 if (componentPropertyOwner && componentPropertyOwner.componentName === 'vnfConfiguration') {
270 this.$scope.isVnfConfiguration = true;
274 this.initForNotSimpleType();
275 this.initComponentInstanceMap();
277 this.$scope.validateJson = (json:string):boolean => {
281 return this.ValidationUtils.validateJson(json);
284 this.DataTypesService.fetchDataTypesByModel(this.workspaceService.metadata.model).then(response => {
285 this.$scope.dataTypes = response.data as DataTypesMap;
286 this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
287 return this.$scope.editPropertyModel.types.indexOf(type) == -1;
290 this.$scope.isLoading = false;
294 this.$scope.save = (doNotCloseModal?:boolean):void => {
295 let property:PropertyModel = this.$scope.editPropertyModel.property;
296 this.$scope.editPropertyModel.property.description = this.ValidationUtils.stripAndSanitize(this.$scope.editPropertyModel.property.description);
297 //if read only - or no changes made - just closes the modal
298 //need to check for property.value changes manually to detect if map properties deleted
299 if ((this.$scope.editPropertyModel.property.readonly && !this.$scope.isPropertyValueOwner)
300 || (!this.$scope.forms.editForm.$dirty && angular.equals(JSON.stringify(this.$scope.myValue), this.$scope.editPropertyModel.property.value))) {
301 this.$uibModalInstance.close();
305 this.$scope.isLoading = true;
307 let onPropertyFailure = (response):void => {
308 console.error('Failed to update property', response);
309 this.$scope.isLoading = false;
312 let onPropertySuccess = (propertyFromBE:PropertyModel):void => {
313 this.$scope.isLoading = false;
314 this.filteredProperties[this.$scope.currentPropertyIndex] = propertyFromBE;
315 if (!doNotCloseModal) {
316 this.$uibModalInstance.close(propertyFromBE);
318 this.$scope.forms.editForm.$setPristine();
319 this.$scope.editPropertyModel.property = new PropertyModel();
323 //Not clean, but doing this as a temporary fix until we update the property right panel modals
324 if (this.propertyOwnerType === "group"){
325 this.ComponentInstanceServiceNg2.updateComponentGroupInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
326 .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
327 } else if (this.propertyOwnerType === "policy"){
328 if (!this.$scope.editPropertyModel.property.simpleType &&
329 !this.$scope.isSimpleType(this.$scope.editPropertyModel.property.type) &&
330 !_.isNil(this.$scope.myValue)) {
331 property.value = JSON.stringify(this.$scope.myValue);
333 this.ComponentInstanceServiceNg2.updateComponentPolicyInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
334 .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
336 //in case we have uniqueId we call update method
337 if (this.$scope.isPropertyValueOwner) {
338 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
339 property.value = JSON.stringify(this.$scope.myValue);
341 this.updateInstanceProperties(property.resourceInstanceUniqueId, [property]).subscribe((propertiesFromBE) => onPropertySuccess(propertiesFromBE[0]),
342 error => onPropertyFailure(error));
344 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
345 property.defaultValue = JSON.stringify(this.$scope.myValue);
347 this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.value;
349 this.addOrUpdateProperty(property).subscribe(onPropertySuccess, error => onPropertyFailure(error));
354 this.$scope.getPrev = ():void=> {
355 this.property = this.filteredProperties[--this.$scope.currentPropertyIndex];
357 this.initForNotSimpleType();
358 this.$scope.isLastProperty = false;
361 this.$scope.getNext = ():void=> {
362 this.property = this.filteredProperties[++this.$scope.currentPropertyIndex];
364 this.initForNotSimpleType();
365 this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
368 this.$scope.isSimpleType = (typeName:string):boolean=> {
369 return typeName && this.$scope.editPropertyModel.simpleTypes.indexOf(typeName) != -1;
372 this.$scope.showSchema = ():boolean => {
373 return [PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP].indexOf(this.$scope.editPropertyModel.property.type) > -1;
376 this.$scope.getValidationPattern = (type:string):RegExp => {
377 return this.ValidationUtils.getValidationPattern(type);
380 this.$scope.validateIntRange = (value:string):boolean => {
381 return !value || this.ValidationUtils.validateIntRange(value);
384 this.$scope.close = ():void => {
385 this.$uibModalInstance.close();
388 // put default value when instance value is empty
389 this.$scope.onValueChange = ():void => {
390 if (!this.$scope.editPropertyModel.property.value) {
391 if (this.$scope.isPropertyValueOwner) {
392 this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.defaultValue;
397 // Add the done button at the footer.
398 this.$scope.footerButtons = [
399 {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save},
400 {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
403 this.$scope.$watch("forms.editForm.$invalid", (newVal) => {
404 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
405 this.$scope.footerButtons[0].disabled = newVal || !this.$scope.editPropertyModel.property.toscaFunction || this.isViewOnly;
407 this.$scope.footerButtons[0].disabled = newVal || this.isViewOnly;
411 this.$scope.$watch("forms.editForm.$valid", (newVal) => {
412 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
413 this.$scope.footerButtons[0].disabled = !newVal || !this.$scope.editPropertyModel.property.toscaFunction || this.isViewOnly;
415 this.$scope.footerButtons[0].disabled = !newVal || this.isViewOnly;
419 this.$scope.getDefaultValue = ():any => {
420 return this.$scope.isPropertyValueOwner ? this.$scope.editPropertyModel.property.defaultValue : null;
423 this.$scope.onTypeChange = ():void => {
424 this.$scope.editPropertyModel.property.value = '';
425 this.$scope.editPropertyModel.property.defaultValue = '';
427 this.initForNotSimpleType();
430 this.$scope.onSchemaTypeChange = ():void => {
431 if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.MAP) {
432 this.$scope.myValue = {};
433 } else if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.LIST) {
434 this.$scope.myValue = [];
439 this.$scope.delete = (property:PropertyModel):void => {
440 let onOk: Function = ():void => {
441 this.deleteProperty(property.uniqueId).subscribe(
445 let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
446 let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
447 const okButton = {testId: "OK", text: "OK", type: SdcUiCommon.ButtonType.info, callback: onOk, closeModal: true} as SdcUiComponents.ModalButtonComponent;
448 this.modalService.openInfoModal(title, message, 'delete-modal', [okButton]);
451 this.$scope.onValueTypeChange = (): void => {
452 this.setEmptyValue();
453 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
454 this.$scope.editPropertyModel.isGetFunctionValid = undefined;
456 this.$scope.editPropertyModel.property.toscaFunction = undefined;
457 this.$scope.editPropertyModel.isGetFunctionValid = true;
461 this.$scope.onGetFunctionValidFunction = (toscaGetFunction: ToscaGetFunction): void => {
462 this.$scope.editPropertyModel.property.toscaFunction = toscaGetFunction;
465 this.$scope.onToscaFunctionValidityChange = (validationEvent: ToscaFunctionValidationEvent): void => {
466 if (validationEvent.isValid) {
467 this.$scope.editPropertyModel.isGetFunctionValid = true;
470 this.$scope.editPropertyModel.isGetFunctionValid = undefined;
475 private setEmptyValue() {
476 const property1 = this.$scope.editPropertyModel.property;
477 property1.value = undefined;
478 if (this.isComplexType(property1.type)) {
479 this.initEmptyComplexValue(property1.type);
482 this.$scope.myValue = '';
485 private updateInstanceProperties = (componentInstanceId:string, properties:PropertyModel[]):Observable<PropertyModel[]> => {
487 return this.ComponentInstanceServiceNg2.updateInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, componentInstanceId, properties)
488 .map(newProperties => {
489 newProperties.forEach((newProperty) => {
490 if (!_.isNil(newProperty.path)) {
491 if (newProperty.path[0] === newProperty.resourceInstanceUniqueId) newProperty.path.shift();
492 // find exist instance property in parent component for update the new value ( find bu uniqueId & path)
493 let existProperty: PropertyModel = <PropertyModel>_.find(this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId], {
494 uniqueId: newProperty.uniqueId,
495 path: newProperty.path
497 let index = this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId].indexOf(existProperty);
498 this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId][index] = newProperty;
501 return newProperties;
505 private addOrUpdateProperty = (property: PropertyModel): Observable<PropertyModel> => {
506 if (!property.uniqueId) {
507 let onSuccess = (newProperty: PropertyModel): PropertyModel => {
508 this.filteredProperties.push(newProperty);
511 return this.topologyTemplateService.addProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property)
514 let onSuccess = (newProperty: PropertyModel): PropertyModel => {
515 // find exist instance property in parent component for update the new value ( find bu uniqueId )
516 let existProperty: PropertyModel = <PropertyModel>_.find(this.filteredProperties, {uniqueId: newProperty.uniqueId});
517 let propertyIndex = this.filteredProperties.indexOf(existProperty);
518 this.filteredProperties[propertyIndex] = newProperty;
521 return this.topologyTemplateService.updateProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property).map(onSuccess);
525 public deleteProperty = (propertyId:string):Observable<void> => {
526 let onSuccess = ():void => {
527 console.debug("Property deleted");
528 delete _.remove(this.filteredProperties, {uniqueId: propertyId})[0];
530 let onFailed = ():void => {
531 console.debug("Failed to delete property");
533 return this.topologyTemplateService.deleteProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, propertyId).map(onSuccess, onFailed);