Merge "identify macro services without instantiation type in BE by feature flag"
[vid.git] / vid-webpack-master / src / app / shared / components / genericForm / formControlsServices / basic.control.generator.ts
1 import {Injectable} from "@angular/core";
2 import {DropdownFormControl} from "../../../models/formControlModels/dropdownFormControl.model";
3 import {FormGroup} from "@angular/forms";
4 import {
5   CustomValidatorOptions,
6   FormControlModel,
7   ValidatorModel,
8   ValidatorOptions
9 } from "../../../models/formControlModels/formControl.model";
10 import {InputFormControl} from "../../../models/formControlModels/inputFormControl.model";
11 import {AppState} from "../../../store/reducers";
12 import {NgRedux} from "@angular-redux/store";
13 import {NumberFormControl} from "../../../models/formControlModels/numberFormControl.model";
14 import {FormControlType} from "../../../models/formControlModels/formControlTypes.enum";
15 import {FileFormControl} from "../../../models/formControlModels/fileFormControl.model";
16 import {SelectOption} from "../../../models/selectOption";
17 import * as _ from 'lodash';
18 import {DynamicInputLabelPipe} from "../../../pipes/dynamicInputLabel/dynamic-input-label.pipe";
19 import {AaiService} from "../../../services/aaiService/aai.service";
20 import {FormGeneralErrorsService} from "../../formGeneralErrors/formGeneralErrors.service";
21 import {Observable, of} from "rxjs";
22 import {NodeModel} from "../../../models/nodeModel";
23 import {Constants} from "../../../utils/constants";
24
25
26 @Injectable()
27 export class BasicControlGenerator {
28
29   public static readonly INSTANCE_NAME_REG_EX:RegExp = /^[a-zA-Z0-9._-]*$/;
30   public static readonly GENERATED_NAME_REG_EX:RegExp = /[^a-zA-Z0-9._-]/g;
31
32   constructor(private _store : NgRedux<AppState>,
33               private _aaiService : AaiService){}
34   getSubscribeResult(subscribeFunction : Function, control : DropdownFormControl) : Observable<any>{
35     return subscribeFunction(this).subscribe((res) => {
36       control.options$ = res;
37       control.hasEmptyOptions = res.length === 0;
38       FormGeneralErrorsService.checkForErrorTrigger.next();
39       return of(res);
40     });
41   }
42
43   getSubscribeInitResult(subscribeFunction : Function, control : DropdownFormControl, form : FormGroup) : Observable<any>{
44     return subscribeFunction(this).subscribe((res) => {
45       if(!_.isNil(control['onInitSelectedField'])){
46         let result = res;
47         for(let key of control['onInitSelectedField']){
48           result = !_.isNil(result[key]) ? result[key] : [];
49         }
50         control.options$ = result;
51         control.hasEmptyOptions = _.isNil(result) || result.length === 0;
52       } else{
53         control.options$ = !_.isNil(res) ? res : [];
54         control.hasEmptyOptions = _.isNil(res) || res.length === 0;
55       }
56
57       FormGeneralErrorsService.checkForErrorTrigger.next();
58       return of(res);
59     });
60   }
61
62   getInstanceNameController(instance: any, serviceId: string, isEcompGeneratedNaming: boolean, model: NodeModel): FormControlModel {
63     let validations: ValidatorModel[] = this.createValidationsForInstanceName(instance, serviceId, isEcompGeneratedNaming);
64     return new InputFormControl({
65       controlName: 'instanceName',
66       displayName: 'Instance name',
67       dataTestId: 'instanceName',
68       placeHolder: (!isEcompGeneratedNaming) ? 'Instance name' : 'Automatically generated when not provided',
69       validations: validations,
70       isVisible : true,
71       value : (!isEcompGeneratedNaming || (!_.isNil(instance) && !_.isNil(instance.instanceName)))
72         ? this.getDefaultInstanceName(instance, model) : null,
73       onKeypress : (event) => {
74         const pattern:RegExp = BasicControlGenerator.INSTANCE_NAME_REG_EX;
75         if(pattern){
76           if(!pattern.test(event['key'])){
77             event.preventDefault();
78           }
79         }
80         return event;
81       }
82     });
83   }
84
85   getInstanceName(instance : any, serviceId : string, isEcompGeneratedNaming: boolean): FormControlModel {
86     let formControlModel:FormControlModel = this.getInstanceNameController(instance, serviceId, isEcompGeneratedNaming, new NodeModel());
87     formControlModel.value = instance ? instance.instanceName : null;
88     return formControlModel;
89   }
90
91   isLegacyRegionShouldBeVisible(instance : any) : boolean {
92     if(!_.isNil(instance) && !_.isNil(instance.lcpCloudRegionId))  {
93       return Constants.LegacyRegion.MEGA_REGION.indexOf(instance.lcpCloudRegionId) !== -1;
94     }
95     return false;
96   }
97
98   getLegacyRegion(instance: any): FormControlModel {
99     return new InputFormControl({
100       controlName: 'legacyRegion',
101       displayName: 'Legacy Region',
102       dataTestId: 'lcpRegionText',
103       placeHolder: 'Type Legacy Region',
104       validations: [],
105       isVisible: this.isLegacyRegionShouldBeVisible(instance),
106       isDisabled : _.isNil(instance) ? true : Constants.LegacyRegion.MEGA_REGION.indexOf(instance.lcpCloudRegionId),
107       value: instance ? instance.legacyRegion : null
108     });
109   }
110
111   private createValidationsForInstanceName(instance: any, serviceId: string, isEcompGeneratedNaming: boolean): ValidatorModel[] {
112     let validations: ValidatorModel[] = [
113       new ValidatorModel(ValidatorOptions.pattern, 'Instance name may include only alphanumeric characters and underscore.', BasicControlGenerator.INSTANCE_NAME_REG_EX),
114       new ValidatorModel(CustomValidatorOptions.uniqueInstanceNameValidator, 'some error', [this._store, serviceId, instance && instance.instanceName])
115     ];
116     if (!isEcompGeneratedNaming) {
117       validations.push(new ValidatorModel(ValidatorOptions.required, 'is required'));
118     }
119     return validations;
120   }
121
122   getInputsOptions = (options: any[]) : Observable<SelectOption[]> =>{
123     let optionList: SelectOption[] = [];
124     options.forEach((option) => {
125       optionList.push(new SelectOption({
126         id: option.id || option.name,
127         name: option.name
128       }));
129     });
130     return of(optionList);
131   };
132
133   getProductFamilyControl = (instance : any, controls : FormControlModel[], isMandatory?: boolean) : DropdownFormControl => {
134     return new DropdownFormControl({
135       type : FormControlType.DROPDOWN,
136       controlName : 'productFamilyId',
137       displayName : 'Product family',
138       dataTestId : 'productFamily',
139       placeHolder : 'Select Product Family',
140       isDisabled : false,
141       name : "product-family-select",
142       value : instance ? instance.productFamilyId : null,
143       validations : _.isNil(isMandatory) || isMandatory === true ? [new ValidatorModel(ValidatorOptions.required, 'is required')]: [],
144       onInit : this.getSubscribeResult.bind(this, this._aaiService.getProductFamilies),
145     })
146   };
147
148
149
150   getDynamicInputsByType(dynamicInputs : any, serviceModelId : string, storeKey : string, type: string ) : FormControlModel[] {
151     let result : FormControlModel[] = [];
152     if(dynamicInputs) {
153       let nodeInstance = null;
154       if (_.has(this._store.getState().service.serviceInstance[serviceModelId][type], storeKey)) {
155         nodeInstance = Object.assign({}, this._store.getState().service.serviceInstance[serviceModelId][type][storeKey]);
156       }
157       result = this.getDynamicInputs(dynamicInputs, nodeInstance);
158     }
159     return result;
160   }
161
162
163   getServiceDynamicInputs(dynamicInputs : any, serviceModelId : string) : FormControlModel[] {
164     let result: FormControlModel[] = [];
165     if (dynamicInputs) {
166       let serviceInstance = null;
167       if (_.has(this._store.getState().service.serviceInstance, serviceModelId)) {
168         serviceInstance = Object.assign({}, this._store.getState().service.serviceInstance[serviceModelId]);
169       }
170       result = this.getDynamicInputs(dynamicInputs, serviceInstance);
171     }
172     return result;
173   }
174
175   getDynamicInputs(dynamicInputs : any, instance :any)  : FormControlModel[]{
176     let result : FormControlModel[] = [];
177     if(dynamicInputs) {
178       dynamicInputs.forEach((input)=> {
179         let validations: ValidatorModel[] = [];
180         if(input.isRequired) {
181           validations.push(new ValidatorModel(ValidatorOptions.required, 'is required'))
182         }
183         if(input.minLength) {
184           validations.push(new ValidatorModel(ValidatorOptions.minLength, '', input.minLength))
185         }
186         if(input.maxLength) {
187           validations.push(new ValidatorModel(ValidatorOptions.maxLength, '', input.maxLength))
188         }
189
190         let dynamicInputLabelPipe: DynamicInputLabelPipe = new DynamicInputLabelPipe();
191         let data:any = {
192           controlName: input.name,
193           displayName: dynamicInputLabelPipe.transform(input.name).slice(0, -1),
194           dataTestId: input.id,
195           placeHolder: input.prompt,
196           tooltip: input.description,
197           validations: validations,
198           isVisible: input.isVisible,
199           value: !_.isNil(instance) && !_.isNil(instance.instanceParams) && instance.instanceParams.length > 0 ? instance.instanceParams[0][input.name] : input.value
200         };
201
202         switch (input.type) {
203           case 'select' :
204           case 'boolean' :{
205             data.value = data.value || input.optionList.filter((option) => option.isDefault ? option.id || option.name: null);
206             data.onInit  = this.getSubscribeInitResult.bind(null, this.getInputsOptions.bind(this, input.optionList));
207             result.push(new DropdownFormControl(data));
208             break;
209           }
210           case 'checkbox': {
211             data.type = FormControlType.CHECKBOX;
212             result.push(new FormControlModel(data));
213             break;
214           }
215           case 'number': {
216             data.min = input.min;
217             data.max = input.max;
218             result.push(new NumberFormControl(data));
219             break;
220           }
221           case 'file': {
222             result.push(new FileFormControl(data));
223             break;
224           }
225           default: {
226             result.push(new InputFormControl(data));
227           }
228         }
229       })
230     }
231
232     return result;
233   }
234
235   getDefaultInstanceName(instance: any, model: NodeModel) : string {
236     const initialInstanceName = (!_.isNil(instance) && instance.instanceName) || (!_.isNil(model.name) ? model.name.replace(BasicControlGenerator.GENERATED_NAME_REG_EX, "") : model.name);
237     return initialInstanceName;
238   }
239
240 }