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>;
52 componentMetadata: { isService: boolean, isVfc: boolean }
53 validationPattern:RegExp;
54 propertyNameValidationPattern:RegExp;
55 commentValidationPattern:RegExp;
56 editPropertyModel: IEditPropertyModel;
57 componentInstanceMap: Map<string, InstanceFeDetails>;
58 modalInstanceProperty:ng.ui.bootstrap.IModalServiceInstance;
59 currentPropertyIndex:number;
60 isLastProperty:boolean;
62 nonPrimitiveTypes:Array<string>;
63 dataTypes:DataTypesMap;
64 isTypeDataType:boolean;
67 isPropertyValueOwner:boolean;
68 isVnfConfiguration:boolean;
70 modelNameFilter:string;
71 isGetFunctionValueType: boolean;
72 invalidMandatoryFields: boolean;
74 validateJson(json:string):boolean;
75 save(doNotCloseModal?:boolean):void;
76 getValidationPattern(type:string):RegExp;
77 validateIntRange(value:string):boolean;
80 onSchemaTypeChange():void;
81 onTypeChange(resetSchema:boolean):void;
83 delete(property:PropertyModel):void;
86 isSimpleType(typeName:string):boolean;
87 getDefaultValue():any;
88 onValueTypeChange(): void;
91 export class PropertyFormViewModel {
95 'Sdc.Services.DataTypesService',
99 'PropertyNameValidationPattern',
100 'CommentValidationPattern',
105 'filteredProperties',
108 'isPropertyValueOwner',
111 'ComponentInstanceServiceNg2',
112 'TopologyTemplateService',
113 'CompositionService',
117 private formState:FormState;
119 constructor(private $scope:IPropertyFormViewModelScope,
120 private DataTypesService:DataTypesService,
121 private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
122 private property:PropertyModel,
123 private ValidationPattern:RegExp,
124 private PropertyNameValidationPattern:RegExp,
125 private CommentValidationPattern:RegExp,
126 private ValidationUtils:ValidationUtils,
127 // private component:Component,
128 private $filter:ng.IFilterService,
129 private modalService:SdcUiServices.ModalService,
130 private filteredProperties:Array<PropertyModel>,
131 private $timeout:ng.ITimeoutService,
132 private isViewOnly:boolean,
133 private isPropertyValueOwner:boolean,
134 private propertyOwnerType:string,
135 private propertyOwnerId:string,
136 private ComponentInstanceServiceNg2: ComponentInstanceServiceNg2,
137 private topologyTemplateService: TopologyTemplateService,
138 private compositionService: CompositionService,
139 private workspaceService: WorkspaceService) {
141 this.formState = angular.isDefined(property.name) ? FormState.UPDATE : FormState.CREATE;
145 private initResource = ():void => {
146 this.$scope.editPropertyModel.property = new PropertyModel(this.property);
147 this.$scope.editPropertyModel.property.type = this.property.type ? this.property.type : null;
148 this.$scope.constraints = this.property.constraints && this.property.constraints[0] ? this.property.constraints[0]["validValues"] : null;
149 this.initToscaGetFunction();
153 private initToscaGetFunction() {
154 this.$scope.editPropertyModel.hasGetFunctionValue = this.$scope.editPropertyModel.property.isToscaFunction();
155 this.$scope.editPropertyModel.isGetFunctionValid = true;
158 private isDataTypeForPropertyType = (property:PropertyModel):boolean=> {
159 property.simpleType = "";
160 if (property.type && PROPERTY_DATA.TYPES.indexOf(property.type) > -1) {
163 let simpleType = this.getTypeForDataTypeDerivedFromSimple(property.type);
165 property.simpleType = simpleType;
171 private getTypeForDataTypeDerivedFromSimple = (dataTypeName:string):string => {
172 if (!this.$scope.dataTypes[dataTypeName]) {
175 if (this.$scope.dataTypes[dataTypeName].derivedFromName == "tosca.datatypes.Root" || this.$scope.dataTypes[dataTypeName].properties) {
178 if (PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.$scope.dataTypes[dataTypeName].derivedFromName) > -1) {
179 return this.$scope.dataTypes[dataTypeName].derivedFromName
181 return this.getTypeForDataTypeDerivedFromSimple(this.$scope.dataTypes[dataTypeName].derivedFromName);
184 private initForNotSimpleType = ():void => {
185 const property = this.$scope.editPropertyModel.property;
186 this.$scope.isTypeDataType = this.isDataTypeForPropertyType(this.$scope.editPropertyModel.property);
187 if (property.isToscaFunction()) {
188 this.initValueForGetFunction();
192 if (this.isComplexType(property.type)) {
193 if (property.value || property.defaultValue) {
194 this.$scope.myValue = JSON.parse(property.value || property.defaultValue);
196 this.initEmptyComplexValue(property.type);
201 private initValueForGetFunction(): void {
202 const property = this.$scope.editPropertyModel.property;
203 if (property.defaultValue) {
204 this.$scope.myValue = JSON.parse(property.defaultValue);
207 if (this.isComplexType(property.type)) {
208 this.initEmptyComplexValue(property.type);
212 this.$scope.myValue = undefined;
215 private initComponentInstanceMap() {
216 this.$scope.componentInstanceMap = new Map<string, InstanceFeDetails>();
217 if (this.compositionService.componentInstances) {
218 this.compositionService.componentInstances.forEach(value => {
219 this.$scope.componentInstanceMap.set(value.uniqueId, <InstanceFeDetails>{
226 private initEmptyComplexValue(type: string): any {
228 case PROPERTY_TYPES.MAP:
229 this.$scope.myValue = {'': null};
231 case PROPERTY_TYPES.LIST:
232 this.$scope.myValue = [];
235 this.$scope.myValue = {};
239 private isComplexType(type: string): boolean {
243 return PROPERTY_DATA.SIMPLE_TYPES.indexOf(type) == -1;
246 private setMaxLength = ():void => {
247 switch (this.$scope.editPropertyModel.property.type) {
248 case PROPERTY_TYPES.MAP:
249 case PROPERTY_TYPES.LIST:
250 this.$scope.maxLength = this.$scope.editPropertyModel.property.schema.property.type == PROPERTY_TYPES.JSON ?
251 PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH :
252 PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
254 case PROPERTY_TYPES.JSON:
255 this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH;
258 this.$scope.maxLength =PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
263 private initScope = ():void => {
266 this.$scope.isViewOnly = this.isViewOnly;
267 this.$scope.isLoading = true;
268 this.$scope.forms = {};
269 this.$scope.validationPattern = this.ValidationPattern;
270 this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
271 this.$scope.commentValidationPattern = this.CommentValidationPattern;
272 this.$scope.nameMaxLength = PROPERTY_VALUE_CONSTRAINTS.NAME_MAX_LENGTH;
273 this.$scope.isNew = (this.formState === FormState.CREATE);
274 this.$scope.componentMetadata = {
275 isService: this.workspaceService.metadata.isService(),
276 isVfc: this.workspaceService.metadata.isVfc()
278 this.$scope.modalInstanceProperty = this.$uibModalInstance;
279 this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, i=> i.name == this.property.name);
280 this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
281 const property = new PropertyModel(this.property);
282 this.$scope.editPropertyModel = {
283 'property': property,
284 types: PROPERTY_DATA.TYPES,
285 simpleTypes: PROPERTY_DATA.SIMPLE_TYPES,
286 hasGetFunctionValue: property.isToscaFunction(),
287 isGetFunctionValid: true,
289 this.$scope.isPropertyValueOwner = this.isPropertyValueOwner;
290 this.$scope.propertyOwnerType = this.propertyOwnerType;
291 this.$scope.modelNameFilter = this.workspaceService.metadata.model;
292 //check if property of VnfConfiguration
293 this.$scope.isVnfConfiguration = false;
294 if(this.propertyOwnerType == "component" && angular.isArray(this.compositionService.componentInstances)) {
295 const componentPropertyOwner:ComponentInstance = this.compositionService.componentInstances.find((ci:ComponentInstance) => {
296 return ci.uniqueId === this.property.resourceInstanceUniqueId;
298 if (componentPropertyOwner && componentPropertyOwner.componentName === 'vnfConfiguration') {
299 this.$scope.isVnfConfiguration = true;
303 this.initComponentInstanceMap();
305 this.$scope.validateJson = (json:string):boolean => {
309 return this.ValidationUtils.validateJson(json);
312 this.DataTypesService.fetchDataTypesByModel(this.workspaceService.metadata.model).then(response => {
313 this.$scope.dataTypes = response.data as DataTypesMap;
315 this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
316 return this.$scope.editPropertyModel.types.indexOf(type) == -1;
318 this.initForNotSimpleType();
319 this.$scope.isLoading = false;
323 this.$scope.save = (doNotCloseModal?:boolean):void => {
324 let property:PropertyModel = this.$scope.editPropertyModel.property;
325 this.$scope.editPropertyModel.property.description = this.ValidationUtils.stripAndSanitize(this.$scope.editPropertyModel.property.description);
326 //if read only - or no changes made - just closes the modal
327 //need to check for property.value changes manually to detect if map properties deleted
328 if ((this.$scope.editPropertyModel.property.readonly && !this.$scope.isPropertyValueOwner)
329 || (!this.$scope.forms.editForm.$dirty && angular.equals(JSON.stringify(this.$scope.myValue), this.$scope.editPropertyModel.property.value))) {
330 this.$uibModalInstance.close();
334 this.$scope.isLoading = true;
336 let onPropertyFailure = (response):void => {
337 console.error('Failed to update property', response);
338 this.$scope.isLoading = false;
341 let onPropertySuccess = (propertyFromBE:PropertyModel):void => {
342 this.$scope.isLoading = false;
343 this.filteredProperties[this.$scope.currentPropertyIndex] = propertyFromBE;
344 if (!doNotCloseModal) {
345 this.$uibModalInstance.close(propertyFromBE);
347 this.$scope.forms.editForm.$setPristine();
348 this.$scope.editPropertyModel.property = new PropertyModel();
352 //Not clean, but doing this as a temporary fix until we update the property right panel modals
353 if (this.propertyOwnerType === "group"){
354 this.ComponentInstanceServiceNg2.updateComponentGroupInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
355 .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
356 } else if (this.propertyOwnerType === "policy"){
357 if (!this.$scope.editPropertyModel.property.simpleType &&
358 !this.$scope.isSimpleType(this.$scope.editPropertyModel.property.type) &&
359 !_.isNil(this.$scope.myValue)) {
360 property.value = JSON.stringify(this.$scope.myValue);
362 this.ComponentInstanceServiceNg2.updateComponentPolicyInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
363 .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
365 //in case we have uniqueId we call update method
366 if (this.$scope.isPropertyValueOwner) {
367 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
368 property.value = JSON.stringify(this.$scope.myValue);
370 this.updateInstanceProperties(property.resourceInstanceUniqueId, [property]).subscribe((propertiesFromBE) => onPropertySuccess(propertiesFromBE[0]),
371 error => onPropertyFailure(error));
373 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
374 property.defaultValue = JSON.stringify(this.$scope.myValue);
376 this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.value;
378 this.addOrUpdateProperty(property).subscribe(onPropertySuccess, error => onPropertyFailure(error));
383 this.$scope.getPrev = ():void=> {
384 this.property = this.filteredProperties[--this.$scope.currentPropertyIndex];
386 this.initForNotSimpleType();
387 this.$scope.isLastProperty = false;
390 this.$scope.getNext = ():void=> {
391 this.property = this.filteredProperties[++this.$scope.currentPropertyIndex];
393 this.initForNotSimpleType();
394 this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
397 this.$scope.isSimpleType = (typeName:string):boolean=> {
398 return typeName && this.$scope.editPropertyModel.simpleTypes.indexOf(typeName) != -1;
401 this.$scope.showSchema = ():boolean => {
402 return [PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP].indexOf(this.$scope.editPropertyModel.property.type) > -1;
405 this.$scope.getValidationPattern = (type:string):RegExp => {
406 return this.ValidationUtils.getValidationPattern(type);
409 this.$scope.validateIntRange = (value:string):boolean => {
410 return !value || this.ValidationUtils.validateIntRange(value);
413 this.$scope.close = ():void => {
414 this.$uibModalInstance.close();
417 // put default value when instance value is empty
418 this.$scope.onValueChange = ():void => {
419 if (!this.$scope.editPropertyModel.property.value) {
420 if (this.$scope.isPropertyValueOwner) {
421 this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.defaultValue;
426 // Add the done button at the footer.
427 this.$scope.footerButtons = [
428 {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save},
429 {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
432 this.$scope.$watch("forms.editForm.$invalid", (newVal) => {
433 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
434 this.$scope.invalidMandatoryFields = !newVal || !this.$scope.editPropertyModel.property.toscaFunction || this.isViewOnly;
435 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
437 this.$scope.invalidMandatoryFields = !newVal || this.isViewOnly;
438 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
442 this.$scope.$watch("forms.editForm.$valid", (newVal) => {
443 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
444 this.$scope.invalidMandatoryFields = !newVal || !this.$scope.editPropertyModel.property.toscaFunction || this.isViewOnly;
445 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
447 this.$scope.invalidMandatoryFields = !newVal || this.isViewOnly;
448 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
452 this.$scope.getDefaultValue = ():any => {
453 return this.$scope.isPropertyValueOwner ? this.$scope.editPropertyModel.property.defaultValue : null;
456 this.$scope.onTypeChange = ():void => {
457 this.$scope.editPropertyModel.property.value = '';
458 this.$scope.editPropertyModel.property.defaultValue = '';
460 this.initForNotSimpleType();
463 this.$scope.onSchemaTypeChange = ():void => {
464 if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.MAP) {
465 this.$scope.myValue = {};
466 } else if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.LIST) {
467 this.$scope.myValue = [];
472 this.$scope.delete = (property:PropertyModel):void => {
473 let onOk: Function = ():void => {
474 this.deleteProperty(property.uniqueId).subscribe(
478 let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
479 let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
480 const okButton = {testId: "OK", text: "OK", type: SdcUiCommon.ButtonType.info, callback: onOk, closeModal: true} as SdcUiComponents.ModalButtonComponent;
481 this.modalService.openInfoModal(title, message, 'delete-modal', [okButton]);
484 this.$scope.onValueTypeChange = (): void => {
485 this.setEmptyValue();
486 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
487 this.$scope.editPropertyModel.isGetFunctionValid = undefined;
489 this.$scope.editPropertyModel.property.toscaFunction = undefined;
490 this.$scope.editPropertyModel.isGetFunctionValid = true;
494 this.$scope.onConstraintChange = (constraints: any): void => {
495 if (!this.$scope.invalidMandatoryFields) {
496 this.$scope.footerButtons[0].disabled = !constraints.valid;
498 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
500 if (!constraints.constraints || constraints.constraints.length == 0) {
501 this.$scope.editPropertyModel.property.propertyConstraints = null;
502 this.$scope.editPropertyModel.property.constraints = null;
505 this.$scope.editPropertyModel.property.propertyConstraints = this.serializePropertyConstraints(constraints.constraints);
506 this.$scope.editPropertyModel.property.constraints = constraints.constraints;
509 this.$scope.onGetFunctionValidFunction = (toscaGetFunction: ToscaGetFunction): void => {
510 this.$scope.editPropertyModel.property.toscaFunction = toscaGetFunction;
513 this.$scope.onToscaFunctionValidityChange = (validationEvent: ToscaFunctionValidationEvent): void => {
514 if (validationEvent.isValid) {
515 this.$scope.editPropertyModel.isGetFunctionValid = true;
518 this.$scope.editPropertyModel.isGetFunctionValid = undefined;
522 private serializePropertyConstraints(constraints: any[]): string[] {
524 let stringConstrsints = new Array();
525 constraints.forEach((constraint) => {
526 stringConstrsints.push(JSON.stringify(constraint));
528 return stringConstrsints;
533 private setEmptyValue() {
534 const property1 = this.$scope.editPropertyModel.property;
535 property1.value = undefined;
536 if (this.isComplexType(property1.type)) {
537 this.initEmptyComplexValue(property1.type);
540 this.$scope.myValue = '';
543 private updateInstanceProperties = (componentInstanceId:string, properties:PropertyModel[]):Observable<PropertyModel[]> => {
545 return this.ComponentInstanceServiceNg2.updateInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, componentInstanceId, properties)
546 .map(newProperties => {
547 newProperties.forEach((newProperty) => {
548 if (!_.isNil(newProperty.path)) {
549 if (newProperty.path[0] === newProperty.resourceInstanceUniqueId) newProperty.path.shift();
550 // find exist instance property in parent component for update the new value ( find bu uniqueId & path)
551 let existProperty: PropertyModel = <PropertyModel>_.find(this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId], {
552 uniqueId: newProperty.uniqueId,
553 path: newProperty.path
555 let index = this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId].indexOf(existProperty);
556 this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId][index] = newProperty;
559 return newProperties;
563 private addOrUpdateProperty = (property: PropertyModel): Observable<PropertyModel> => {
564 if (!property.uniqueId) {
565 let onSuccess = (newProperty: PropertyModel): PropertyModel => {
566 this.filteredProperties.push(newProperty);
569 return this.topologyTemplateService.addProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property)
572 let onSuccess = (newProperty: PropertyModel): PropertyModel => {
573 // find exist instance property in parent component for update the new value ( find bu uniqueId )
574 let existProperty: PropertyModel = <PropertyModel>_.find(this.filteredProperties, {uniqueId: newProperty.uniqueId});
575 let propertyIndex = this.filteredProperties.indexOf(existProperty);
576 this.filteredProperties[propertyIndex] = newProperty;
579 return this.topologyTemplateService.updateProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property).map(onSuccess);
583 public deleteProperty = (propertyId:string):Observable<void> => {
584 let onSuccess = ():void => {
585 console.debug("Property deleted");
586 delete _.remove(this.filteredProperties, {uniqueId: propertyId})[0];
588 let onFailed = ():void => {
589 console.debug("Failed to delete property");
591 return this.topologyTemplateService.deleteProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, propertyId).map(onSuccess, onFailed);