set default values in VFM Upgrade popup
[vid.git] / vid-webpack-master / src / app / shared / components / genericForm / formControlsServices / sharedControlles / shared.controllers.service.ts
1 import {Injectable} from "@angular/core";
2 import {DropdownFormControl} from "../../../../models/formControlModels/dropdownFormControl.model";
3 import {FormControlType} from "../../../../models/formControlModels/formControlTypes.enum";
4 import {
5   FormControlModel,
6   ValidatorModel,
7   ValidatorOptions
8 } from "../../../../models/formControlModels/formControl.model";
9 import {NgRedux} from "@angular-redux/store";
10 import {AppState} from "../../../../store/reducers";
11 import {AaiService} from "../../../../services/aaiService/aai.service";
12 import {ControlGeneratorUtil, SDN_C_PRE_LOAD} from "../control.generator.util.service";
13 import * as _ from "lodash";
14 import {FormGroup} from "@angular/forms";
15 import {Constants} from "../../../../utils/constants";
16 import {CheckboxFormControl} from "../../../../models/formControlModels/checkboxFormControl.model";
17 import {InputFormControl} from "../../../../models/formControlModels/inputFormControl.model";
18 import {NodeModel} from "../../../../models/nodeModel";
19 import {LcpRegion} from "../../../../models/lcpRegion";
20 import {Tenant} from "../../../../models/tenant";
21 import {MultiselectFormControl} from "../../../../models/formControlModels/multiselectFormControl.model";
22 import {MultiSelectItem} from "../../../formControls/component/multiselect/multiselect.model";
23
24 @Injectable()
25 export class SharedControllersService {
26   constructor(private _store : NgRedux<AppState>,
27               private _aaiService : AaiService,
28               private _basicControlGenerator : ControlGeneratorUtil){}
29
30
31   getLineOfBusinessControl = (instance?: any): DropdownFormControl => {
32     return this.getLineOfBusinessControlInternal(undefined, instance);
33   };
34
35   getMultiSelectLineOfBusinessControl = (instance: any, isMultiSelected: boolean): MultiselectFormControl => {
36     return this.getLobMultiselectControl(instance, isMultiSelected);
37   };
38
39   getLineOfBusinessByOwningEntityControl = (instance?: any, serviceId?: string, controls?: FormControlModel[]): DropdownFormControl => {
40     const service = this._store.getState().service.serviceInstance[serviceId];
41     const owningEntityName: string = service.owningEntityName;
42
43     const changeLcpRegionOptionsOnChange = (lineOfBusinessNameParam: string, form: FormGroup) => {
44       form.controls['lcpCloudRegionId'].enable();
45       form.controls['lcpCloudRegionId'].reset();
46       this._basicControlGenerator.getSubscribeInitResult(
47         this._aaiService.getLcpRegionsByOwningEntityAndLineOfBusiness.bind(this, owningEntityName, lineOfBusinessNameParam),
48         controls.find(item => item.controlName === 'lcpCloudRegionId') as DropdownFormControl, form
49       ).subscribe()
50     };
51
52     return this.getLineOfBusinessControlInternal(changeLcpRegionOptionsOnChange, instance);
53   };
54
55   private getLineOfBusinessControlInternal = (onChange: Function, instance?: any): DropdownFormControl  => {
56     return new DropdownFormControl({
57       type: FormControlType.DROPDOWN,
58       controlName: 'lineOfBusiness',
59       displayName: 'Line of business',
60       dataTestId: 'lineOfBusiness',
61       placeHolder: 'Select Line Of Business',
62       isDisabled: false,
63       name: "lineOfBusiness",
64       value: instance ? instance.lineOfBusiness : null,
65       validations: [new ValidatorModel(ValidatorOptions.required, 'is required')],
66       onInitSelectedField: ['lineOfBusinessList'],
67       onChange,
68       onInit: this._basicControlGenerator.getSubscribeInitResult.bind(null, this._aaiService.getCategoryParameters)
69     })
70   };
71
72   getTenantControl = (serviceId: string, instance?: any): DropdownFormControl => {
73     const service = this._store.getState().service.serviceInstance[serviceId];
74     const globalCustomerId: string = service.globalSubscriberId;
75     const serviceType: string = service.subscriptionServiceType;
76
77     const onInit = instance
78       ? this._basicControlGenerator.getSubscribeInitResult.bind(
79           this._aaiService,
80           this._aaiService.getLcpRegionsAndTenants.bind(this, globalCustomerId, serviceType))
81       : () => {};
82     return this.getTenantControlInternal(onInit, instance);
83   };
84
85   getTenantByLcpRegionControl = (serviceId: string, instance?: any): DropdownFormControl => {
86     return this.getTenantControlInternal(() => {}, instance);
87   };
88
89   private getTenantControlInternal = (onInit: Function, instance?: any): DropdownFormControl => {
90     return new DropdownFormControl({
91       type: FormControlType.DROPDOWN,
92       controlName: 'tenantId',
93       displayName: 'Tenant',
94       dataTestId: 'tenant',
95       placeHolder: 'Select Tenant',
96       name: 'tenant',
97       isDisabled: _.isNil(instance) || _.isNil(instance.lcpCloudRegionId),
98       onInitSelectedField: instance ? ['lcpRegionsTenantsMap', instance.lcpCloudRegionId] : null,
99       value: instance ? instance.tenantId : null,
100       validations: [new ValidatorModel(ValidatorOptions.required, 'is required')],
101       onInit,
102     })
103   };
104
105   getRollbackOnFailureControl = (instance?: any): DropdownFormControl => {
106     return new DropdownFormControl({
107       type: FormControlType.DROPDOWN,
108       controlName: 'rollbackOnFailure',
109       displayName: 'Rollback on failure',
110       dataTestId: 'rollback',
111       placeHolder: 'Rollback on failure',
112       isDisabled: false,
113       validations: [new ValidatorModel(ValidatorOptions.required, 'is required')],
114       value: instance ? instance.rollbackOnFailure : 'true',
115       onInit: this._basicControlGenerator.getSubscribeInitResult.bind(null, this._basicControlGenerator.getRollBackOnFailureOptions)
116     })
117   };
118
119   getLegacyRegion(instance: any): FormControlModel {
120     return new InputFormControl({
121       controlName: 'legacyRegion',
122       displayName: 'Legacy Region',
123       dataTestId: 'lcpRegionText',
124       placeHolder: 'Type Legacy Region',
125       validations: [],
126       isVisible: this._basicControlGenerator.isLegacyRegionShouldBeVisible(instance),
127       isDisabled : _.isNil(instance) ? true : Constants.LegacyRegion.MEGA_REGION.indexOf(instance.lcpCloudRegionId),
128       value: instance ? instance.legacyRegion : null
129     });
130   }
131
132   getLcpRegionControl = (serviceId: string, instance: any, controls: FormControlModel[]): DropdownFormControl => {
133     const service = this._store.getState().service.serviceInstance[serviceId];
134     const globalCustomerId: string = service.globalSubscriberId;
135     const serviceType: string = service.subscriptionServiceType;
136
137     const onInit = this._basicControlGenerator.getSubscribeInitResult.bind(
138       this._aaiService,
139       this._aaiService.getLcpRegionsAndTenants.bind(this, globalCustomerId, serviceType)
140     );
141
142     const changeTenantsOptionsByServiceTypeOnChange = (
143       (globalCustomerId, serviceType, lcpCloudRegionIdParam) => {
144         if (!_.isNil(globalCustomerId) && !_.isNil(serviceType)) {
145           this._basicControlGenerator.getSubscribeResult.bind(this,
146             this._aaiService.getLcpRegionsAndTenants(globalCustomerId, serviceType)
147             .subscribe(res => this.setTenantsOptions(controls, res.lcpRegionsTenantsMap[lcpCloudRegionIdParam])));
148         }
149
150       }
151     ).bind(this, globalCustomerId, serviceType);
152
153     return this.getLcpRegionControlInternal(instance, controls,
154       false, onInit, ['lcpRegionList'], changeTenantsOptionsByServiceTypeOnChange)
155   };
156
157   getLcpRegionByLineOfBusinessControl = (serviceId: string, instance: any, controls: FormControlModel[]): DropdownFormControl => {
158     const service = this._store.getState().service.serviceInstance[serviceId];
159     const owningEntityName: string = service.owningEntityName;
160
161     const changeTenantsOptions = (controls: FormControlModel[], cloudRegionId, lcpRegionList: LcpRegion[]) => {
162       const lcpRegionOption = (_.isNil(lcpRegionList) || _.isNil(cloudRegionId))
163         ? null : lcpRegionList.find(({id}) => id === cloudRegionId);
164
165       if (!_.isNil(lcpRegionOption)) {
166         this._aaiService.getTenantsByCloudOwnerAndCloudRegionId(lcpRegionOption.cloudOwner, lcpRegionOption.id)
167           .subscribe(res => this.setTenantsOptions(controls, res));
168       }
169     };
170
171     const lcpRegionOptionsList = (controls: FormControlModel[]): LcpRegion[] => {
172       const lcpCloudRegionIdControl = _.isNil(controls)
173         ? null : controls.find(({controlName}) => controlName === 'lcpCloudRegionId');
174
175       return _.isNil(lcpCloudRegionIdControl) ? null : lcpCloudRegionIdControl['options$'];
176     };
177
178     const loadLcpRegionOptionsOnInit = (_.isNil(instance) || _.isNil(instance.lineOfBusiness))
179       ? () => {}
180       : this._basicControlGenerator.getSubscribeInitResult.bind(
181         this, () => {
182           return this._aaiService.getLcpRegionsByOwningEntityAndLineOfBusiness(owningEntityName, instance.lineOfBusiness)
183           .do(res => changeTenantsOptions(controls, instance.lcpCloudRegionId, res));
184         }
185       );
186
187     const changeTenantsOptionsByCloudRegionIdOnChange = (
188       (controls, lcpCloudRegionIdParam) => changeTenantsOptions(controls, lcpCloudRegionIdParam, lcpRegionOptionsList(controls))
189     ).bind(this, controls);
190
191     return this.getLcpRegionControlInternal(instance, controls,
192       _.isNil(instance) || _.isNil(instance.lineOfBusiness),
193       loadLcpRegionOptionsOnInit, null, changeTenantsOptionsByCloudRegionIdOnChange
194       )
195   };
196
197   private getLcpRegionControlInternal = (instance: any, controls: FormControlModel[], isDisabled: boolean,
198                                          onInit: Function, onInitSelectedField: string[], changeTenantsOptionsOnChange: Function
199   ): DropdownFormControl => {
200     return new DropdownFormControl({
201       type: FormControlType.DROPDOWN,
202       controlName: 'lcpCloudRegionId',
203       displayName: 'LCP region',
204       dataTestId: 'lcpRegion',
205       placeHolder: 'Select LCP Region',
206       name: "lcpRegion",
207       isDisabled,
208       value: instance ? instance.lcpCloudRegionId : null,
209       validations: [new ValidatorModel(ValidatorOptions.required, 'is required')],
210       onInitSelectedField,
211       onInit,
212
213       onChange: (lcpCloudRegionIdParam: string, form: FormGroup) => {
214         form.controls['tenantId'].enable();
215         form.controls['tenantId'].reset();
216
217         changeTenantsOptionsOnChange(lcpCloudRegionIdParam);
218
219         if (Constants.LegacyRegion.MEGA_REGION.indexOf(lcpCloudRegionIdParam) !== -1) {
220           form.controls['legacyRegion'].enable();
221           controls.find(item => item.controlName === 'legacyRegion').isVisible = true;
222
223         } else {
224           controls.find(item => item.controlName === 'legacyRegion').isVisible = false;
225           form.controls['legacyRegion'].setValue(null);
226           form.controls['legacyRegion'].reset();
227           form.controls['legacyRegion'].disable();
228         }
229       }
230     })
231   };
232
233   private setTenantsOptions = (controls: FormControlModel[], tenants: Tenant[]) => {
234     const tenantsControl = controls.find(item => item.controlName === 'tenantId');
235     tenantsControl['options$'] = tenants;
236     tenantsControl['hasEmptyOptions'] = tenants && tenants.length === 0;
237   };
238
239
240   getSDNCControl = (instance: any, checkedByDefault: boolean, extraContents? : object[]): FormControlModel => {
241     return new CheckboxFormControl({
242       controlName: SDN_C_PRE_LOAD,
243       displayName: 'SDN-C pre-load',
244       dataTestId: 'sdncPreLoad',
245       value: instance ? instance.sdncPreLoad : checkedByDefault,
246       validations: [new ValidatorModel(ValidatorOptions.required, 'is required')],
247       extraContents
248     })
249   };
250
251   getProductFamilyControl = (instance : any, controls : FormControlModel[], isMandatory?: boolean) : DropdownFormControl => {
252     return new DropdownFormControl({
253       type : FormControlType.DROPDOWN,
254       controlName : 'productFamilyId',
255       displayName : 'Product family',
256       dataTestId : 'productFamily',
257       placeHolder : 'Select Product Family',
258       isDisabled : false,
259       name : "product-family-select",
260       value : instance ? instance.productFamilyId : null,
261       validations : _.isNil(isMandatory) || isMandatory === true ? [new ValidatorModel(ValidatorOptions.required, 'is required')]: [],
262       onInit : this._basicControlGenerator.getSubscribeResult.bind(this, this._aaiService.getProductFamilies),
263     })
264   };
265
266   getInstanceNameController(instance: any, serviceId: string, isEcompGeneratedNaming: boolean, model: NodeModel): FormControlModel {
267     let validations: ValidatorModel[] = this._basicControlGenerator.createValidationsForInstanceName(instance, serviceId, isEcompGeneratedNaming);
268     return new InputFormControl({
269       controlName: 'instanceName',
270       displayName: 'Instance name',
271       dataTestId: 'instanceName',
272       placeHolder: (!isEcompGeneratedNaming) ? 'Instance name' : 'Automatically generated when not provided',
273       validations: validations,
274       isVisible : true,
275       value : (!isEcompGeneratedNaming || (!_.isNil(instance) && !_.isNil(instance.instanceName) && instance.instanceName !== ""))
276         ? this._basicControlGenerator.getDefaultInstanceName(instance, model) : null,
277       onKeypress : (event) => {
278         const pattern:RegExp = ControlGeneratorUtil.INSTANCE_NAME_REG_EX;
279         if(pattern){
280           if(!pattern.test(event['key'])){
281             event.preventDefault();
282           }
283         }
284         return event;
285       }
286     });
287   }
288
289   getInstanceName(instance : any, serviceId : string, isEcompGeneratedNaming: boolean): FormControlModel {
290     let formControlModel:FormControlModel = this.getInstanceNameController(instance, serviceId, isEcompGeneratedNaming, new NodeModel());
291     formControlModel.value = instance ? instance.instanceName : null;
292     return formControlModel;
293   }
294
295   getPlatformMultiselectControl = (instance: any, controls: FormControlModel[], isMultiSelected: boolean) : MultiselectFormControl => {
296     return this.getMultiSelectFormControl(
297       'platformName',
298       'Platform',
299       'multi-selectPlatform',
300       'Select Platform',
301       "platform",
302       instance,
303       instance ? instance.platformName : null,
304       isMultiSelected,
305       'platformList'
306     );
307   };
308
309   getLobMultiselectControl = (instance: any, isMultiSelected: boolean) : MultiselectFormControl => {
310     return this.getMultiSelectFormControl(
311       'lineOfBusiness',
312       'Line of business',
313       'multi-lineOfBusiness',
314       'Select Line Of Business',
315       "lineOfBusiness",
316       instance,
317       instance ? instance.lineOfBusiness : null,
318       isMultiSelected,
319       'lineOfBusinessList');
320   };
321
322   private getMultiSelectFormControl(controlName: string, displayName: string, dataTestId: string, placeholder: string,
323                                     name: string, instance: any, defaultValue, isMultiSelected: boolean, catagoryParamResponseFieldName: string) {
324     return new MultiselectFormControl({
325       type: FormControlType.MULTI_SELECT,
326       controlName,
327       displayName,
328       dataTestId,
329       selectedFieldName: 'name',
330       ngValue: 'name',
331       placeHolder: placeholder,
332       isDisabled: false,
333       name: name,
334       value: instance ? defaultValue : '',
335       limitSelection: isMultiSelected ? 1000 : 1,
336       validations: [new ValidatorModel(ValidatorOptions.required, 'is required')],
337       onInitSelectedField: [catagoryParamResponseFieldName],
338       onInit: this._basicControlGenerator.getSubscribeInitResult.bind(null, this._aaiService.getCategoryParameters),
339       onChange: (param: MultiSelectItem[], form: FormGroup) => {
340         form.controls[controlName].setValue(param.map((multiSelectItem: MultiSelectItem) => {
341           return multiSelectItem.itemName
342         }).join(','));
343       },
344       convertOriginalDataToArray: (value?: string) => {
345         if (_.isNil(value)) return [];
346         return value.split(',');
347       }
348     });
349   }
350 }