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 { PROPERTY_TYPES, ValidationUtils, PROPERTY_VALUE_CONSTRAINTS, FormState, PROPERTY_DATA } from "app/utils";
24 import { DataTypesService } from "app/services";
25 import { PropertyModel, DataTypesMap, Component, GroupInstance, PolicyInstance, PropertyBEModel, ComponentMetadata } 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, SdcUiServices, SdcUiComponents } 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";
34 export interface IEditPropertyModel {
35 property:PropertyModel;
37 simpleTypes:Array<string>;
40 interface IPropertyFormViewModelScope extends ng.IScope {
42 editForm:ng.IFormController;
43 footerButtons:Array<any>;
47 validationPattern:RegExp;
48 propertyNameValidationPattern:RegExp;
49 commentValidationPattern:RegExp;
50 editPropertyModel:IEditPropertyModel;
51 modalInstanceProperty:ng.ui.bootstrap.IModalServiceInstance;
52 currentPropertyIndex:number;
53 isLastProperty:boolean;
55 nonPrimitiveTypes:Array<string>;
56 dataTypes:DataTypesMap;
57 isTypeDataType:boolean;
59 isPropertyValueOwner:boolean;
60 isVnfConfiguration:boolean;
63 validateJson(json:string):boolean;
64 save(doNotCloseModal?:boolean):void;
65 getValidationPattern(type:string):RegExp;
66 validateIntRange(value:string):boolean;
69 onSchemaTypeChange():void;
70 onTypeChange(resetSchema:boolean):void;
72 delete(property:PropertyModel):void;
75 isSimpleType(typeName:string):boolean;
76 getDefaultValue():any;
79 export class PropertyFormViewModel {
83 'Sdc.Services.DataTypesService',
87 'PropertyNameValidationPattern',
88 'CommentValidationPattern',
95 'isPropertyValueOwner',
98 'ComponentInstanceServiceNg2',
99 'TopologyTemplateService',
100 'CompositionService',
104 private formState:FormState;
106 constructor(private $scope:IPropertyFormViewModelScope,
107 private DataTypesService:DataTypesService,
108 private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
109 private property:PropertyModel,
110 private ValidationPattern:RegExp,
111 private PropertyNameValidationPattern:RegExp,
112 private CommentValidationPattern:RegExp,
113 private ValidationUtils:ValidationUtils,
114 // private component:Component,
115 private $filter:ng.IFilterService,
116 private modalService:SdcUiServices.ModalService,
117 private filteredProperties:Array<PropertyModel>,
118 private $timeout:ng.ITimeoutService,
119 private isPropertyValueOwner:boolean,
120 private propertyOwnerType:string,
121 private propertyOwnerId:string,
122 private ComponentInstanceServiceNg2: ComponentInstanceServiceNg2,
123 private topologyTemplateService: TopologyTemplateService,
124 private compositionService: CompositionService,
125 private workspaceService: WorkspaceService) {
127 this.formState = angular.isDefined(property.name) ? FormState.UPDATE : FormState.CREATE;
132 private initResource = ():void => {
133 this.$scope.editPropertyModel.property = new PropertyModel(this.property);
134 this.$scope.editPropertyModel.property.type = this.property.type ? this.property.type : null;
135 this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.value || this.$scope.editPropertyModel.property.defaultValue;
136 this.$scope.constraints = this.property.constraints && this.property.constraints[0] ? this.property.constraints[0]["validValues"] : null;
142 //init property add-ons labels that show up at the left side of the input.
143 private initAddOnLabels = () => {
144 if (this.$scope.editPropertyModel.property.name == 'network_role' && this.$scope.isService) {
145 //the server sends back the normalized name. Remove it (to prevent interference with validation) and set the addon label to the component name directly.
146 //Note: this cant be done in properties.ts because we dont have access to the component
147 if (this.$scope.editPropertyModel.property.value) {
148 let splitProp = this.$scope.editPropertyModel.property.value.split(new RegExp(this.workspaceService.metadata.normalizedName + '.', "gi"));
149 this.$scope.editPropertyModel.property.value = splitProp.pop();
151 this.$scope.editPropertyModel.property.addOn = this.workspaceService.metadata.name;
155 private initForNotSimpleType = ():void => {
156 let property = this.$scope.editPropertyModel.property;
157 this.$scope.isTypeDataType = this.DataTypesService.isDataTypeForPropertyType(this.$scope.editPropertyModel.property);
158 if (property.type && this.$scope.editPropertyModel.simpleTypes.indexOf(property.type) == -1) {
159 if (!(property.value || property.defaultValue)) {
160 switch (property.type) {
161 case PROPERTY_TYPES.MAP:
162 this.$scope.myValue = {'': null};
164 case PROPERTY_TYPES.LIST:
165 this.$scope.myValue = [];
168 this.$scope.myValue = {};
171 this.$scope.myValue = JSON.parse(property.value || property.defaultValue);
176 private setMaxLength = ():void => {
177 switch (this.$scope.editPropertyModel.property.type) {
178 case PROPERTY_TYPES.MAP:
179 case PROPERTY_TYPES.LIST:
180 this.$scope.maxLength = this.$scope.editPropertyModel.property.schema.property.type == PROPERTY_TYPES.JSON ?
181 PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH :
182 PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
184 case PROPERTY_TYPES.JSON:
185 this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH;
188 this.$scope.maxLength =PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
193 private initScope = ():void => {
196 this.$scope.forms = {};
197 this.$scope.validationPattern = this.ValidationPattern;
198 this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
199 this.$scope.commentValidationPattern = this.CommentValidationPattern;
200 this.$scope.isLoading = false;
201 this.$scope.isNew = (this.formState === FormState.CREATE);
202 this.$scope.isService = this.workspaceService.metadata.isService();
203 this.$scope.modalInstanceProperty = this.$uibModalInstance;
204 this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, i=> i.name == this.property.name);
205 this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
206 this.$scope.dataTypes = this.DataTypesService.getAllDataTypes();
207 this.$scope.isPropertyValueOwner = this.isPropertyValueOwner;
208 this.$scope.propertyOwnerType = this.propertyOwnerType;
210 this.$scope.editPropertyModel = {
211 property : new PropertyModel(this.property),
212 types : PROPERTY_DATA.TYPES,
213 simpleTypes : PROPERTY_DATA.SIMPLE_TYPES}; //All simple types
216 //check if property of VnfConfiguration
217 this.$scope.isVnfConfiguration = false;
218 if(this.propertyOwnerType == "component" && angular.isArray(this.compositionService.componentInstances)) {
220 var componentPropertyOwner:ComponentInstance = this.compositionService.componentInstances.find((ci:ComponentInstance) => {
221 return ci.uniqueId === this.property.resourceInstanceUniqueId;
223 if (componentPropertyOwner && componentPropertyOwner.componentName === 'vnfConfiguration') {
224 this.$scope.isVnfConfiguration = true;
228 this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
229 return this.$scope.editPropertyModel.types.indexOf(type) == -1;
232 this.initForNotSimpleType();
235 this.$scope.validateJson = (json:string):boolean => {
239 return this.ValidationUtils.validateJson(json);
244 this.$scope.save = (doNotCloseModal?:boolean):void => {
245 let property:PropertyModel = this.$scope.editPropertyModel.property;
246 this.$scope.editPropertyModel.property.description = this.ValidationUtils.stripAndSanitize(this.$scope.editPropertyModel.property.description);
247 //if read only - or no changes made - just closes the modal
248 //need to check for property.value changes manually to detect if map properties deleted
249 if ((this.$scope.editPropertyModel.property.readonly && !this.$scope.isPropertyValueOwner)
250 || (!this.$scope.forms.editForm.$dirty && angular.equals(JSON.stringify(this.$scope.myValue), this.$scope.editPropertyModel.property.value))) {
251 this.$uibModalInstance.close();
255 this.$scope.isLoading = true;
257 let onPropertyFaild = (response):void => {
258 console.info('onFaild', response);
259 this.$scope.isLoading = false;
262 let onPropertySuccess = (propertyFromBE:PropertyModel):void => {
263 console.info('onPropertyResourceSuccess : ', propertyFromBE);
264 this.$scope.isLoading = false;
265 this.filteredProperties[this.$scope.currentPropertyIndex] = propertyFromBE;
266 if (!doNotCloseModal) {
267 this.$uibModalInstance.close(propertyFromBE);
269 this.$scope.forms.editForm.$setPristine();
270 this.$scope.editPropertyModel.property = new PropertyModel();
274 //Not clean, but doing this as a temporary fix until we update the property right panel modals
275 if (this.propertyOwnerType === "group"){
276 this.ComponentInstanceServiceNg2.updateComponentGroupInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
277 .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFaild(error));
278 } else if (this.propertyOwnerType === "policy"){
279 if (!this.$scope.editPropertyModel.property.simpleType &&
280 !this.$scope.isSimpleType(this.$scope.editPropertyModel.property.type) &&
281 !_.isNil(this.$scope.myValue)) {
282 property.value = JSON.stringify(this.$scope.myValue);
284 this.ComponentInstanceServiceNg2.updateComponentPolicyInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
285 .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFaild(error));
287 //in case we have uniqueId we call update method
288 if (this.$scope.isPropertyValueOwner) {
289 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
290 let myValueString:string = JSON.stringify(this.$scope.myValue);
291 property.value = myValueString;
293 this.updateInstanceProperties(property.resourceInstanceUniqueId, [property]).subscribe((propertiesFromBE) => onPropertySuccess(propertiesFromBE[0]), onPropertyFaild);
295 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
296 let myValueString:string = JSON.stringify(this.$scope.myValue);
297 property.defaultValue = myValueString;
299 this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.value;
301 this.addOrUpdateProperty(property).subscribe(onPropertySuccess, onPropertyFaild);
306 this.$scope.getPrev = ():void=> {
307 this.property = this.filteredProperties[--this.$scope.currentPropertyIndex];
309 this.initForNotSimpleType();
310 this.$scope.isLastProperty = false;
313 this.$scope.getNext = ():void=> {
314 this.property = this.filteredProperties[++this.$scope.currentPropertyIndex];
316 this.initForNotSimpleType();
317 this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
320 this.$scope.isSimpleType = (typeName:string):boolean=> {
321 return typeName && this.$scope.editPropertyModel.simpleTypes.indexOf(typeName) != -1;
324 this.$scope.showSchema = ():boolean => {
325 return [PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP].indexOf(this.$scope.editPropertyModel.property.type) > -1;
328 this.$scope.getValidationPattern = (type:string):RegExp => {
329 return this.ValidationUtils.getValidationPattern(type);
332 this.$scope.validateIntRange = (value:string):boolean => {
333 return !value || this.ValidationUtils.validateIntRange(value);
336 this.$scope.close = ():void => {
337 this.$uibModalInstance.close();
340 // put default value when instance value is empty
341 this.$scope.onValueChange = ():void => {
342 if (!this.$scope.editPropertyModel.property.value) {
343 if (this.$scope.isPropertyValueOwner) {
344 this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.defaultValue;
349 // Add the done button at the footer.
350 this.$scope.footerButtons = [
351 {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save},
352 {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
355 this.$scope.$watch("forms.editForm.$invalid", (newVal, oldVal) => {
356 this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
359 this.$scope.getDefaultValue = ():any => {
360 return this.$scope.isPropertyValueOwner ? this.$scope.editPropertyModel.property.defaultValue : null;
363 this.$scope.onTypeChange = ():void => {
364 this.$scope.editPropertyModel.property.value = '';
365 this.$scope.editPropertyModel.property.defaultValue = '';
367 this.initForNotSimpleType();
370 this.$scope.onSchemaTypeChange = ():void => {
371 if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.MAP) {
372 this.$scope.myValue = {'': null};
373 } else if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.LIST) {
374 this.$scope.myValue = [];
379 this.$scope.delete = (property:PropertyModel):void => {
380 let onOk: Function = ():void => {
381 this.deleteProperty(property.uniqueId).subscribe(
385 let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
386 let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
387 const okButton = {testId: "OK", text: "OK", type: SdcUiCommon.ButtonType.info, callback: onOk, closeModal: true} as SdcUiComponents.ModalButtonComponent;
388 this.modalService.openInfoModal(title, message, 'delete-modal', [okButton]);
392 private updateInstanceProperties = (componentInstanceId:string, properties:PropertyModel[]):Observable<PropertyModel[]> => {
394 return this.ComponentInstanceServiceNg2.updateInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, componentInstanceId, properties)
395 .map(newProperties => {
396 newProperties.forEach((newProperty) => {
397 if(newProperty.path[0] === newProperty.resourceInstanceUniqueId) newProperty.path.shift();
398 // find exist instance property in parent component for update the new value ( find bu uniqueId & path)
399 let existProperty: PropertyModel = <PropertyModel>_.find(this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId], {
400 uniqueId: newProperty.uniqueId,
401 path: newProperty.path
403 let index = this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId].indexOf(existProperty);
404 this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId][index] = newProperty;
406 return newProperties;
410 private addOrUpdateProperty = (property:PropertyModel):Observable<PropertyModel> => {
411 if (!property.uniqueId) {
412 let onSuccess = (property:PropertyModel):PropertyModel => {
413 let newProperty = new PropertyModel(property);
414 this.filteredProperties.push(newProperty);
417 return this.topologyTemplateService.addProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property).map(onSuccess);
420 let onSuccess = (newProperty:PropertyModel):PropertyModel => {
421 // find exist instance property in parent component for update the new value ( find bu uniqueId )
422 let existProperty:PropertyModel = <PropertyModel>_.find(this.filteredProperties, {uniqueId: newProperty.uniqueId});
423 let propertyIndex = this.filteredProperties.indexOf(existProperty);
424 this.filteredProperties[propertyIndex] = newProperty;
427 return this.topologyTemplateService.updateProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property).map(onSuccess);
431 public deleteProperty = (propertyId:string):Observable<void> => {
432 let onSuccess = ():void => {
433 console.log("Property deleted");
434 delete _.remove(this.filteredProperties, {uniqueId: propertyId})[0];
436 let onFailed = ():void => {
437 console.log("Failed to delete property");
439 return this.topologyTemplateService.deleteProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, propertyId).map(onSuccess, onFailed);