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";
36 export interface IEditPropertyModel {
37 property:PropertyModel;
39 simpleTypes:Array<string>;
40 hasGetFunctionValue: boolean;
41 isGetFunctionValid: boolean;
44 interface IPropertyFormViewModelScope extends ng.IScope {
46 editForm:ng.IFormController;
47 footerButtons:Array<any>;
50 componentMetadata: { isService: boolean, isVfc: boolean }
51 validationPattern:RegExp;
52 propertyNameValidationPattern:RegExp;
53 commentValidationPattern:RegExp;
54 editPropertyModel: IEditPropertyModel;
55 componentInstanceMap: Map<string, InstanceFeDetails>;
56 modalInstanceProperty:ng.ui.bootstrap.IModalServiceInstance;
57 currentPropertyIndex:number;
58 isLastProperty:boolean;
60 nonPrimitiveTypes:Array<string>;
61 dataTypes:DataTypesMap;
62 isTypeDataType:boolean;
64 isPropertyValueOwner:boolean;
65 isVnfConfiguration:boolean;
67 modelNameFilter:string;
68 isGetFunctionValueType: boolean;
70 validateJson(json:string):boolean;
71 save(doNotCloseModal?:boolean):void;
72 getValidationPattern(type:string):RegExp;
73 validateIntRange(value:string):boolean;
76 onSchemaTypeChange():void;
77 onTypeChange(resetSchema:boolean):void;
79 delete(property:PropertyModel):void;
82 isSimpleType(typeName:string):boolean;
83 getDefaultValue():any;
84 onValueTypeChange(): void;
87 export class PropertyFormViewModel {
91 'Sdc.Services.DataTypesService',
95 'PropertyNameValidationPattern',
96 'CommentValidationPattern',
101 'filteredProperties',
103 'isPropertyValueOwner',
106 'ComponentInstanceServiceNg2',
107 'TopologyTemplateService',
108 'CompositionService',
112 private formState:FormState;
114 constructor(private $scope:IPropertyFormViewModelScope,
115 private DataTypesService:DataTypesService,
116 private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
117 private property:PropertyModel,
118 private ValidationPattern:RegExp,
119 private PropertyNameValidationPattern:RegExp,
120 private CommentValidationPattern:RegExp,
121 private ValidationUtils:ValidationUtils,
122 // private component:Component,
123 private $filter:ng.IFilterService,
124 private modalService:SdcUiServices.ModalService,
125 private filteredProperties:Array<PropertyModel>,
126 private $timeout:ng.ITimeoutService,
127 private isPropertyValueOwner:boolean,
128 private propertyOwnerType:string,
129 private propertyOwnerId:string,
130 private ComponentInstanceServiceNg2: ComponentInstanceServiceNg2,
131 private topologyTemplateService: TopologyTemplateService,
132 private compositionService: CompositionService,
133 private workspaceService: WorkspaceService) {
135 this.formState = angular.isDefined(property.name) ? FormState.UPDATE : FormState.CREATE;
139 private initResource = ():void => {
140 this.$scope.editPropertyModel.property = new PropertyModel(this.property);
141 this.$scope.editPropertyModel.property.type = this.property.type ? this.property.type : null;
142 this.$scope.constraints = this.property.constraints && this.property.constraints[0] ? this.property.constraints[0]["validValues"] : null;
143 this.initToscaGetFunction();
147 private initToscaGetFunction() {
148 this.$scope.editPropertyModel.hasGetFunctionValue = this.$scope.editPropertyModel.property.isToscaGetFunction();
149 this.$scope.editPropertyModel.isGetFunctionValid = true;
152 private initForNotSimpleType = ():void => {
153 const property = this.$scope.editPropertyModel.property;
154 this.$scope.isTypeDataType = this.DataTypesService.isDataTypeForPropertyType(this.$scope.editPropertyModel.property);
155 if (property.isToscaGetFunction()) {
156 this.initValueForGetFunction();
160 if (this.isComplexType(property.type)) {
161 if (property.value || property.defaultValue) {
162 this.$scope.myValue = JSON.parse(property.value || property.defaultValue);
164 this.initEmptyComplexValue(property.type);
169 private initValueForGetFunction(): void {
170 const property = this.$scope.editPropertyModel.property;
171 if (property.defaultValue) {
172 this.$scope.myValue = JSON.parse(property.defaultValue);
175 if (this.isComplexType(property.type)) {
176 this.initEmptyComplexValue(property.type);
180 this.$scope.myValue = undefined;
183 private initComponentInstanceMap() {
184 this.$scope.componentInstanceMap = new Map<string, InstanceFeDetails>();
185 if (this.compositionService.componentInstances) {
186 this.compositionService.componentInstances.forEach(value => {
187 this.$scope.componentInstanceMap.set(value.uniqueId, <InstanceFeDetails>{
194 private initEmptyComplexValue(type: string): any {
196 case PROPERTY_TYPES.MAP:
197 this.$scope.myValue = {'': null};
199 case PROPERTY_TYPES.LIST:
200 this.$scope.myValue = [];
203 this.$scope.myValue = {};
207 private isComplexType(type: string): boolean {
211 return PROPERTY_DATA.SIMPLE_TYPES.indexOf(type) == -1;
214 private setMaxLength = ():void => {
215 switch (this.$scope.editPropertyModel.property.type) {
216 case PROPERTY_TYPES.MAP:
217 case PROPERTY_TYPES.LIST:
218 this.$scope.maxLength = this.$scope.editPropertyModel.property.schema.property.type == PROPERTY_TYPES.JSON ?
219 PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH :
220 PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
222 case PROPERTY_TYPES.JSON:
223 this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH;
226 this.$scope.maxLength =PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
231 private initScope = ():void => {
234 this.$scope.isLoading = true;
235 this.$scope.forms = {};
236 this.$scope.validationPattern = this.ValidationPattern;
237 this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
238 this.$scope.commentValidationPattern = this.CommentValidationPattern;
239 this.$scope.isNew = (this.formState === FormState.CREATE);
240 this.$scope.componentMetadata = {
241 isService: this.workspaceService.metadata.isService(),
242 isVfc: this.workspaceService.metadata.isVfc()
244 this.$scope.modalInstanceProperty = this.$uibModalInstance;
245 this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, i=> i.name == this.property.name);
246 this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
247 const property = new PropertyModel(this.property);
248 this.$scope.editPropertyModel = {
249 'property': property,
250 types: PROPERTY_DATA.TYPES,
251 simpleTypes: PROPERTY_DATA.SIMPLE_TYPES,
252 hasGetFunctionValue: property.isToscaGetFunction(),
253 isGetFunctionValid: true,
255 this.$scope.isPropertyValueOwner = this.isPropertyValueOwner;
256 this.$scope.propertyOwnerType = this.propertyOwnerType;
257 this.$scope.modelNameFilter = this.workspaceService.metadata.model;
258 //check if property of VnfConfiguration
259 this.$scope.isVnfConfiguration = false;
260 if(this.propertyOwnerType == "component" && angular.isArray(this.compositionService.componentInstances)) {
261 const componentPropertyOwner:ComponentInstance = this.compositionService.componentInstances.find((ci:ComponentInstance) => {
262 return ci.uniqueId === this.property.resourceInstanceUniqueId;
264 if (componentPropertyOwner && componentPropertyOwner.componentName === 'vnfConfiguration') {
265 this.$scope.isVnfConfiguration = true;
269 this.initForNotSimpleType();
270 this.initComponentInstanceMap();
272 this.$scope.validateJson = (json:string):boolean => {
276 return this.ValidationUtils.validateJson(json);
279 this.DataTypesService.fetchDataTypesByModel(this.workspaceService.metadata.model).then(response => {
280 this.$scope.dataTypes = response.data as DataTypesMap;
281 this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
282 return this.$scope.editPropertyModel.types.indexOf(type) == -1;
285 this.$scope.isLoading = false;
289 this.$scope.save = (doNotCloseModal?:boolean):void => {
290 let property:PropertyModel = this.$scope.editPropertyModel.property;
291 this.$scope.editPropertyModel.property.description = this.ValidationUtils.stripAndSanitize(this.$scope.editPropertyModel.property.description);
292 //if read only - or no changes made - just closes the modal
293 //need to check for property.value changes manually to detect if map properties deleted
294 if ((this.$scope.editPropertyModel.property.readonly && !this.$scope.isPropertyValueOwner)
295 || (!this.$scope.forms.editForm.$dirty && angular.equals(JSON.stringify(this.$scope.myValue), this.$scope.editPropertyModel.property.value))) {
296 this.$uibModalInstance.close();
300 this.$scope.isLoading = true;
302 let onPropertyFailure = (response):void => {
303 console.error('Failed to update property', response);
304 this.$scope.isLoading = false;
307 let onPropertySuccess = (propertyFromBE:PropertyModel):void => {
308 this.$scope.isLoading = false;
309 this.filteredProperties[this.$scope.currentPropertyIndex] = propertyFromBE;
310 if (!doNotCloseModal) {
311 this.$uibModalInstance.close(propertyFromBE);
313 this.$scope.forms.editForm.$setPristine();
314 this.$scope.editPropertyModel.property = new PropertyModel();
318 //Not clean, but doing this as a temporary fix until we update the property right panel modals
319 if (this.propertyOwnerType === "group"){
320 this.ComponentInstanceServiceNg2.updateComponentGroupInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
321 .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
322 } else if (this.propertyOwnerType === "policy"){
323 if (!this.$scope.editPropertyModel.property.simpleType &&
324 !this.$scope.isSimpleType(this.$scope.editPropertyModel.property.type) &&
325 !_.isNil(this.$scope.myValue)) {
326 property.value = JSON.stringify(this.$scope.myValue);
328 this.ComponentInstanceServiceNg2.updateComponentPolicyInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
329 .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
331 //in case we have uniqueId we call update method
332 if (this.$scope.isPropertyValueOwner) {
333 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
334 property.value = JSON.stringify(this.$scope.myValue);
336 this.updateInstanceProperties(property.resourceInstanceUniqueId, [property]).subscribe((propertiesFromBE) => onPropertySuccess(propertiesFromBE[0]),
337 error => onPropertyFailure(error));
339 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
340 property.defaultValue = JSON.stringify(this.$scope.myValue);
342 this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.value;
344 this.addOrUpdateProperty(property).subscribe(onPropertySuccess, error => onPropertyFailure(error));
349 this.$scope.getPrev = ():void=> {
350 this.property = this.filteredProperties[--this.$scope.currentPropertyIndex];
352 this.initForNotSimpleType();
353 this.$scope.isLastProperty = false;
356 this.$scope.getNext = ():void=> {
357 this.property = this.filteredProperties[++this.$scope.currentPropertyIndex];
359 this.initForNotSimpleType();
360 this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
363 this.$scope.isSimpleType = (typeName:string):boolean=> {
364 return typeName && this.$scope.editPropertyModel.simpleTypes.indexOf(typeName) != -1;
367 this.$scope.showSchema = ():boolean => {
368 return [PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP].indexOf(this.$scope.editPropertyModel.property.type) > -1;
371 this.$scope.getValidationPattern = (type:string):RegExp => {
372 return this.ValidationUtils.getValidationPattern(type);
375 this.$scope.validateIntRange = (value:string):boolean => {
376 return !value || this.ValidationUtils.validateIntRange(value);
379 this.$scope.close = ():void => {
380 this.$uibModalInstance.close();
383 // put default value when instance value is empty
384 this.$scope.onValueChange = ():void => {
385 if (!this.$scope.editPropertyModel.property.value) {
386 if (this.$scope.isPropertyValueOwner) {
387 this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.defaultValue;
392 // Add the done button at the footer.
393 this.$scope.footerButtons = [
394 {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save},
395 {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
398 this.$scope.$watch("forms.editForm.$invalid", (newVal) => {
399 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
400 this.$scope.footerButtons[0].disabled = newVal || !this.$scope.editPropertyModel.property.toscaFunction;
402 this.$scope.footerButtons[0].disabled = newVal;
406 this.$scope.$watch("forms.editForm.$valid", (newVal) => {
407 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
408 this.$scope.footerButtons[0].disabled = !newVal || !this.$scope.editPropertyModel.property.toscaFunction;
410 this.$scope.footerButtons[0].disabled = !newVal;
414 this.$scope.getDefaultValue = ():any => {
415 return this.$scope.isPropertyValueOwner ? this.$scope.editPropertyModel.property.defaultValue : null;
418 this.$scope.onTypeChange = ():void => {
419 this.$scope.editPropertyModel.property.value = '';
420 this.$scope.editPropertyModel.property.defaultValue = '';
422 this.initForNotSimpleType();
425 this.$scope.onSchemaTypeChange = ():void => {
426 if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.MAP) {
427 this.$scope.myValue = {'': null};
428 } else if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.LIST) {
429 this.$scope.myValue = [];
434 this.$scope.delete = (property:PropertyModel):void => {
435 let onOk: Function = ():void => {
436 this.deleteProperty(property.uniqueId).subscribe(
440 let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
441 let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
442 const okButton = {testId: "OK", text: "OK", type: SdcUiCommon.ButtonType.info, callback: onOk, closeModal: true} as SdcUiComponents.ModalButtonComponent;
443 this.modalService.openInfoModal(title, message, 'delete-modal', [okButton]);
446 this.$scope.onValueTypeChange = (): void => {
447 this.setEmptyValue();
448 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
449 this.$scope.editPropertyModel.isGetFunctionValid = undefined;
451 this.$scope.editPropertyModel.property.toscaFunction = undefined;
452 this.$scope.editPropertyModel.isGetFunctionValid = true;
456 this.$scope.onGetFunctionValidFunction = (toscaGetFunction: ToscaGetFunction): void => {
457 this.$scope.editPropertyModel.property.toscaFunction = toscaGetFunction;
460 this.$scope.onGetFunctionValidityChange = (isValid): void => {
461 if (isValid.isValid) {
462 this.$scope.editPropertyModel.isGetFunctionValid = true;
465 this.$scope.editPropertyModel.isGetFunctionValid = undefined;
470 private setEmptyValue() {
471 const property1 = this.$scope.editPropertyModel.property;
472 property1.value = undefined;
473 if (this.isComplexType(property1.type)) {
474 this.initEmptyComplexValue(property1.type);
477 this.$scope.myValue = '';
480 private updateInstanceProperties = (componentInstanceId:string, properties:PropertyModel[]):Observable<PropertyModel[]> => {
482 return this.ComponentInstanceServiceNg2.updateInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, componentInstanceId, properties)
483 .map(newProperties => {
484 newProperties.forEach((newProperty) => {
485 if (!_.isNil(newProperty.path)) {
486 if (newProperty.path[0] === newProperty.resourceInstanceUniqueId) newProperty.path.shift();
487 // find exist instance property in parent component for update the new value ( find bu uniqueId & path)
488 let existProperty: PropertyModel = <PropertyModel>_.find(this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId], {
489 uniqueId: newProperty.uniqueId,
490 path: newProperty.path
492 let index = this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId].indexOf(existProperty);
493 this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId][index] = newProperty;
496 return newProperties;
500 private addOrUpdateProperty = (property: PropertyModel): Observable<PropertyModel> => {
501 if (!property.uniqueId) {
502 let onSuccess = (newProperty: PropertyModel): PropertyModel => {
503 this.filteredProperties.push(newProperty);
506 return this.topologyTemplateService.addProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property)
509 let onSuccess = (newProperty: PropertyModel): PropertyModel => {
510 // find exist instance property in parent component for update the new value ( find bu uniqueId )
511 let existProperty: PropertyModel = <PropertyModel>_.find(this.filteredProperties, {uniqueId: newProperty.uniqueId});
512 let propertyIndex = this.filteredProperties.indexOf(existProperty);
513 this.filteredProperties[propertyIndex] = newProperty;
516 return this.topologyTemplateService.updateProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property).map(onSuccess);
520 public deleteProperty = (propertyId:string):Observable<void> => {
521 let onSuccess = ():void => {
522 console.debug("Property deleted");
523 delete _.remove(this.filteredProperties, {uniqueId: propertyId})[0];
525 let onFailed = ():void => {
526 console.debug("Failed to delete property");
528 return this.topologyTemplateService.deleteProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, propertyId).map(onSuccess, onFailed);