Merge "Extract concatSupplementaryFile out of VFM controller"
[vid.git] / vid-webpack-master / src / app / shared / components / genericForm / formControlsServices / vfModuleGenerator / vfModule.control.generator.ts
1 import {Injectable} from "@angular/core";
2 import {GenericFormService} from "../../generic-form.service";
3 import {AaiService} from "../../../../services/aaiService/aai.service";
4 import {NgRedux} from "@angular-redux/store";
5 import {HttpClient} from "@angular/common/http";
6 import {BasicControlGenerator} from "../basic.control.generator";
7 import * as _ from 'lodash';
8 import {Observable, of} from "rxjs";
9
10 import {
11   CustomValidatorOptions,
12   FormControlModel,
13   ValidatorModel,
14   ValidatorOptions
15 } from "../../../../models/formControlModels/formControl.model";
16 import {LogService} from "../../../../utils/log/log.service";
17 import {AppState} from "../../../../store/reducers";
18 import {FormGroup} from "@angular/forms";
19 import {DropdownFormControl} from "../../../../models/formControlModels/dropdownFormControl.model";
20 import {FormControlType} from "../../../../models/formControlModels/formControlTypes.enum";
21 import {InputFormControl} from "../../../../models/formControlModels/inputFormControl.model";
22 import {SelectOption} from "../../../../models/selectOption";
23 import {VfModuleInstance} from "../../../../models/vfModuleInstance";
24 import {VfModule} from "../../../../models/vfModule";
25 import {VNFModel} from "../../../../models/vnfModel";
26 import {VnfInstance} from "../../../../models/vnfInstance";
27 import {FileFormControl} from "../../../../models/formControlModels/fileFormControl.model";
28 import {CheckboxFormControl} from "../../../../models/formControlModels/checkboxFormControl.model";
29 import {FileUnit} from "../../../formControls/component/file/fileUnit.enum";
30 import {Constants} from "../../../../utils/constants";
31
32
33 export enum FormControlNames {
34   INSTANCE_NAME = 'instanceName',
35   VOLUME_GROUP_NAME = 'volumeGroupName',
36   LCPCLOUD_REGION_ID = 'lcpCloudRegionId',
37   LEGACY_REGION = 'legacyRegion',
38   TENANT_ID = 'tenantId',
39   ROLLBACK_ON_FAILURE = 'rollbackOnFailure',
40   SDN_C_PRE_LOAD = 'sdncPreLoad',
41 }
42
43
44 @Injectable()
45 export class VfModuleControlGenerator {
46   aaiService: AaiService;
47   vfModuleModel: VfModule;
48   isUpdateMode : boolean;
49
50   constructor(private genericFormService: GenericFormService,
51               private _basicControlGenerator: BasicControlGenerator,
52               private store: NgRedux<AppState>,
53               private http: HttpClient,
54               private _aaiService: AaiService,
55               private _logService: LogService) {
56     this.aaiService = _aaiService;
57   }
58
59   setVFModuleStoreKey = (serviceId: string, vfModuleUuid: string) => {
60       const vfModules = this.store.getState().service.serviceHierarchy[serviceId].vfModules;
61       const vfModulesKeys = Object.keys(vfModules);
62       for(let key of  vfModulesKeys){
63         if(vfModules[key].uuid === vfModuleUuid){
64           return;
65         }
66       }
67   };
68
69
70   getVfModuleInstance = (serviceId: string, vnfStoreKey: string, UUIDData: Object, isUpdateMode: boolean): VfModuleInstance => {
71     let vfModuleInstance: VfModuleInstance = null;
72     if (isUpdateMode && this.store.getState().service.serviceInstance[serviceId] &&
73       _.has(this.store.getState().service.serviceInstance[serviceId].vnfs, vnfStoreKey) &&
74       _.has(this.store.getState().service.serviceInstance[serviceId].vnfs[vnfStoreKey].vfModules, UUIDData['modelName'])) {
75        vfModuleInstance = Object.assign({},this.store.getState().service.serviceInstance[serviceId].vnfs[vnfStoreKey].vfModules[UUIDData['modelName']][UUIDData['vFModuleStoreKey']]);
76     }
77     return vfModuleInstance;
78   };
79
80   extractVfAccordingToVfModuleUuid(serviceId: string, UUIDData: Object): VfModule {
81     const vfModule = this.store.getState().service.serviceHierarchy[serviceId].vfModules[UUIDData['modelName']];
82     this.vfModuleModel = vfModule;
83     return vfModule;
84   }
85
86   getMacroFormControls(serviceId: string, vnfStoreKey: string, vfModuleStoreKey: string, uuidData : Object, isUpdateMode: boolean): FormControlModel[] {
87     this.isUpdateMode = isUpdateMode;
88     this.extractVfAccordingToVfModuleUuid(serviceId, uuidData);
89     if (_.isNil(serviceId) || _.isNil(vnfStoreKey) || _.isNil(vfModuleStoreKey)) {
90       if(isUpdateMode){
91         this._logService.error('should provide serviceId, vfModuleStoreKey, vnfStoreKey', serviceId);
92         return [];
93       }
94     }
95
96     const vfModuleInstance = this.getVfModuleInstance(serviceId, vnfStoreKey, uuidData, isUpdateMode);
97     const vfModuleModel = this.vfModuleModel;
98     const vnf: VnfInstance = this.store.getState().service.serviceInstance[serviceId].vnfs[vnfStoreKey];
99     const vnfModelName: string = vnf.originalName;
100     const vnfModel = new VNFModel(this.store.getState().service.serviceHierarchy[serviceId].vnfs[vnfModelName]);
101
102     let result: FormControlModel[] = [];
103
104     if (!_.isNil(vfModuleModel)) {
105       result = this.pushInstanceAndVGToForm(result, vfModuleInstance, serviceId, vnfModel, false);
106     }
107     if(this.store.getState().global.flags['FLAG_SUPPLEMENTARY_FILE']) {
108       result = this._basicControlGenerator.concatSupplementaryFile(result, vfModuleInstance);
109     }
110     return result;
111   }
112
113   pushInstanceAndVGToForm(result: FormControlModel[], vfModuleElement: any, serviceId: string, vnfModel: any, isALaCarte: boolean) :FormControlModel[]{
114     result.push(this.getInstanceName(vfModuleElement, serviceId, vnfModel.isEcompGeneratedNaming));
115     if (this.vfModuleModel.volumeGroupAllowed) {
116       result.push(this.getVolumeGroupData(vfModuleElement, serviceId, vnfModel.isEcompGeneratedNaming, isALaCarte));
117     }
118     return result;
119   }
120
121   getAlaCarteFormControls(serviceId: string, vnfStoreKey: string, vfModuleStoreKey: string, uuidData : Object, isUpdateMode: boolean): FormControlModel[] {
122     this.isUpdateMode = isUpdateMode;
123     this.extractVfAccordingToVfModuleUuid(serviceId, uuidData);
124     if (_.isNil(serviceId) || _.isNil(vnfStoreKey) || _.isNil(vfModuleStoreKey)) {
125       if(isUpdateMode){
126         this._logService.error('should provide serviceId, vfModuleStoreKey, vnfStoreKey', serviceId);
127         return [];
128       }
129     }
130     const vnf: VnfInstance = this.store.getState().service.serviceInstance[serviceId].vnfs[vnfStoreKey];
131     const vnfModelName: string = vnf.originalName;
132     const vnfModel = new VNFModel(this.store.getState().service.serviceHierarchy[serviceId].vnfs[vnfModelName]);
133
134     const vfModuleInstance = this.getVfModuleInstance(serviceId, vnfStoreKey, uuidData, isUpdateMode);
135     let result: FormControlModel[] = [];
136     this.pushInstanceAndVGToForm(result, vfModuleInstance, serviceId, vnfModel, true);
137     result.push(this.getLcpRegionControl(serviceId, vfModuleInstance, result));
138     result.push(this._basicControlGenerator.getLegacyRegion(vfModuleInstance));
139     result.push(this.getTenantControl(serviceId, vfModuleInstance, result));
140     result.push(this.getRollbackOnFailureControl(vfModuleInstance, result));
141     result.push(this.getSDNCControl(vfModuleInstance, result));
142     if(this.store.getState().global.flags['FLAG_SUPPLEMENTARY_FILE']) {
143       result = this._basicControlGenerator.concatSupplementaryFile(result, vfModuleInstance);
144     }
145     return result;
146   }
147
148   getInstanceName(instance: any, serviceId: string, isEcompGeneratedNaming: boolean): FormControlModel {
149     let formControlModel:FormControlModel = this._basicControlGenerator.getInstanceNameController(instance, serviceId, isEcompGeneratedNaming, this.vfModuleModel);
150     formControlModel.onBlur = (event, form : FormGroup) => {
151         if(!_.isNil(form.controls['volumeGroupName'])&& event.target.value.length > 0){
152           form.controls['volumeGroupName'].setValue(event.target.value + "_vol");
153         }
154       };
155
156     return formControlModel;
157   }
158
159   getDefaultVolumeGroupName(instance: any, isEcompGeneratedNaming: boolean): string {
160     if ((!_.isNil(instance) && instance.volumeGroupName))  {
161       return instance.volumeGroupName;
162     }
163     if (isEcompGeneratedNaming) {
164       return null;
165     }
166     return this._basicControlGenerator.getDefaultInstanceName(instance, this.vfModuleModel) + "_vol";
167   }
168
169   getVolumeGroupData(instance: any, serviceId: string, isEcompGeneratedNaming: boolean, isALaCarte: boolean): FormControlModel {
170     let validations: ValidatorModel[] = [
171       new ValidatorModel(ValidatorOptions.pattern, 'Instance name may include only alphanumeric characters and underscore.', BasicControlGenerator.INSTANCE_NAME_REG_EX),
172       new ValidatorModel(CustomValidatorOptions.uniqueInstanceNameValidator, 'Volume Group instance name is already in use, please pick another name', [this.store, serviceId, instance && instance.volumeGroupName])
173     ];
174     // comment out because if not provided vid won't create VG
175     // if (!isEcompGeneratedNaming)  {
176     //   validations.push(new ValidatorModel(ValidatorOptions.required, 'is required'));
177     // }
178     return new InputFormControl({
179       controlName: 'volumeGroupName',
180       displayName: 'Volume Group Name',
181       dataTestId: 'volumeGroupName',
182       // placeHolder: (!isEcompGeneratedNaming) ? 'Volume Group Name' : 'Automatically generated when not provided',
183       validations: validations,
184       tooltip : 'When filled, VID will create a Volume Group by this name and associate with this module.\n' +
185                 'When empty, the module is created without a Volume Group.',
186       isVisible: this.shouldVGNameBeVisible(isEcompGeneratedNaming,isALaCarte),
187       value: this.getDefaultVolumeGroupName(instance, isEcompGeneratedNaming),
188       onKeypress: (event) => {
189         const pattern:RegExp = BasicControlGenerator.INSTANCE_NAME_REG_EX;
190         if (pattern) {
191           if (!pattern.test(event['key'])) {
192             event.preventDefault();
193           }
194         }
195         return event;
196       }
197     });
198   }
199
200   private shouldVGNameBeVisible(isEcompGeneratedNaming: boolean, isALaCarte: boolean) {
201     if((!isALaCarte && !isEcompGeneratedNaming) || isALaCarte){
202       return true;
203     }
204     return false;
205
206   }
207
208   getTenantControl = (serviceId: string, instance: any, controls: FormControlModel[]): DropdownFormControl => {
209     const service = this.store.getState().service.serviceInstance[serviceId];
210     const globalCustomerId: string = service.globalSubscriberId;
211     const serviceType: string = service.subscriptionServiceType;
212     return new DropdownFormControl({
213       type: FormControlType.DROPDOWN,
214       controlName: FormControlNames.TENANT_ID,
215       displayName: 'Tenant',
216       dataTestId: 'tenant',
217       placeHolder: 'Select Tenant',
218       name: "tenant",
219       isDisabled: _.isNil(instance) || _.isNil(instance.lcpCloudRegionId),
220       onInitSelectedField: instance ? ['lcpRegionsTenantsMap', instance.lcpCloudRegionId] : null,
221       value: instance ? instance.tenantId : null,
222       validations: [new ValidatorModel(ValidatorOptions.required, 'is required')],
223       onInit: instance ? this._basicControlGenerator.getSubscribeInitResult.bind(
224         this._aaiService,
225         this.aaiService.getLcpRegionsAndTenants.bind(this, globalCustomerId, serviceType)) : () => {
226       },
227     })
228   };
229
230   getLcpRegionControl = (serviceId: string, instance: any, controls: FormControlModel[]): DropdownFormControl => {
231     const service = this.store.getState().service.serviceInstance[serviceId];
232     const globalCustomerId: string = service.globalSubscriberId;
233     const serviceType: string = service.subscriptionServiceType;
234     return new DropdownFormControl({
235       type: FormControlType.DROPDOWN,
236       controlName: 'lcpCloudRegionId',
237       displayName: 'LCP region',
238       dataTestId: 'lcpRegion',
239       placeHolder: 'Select LCP Region',
240       name: "lcpRegion",
241       isDisabled: false,
242       value: instance ? instance.lcpCloudRegionId : null,
243       validations: [new ValidatorModel(ValidatorOptions.required, 'is required')],
244       onInitSelectedField: ['lcpRegionList'],
245       onInit: this._basicControlGenerator.getSubscribeInitResult.bind(
246         this._aaiService,
247         this._aaiService.getLcpRegionsAndTenants.bind(this, globalCustomerId, serviceType)),
248       onChange: (param: string, form: FormGroup) => {
249         form.controls[FormControlNames.TENANT_ID].enable();
250         form.controls[FormControlNames.TENANT_ID].reset();
251         if (!_.isNil(globalCustomerId) && !_.isNil(serviceType)) {
252           this._basicControlGenerator.getSubscribeResult.bind(this, this._aaiService.getLcpRegionsAndTenants(globalCustomerId, serviceType).subscribe(res => {
253             controls.find(item => item.controlName === FormControlNames.TENANT_ID)['options$'] = res.lcpRegionsTenantsMap[param];
254             if (res.lcpRegionsTenantsMap[param]) {
255               controls.find(item => item.controlName === FormControlNames.TENANT_ID)['hasEmptyOptions'] = res.lcpRegionsTenantsMap[param].length === 0;
256             }
257           }));
258         }
259
260         if (Constants.LegacyRegion.MEGA_REGION.indexOf(param) !== -1) {
261           form.controls['legacyRegion'].enable();
262           controls.find(item => item.controlName === 'legacyRegion').isVisible = true;
263
264         } else {
265           controls.find(item => item.controlName === 'legacyRegion').isVisible = false;
266           form.controls['legacyRegion'].setValue(null);
267           form.controls['legacyRegion'].reset();
268           form.controls['legacyRegion'].disable();
269         }
270       }
271     })
272   };
273
274   getSDNCControl = (instance: any, controls: FormControlModel[]): CheckboxFormControl => {
275     return new CheckboxFormControl({
276       type: FormControlType.CHECKBOX,
277       controlName: 'sdncPreLoad',
278       displayName: 'SDN-C pre-load',
279       dataTestId: 'sdncPreLoad',
280       value: instance ? instance.sdncPreLoad : false,
281       validations: [new ValidatorModel(ValidatorOptions.required, 'is required')]
282     })
283   };
284
285   getRollbackOnFailureControl = (instance: any, controls: FormControlModel[]): DropdownFormControl => {
286     return new DropdownFormControl({
287       type: FormControlType.DROPDOWN,
288       controlName: FormControlNames.ROLLBACK_ON_FAILURE,
289       displayName: 'Rollback on failure',
290       dataTestId: 'rollback',
291       isDisabled: false,
292       validations: [new ValidatorModel(ValidatorOptions.required, 'is required')],
293       value: instance ? instance.rollbackOnFailure : 'true',
294       onInit: this._basicControlGenerator.getSubscribeInitResult.bind(null, this.getRollBackOnFailureOptions)
295     })
296   };
297
298   getRollBackOnFailureOptions = (): Observable<SelectOption[]> => {
299     return of([
300       new SelectOption({id: 'true', name: 'Rollback'}),
301       new SelectOption({id: 'false', name: 'Don\'t Rollback'})
302     ]);
303   };
304 }