New Angular UI from 1806
[vid.git] / vid-webpack-master / src / app / components / service-popup / service-instance-details / service-instance-details.component.ts
1 import {Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core';
2 import {FormControl, FormGroup, Validators} from "@angular/forms";
3 import {ServicePopupDataModel} from './servicePopupDataModel';
4 import {AaiService} from '../../../services/aaiService/aai.service';
5 import {updateServiceInstance} from "../../../service.actions";
6 import * as _ from 'lodash';
7 import {ServiceModel} from "../../../shared/models/serviceModel";
8 import {ModelInfo} from "../../../shared/models/modelInfo";
9 import {loadProductFamiliesAction} from "../../../services/aaiService/aai.actions";
10 import {Observable} from "rxjs/Observable";
11 import {SelectOptionInterface} from "../../../shared/models/selectOption";
12 import {NgRedux, select} from "@angular-redux/store";
13 import {AppState} from "../../../store/reducers";
14 import {isNullOrUndefined} from 'util';
15 import {ServiceInstanceDetailsService} from './service-instance-details.service';
16 import {NumbersLettersUnderscoreValidator} from '../../../shared/components/validators/numbersLettersUnderscore/numbersLettersUnderscore.validator';
17 import {DefaultDataGeneratorService} from '../../../shared/services/defaultDataServiceGenerator/default.data.generator.service';
18
19
20 @Component({
21   selector: 'service-instance-details',
22   templateUrl: 'service-instance-details.html',
23   styleUrls: ['service-instance-details.scss'],
24   providers: [AaiService]
25 })
26
27 export class ServiceInstanceDetailsComponent implements OnInit, OnChanges {
28   ngOnChanges(changes: SimpleChanges): void {
29     if (changes["serviceInstance"] !== undefined && changes["serviceInstance"].currentValue !== changes["serviceInstance"].previousValue && changes["serviceInstance"].currentValue !== null) {
30       this.oldServiceInstance = Object.assign({}, this.serviceInstance);
31     }
32   }
33   _serviceModel: ServiceModel;
34   @Input () serviceInstance: any;
35   @Input () dynamicInputs;
36   @Input () servicesQty: number;
37   @Input ()
38   set serviceModel(serviceModel: ServiceModel) {
39     this._serviceModel = serviceModel;
40     this.updateFormGroupControlsWithServiceModel(serviceModel);
41   }
42   @ViewChild('serviceForm') serviceForm: 'ServiceForm';
43   @Output() closePopup : EventEmitter<any> = new EventEmitter<any>();
44   @Output() onDataChanged: EventEmitter<any> = new EventEmitter<any>();
45   oldServiceInstance = {};
46
47   //todo: implement Epics and use @select to fetch the rest of the form's data as done with productFamilies.
48   //that way we can loose the updateFormData function and the subscription to store in the constructor.
49   @select(['service','productFamilies'])
50   readonly productFamilies : Observable<SelectOptionInterface[]>;
51   serviceDetails:any = {
52
53   };
54   servicePopupDataModel: ServicePopupDataModel = new ServicePopupDataModel();
55   serviceInstanceDetailsFormGroup: FormGroup;
56   serviceInstanceDetailsService : ServiceInstanceDetailsService;
57
58   constructor(private _aaiService: AaiService, private store: NgRedux<AppState>, private _serviceInstanceDetailsService : ServiceInstanceDetailsService, private _defaultDataGeneratorService : DefaultDataGeneratorService) {
59     this.store.subscribe(() => {this.updateFormData()});
60     this.serviceInstanceDetailsService = this._serviceInstanceDetailsService;
61     this.serviceInstanceDetailsFormGroup = this.createFormGroup();
62
63     this.serviceInstanceDetailsFormGroup.valueChanges.subscribe(()=> {
64       this.onDataChanged.next();
65     })
66   }
67
68   ngOnInit() {
69     this.subscribeToFormChanges();
70     this._aaiService.getSubscribers().subscribe();
71     this._aaiService.getCategoryParameters(null).subscribe();
72     this._aaiService.getAicZones().subscribe();
73     this.store.dispatch(loadProductFamiliesAction());
74   }
75
76
77   createFormGroup(): FormGroup {
78     const formGroup = new FormGroup({
79       globalSubscriberId: new FormControl(
80         Validators.compose([Validators.required])
81       ),
82       productFamilyId: new FormControl(),
83       subscriptionServiceType: new FormControl({value: null,  disabled: true}, Validators.compose([Validators.required])),
84       lcpCloudRegionId: new FormControl({value: null,  disabled: true}, Validators.compose([Validators.required])),
85       tenantId: new FormControl({value: null,  disabled: true}, Validators.compose([Validators.required])),
86       aicZoneId: new FormControl(),
87       projectName: new FormControl(),
88       owningEntityId: new FormControl(Validators.compose([Validators.required])),
89       rollbackOnFailure: new FormControl(null, Validators.required),
90     });
91
92     return formGroup;
93   }
94
95   updateFormGroupControlsWithServiceModel(serviceModel: ServiceModel) {
96     this.serviceInstanceDetailsFormGroup.markAsUntouched();
97
98     if (serviceModel) {
99       this.serviceDetails.isUserProvidedNaming = serviceModel.isUserProvidedNaming;
100       if (serviceModel.isUserProvidedNaming) {
101         this.serviceInstanceDetailsFormGroup.addControl('instanceName', new FormControl('', Validators.compose([Validators.required, NumbersLettersUnderscoreValidator.valid])))
102       }else{
103         this.serviceInstanceDetailsFormGroup.removeControl('instanceName');
104       }
105
106       if (serviceModel.isMultiStepDesign) {
107         this.serviceInstanceDetailsFormGroup.addControl('pause', new FormControl(true));
108       }else{
109         this.serviceInstanceDetailsFormGroup.removeControl('pause');
110       }
111     }
112   }
113
114   updateFormData() {
115     let service = this.store.getState().service;
116     this.servicePopupDataModel.subscribers = service.subscribers;
117     this.servicePopupDataModel.serviceTypes = service.serviceTypes[this.servicePopupDataModel.globalCustomerId];
118     this.servicePopupDataModel.lcpRegions = service.lcpRegionsAndTenants.lcpRegionList;
119     if (this.serviceInstance) {
120       this.servicePopupDataModel.tenants = service.lcpRegionsAndTenants.lcpRegionsTenantsMap[this.serviceInstance.lcpCloudRegionId];
121     }
122     this.servicePopupDataModel.aicZones = service.aicZones;
123     this.servicePopupDataModel.owningEntities = _.get(service.categoryParameters, 'owningEntityList');
124     this.servicePopupDataModel.projects = _.get(service.categoryParameters, 'projectList');
125     this.onDataChanged.next();
126   }
127
128   subscribeToFormChanges(): void {
129     this.serviceInstanceDetailsFormGroup.get('globalSubscriberId').valueChanges.subscribe(val => {
130       this.updateServiceTypes(val);
131       this.setDisabledState(val, 'subscriptionServiceType');
132
133     });
134     this.serviceInstanceDetailsFormGroup.get('subscriptionServiceType').valueChanges.subscribe(val => {
135       this.getTenants(val);
136       this.setDisabledState(val, 'lcpCloudRegionId');
137
138     });
139     this.serviceInstanceDetailsFormGroup.get('lcpCloudRegionId').valueChanges.subscribe(val => {
140       this.setDisabledState(val, 'tenantId');
141       this.updateTenantList(val);
142
143     });
144
145     this.serviceInstanceDetailsFormGroup.get('tenantId').valueChanges.subscribe(val => {
146       this.serviceDetails.tenantName = this.getNameFromListById(this.servicePopupDataModel.tenants, val);
147       this.onDataChanged.next();
148     });
149
150     this.serviceInstanceDetailsFormGroup.get('aicZoneId').valueChanges.subscribe(val => {
151       this.serviceDetails.aicZoneName = this.getNameFromListById(this.servicePopupDataModel.aicZones, val);
152       this.onDataChanged.next();
153     });
154   }
155
156   getNameFromListById(list, id:string ) {
157     if(list && id) {
158       let filterItem = list.filter(item => {
159         return item.id == id;
160       })
161       return filterItem && filterItem[0].name;
162     }
163     return null;
164   }
165
166   setDisabledState(val, field: string): void {
167     if(val) {
168       this.serviceInstanceDetailsFormGroup.controls[field].enable();
169     } else {
170       this.serviceInstanceDetailsFormGroup.controls[field].disable();
171     }
172   }
173
174   isShowingNotificationArea(): boolean {
175     return this.servicesQty > 1;
176   }
177
178   updateServiceTypes(subscriberId) {
179     if (subscriberId) {
180       this.servicePopupDataModel.globalCustomerId = subscriberId;
181       this._aaiService.getServiceTypes(subscriberId).subscribe(() => {
182         this.updateFormData();
183         this.onDataChanged.next();
184       }, (error) => {
185
186       });
187     }
188   }
189
190   updateTenantList(cloudRegionId) {
191     this.servicePopupDataModel.tenants = this.store.getState().service.lcpRegionsAndTenants.lcpRegionsTenantsMap[cloudRegionId];
192     this.onDataChanged.next();
193   }
194
195   getTenants(serviceType) {
196     if (serviceType) {
197       this._aaiService.getLcpRegionsAndTenants(this.servicePopupDataModel.globalCustomerId, serviceType).subscribe(()=>{
198         this.onDataChanged.next();
199       });
200     }
201   }
202
203   onSubmit(formValues): void {
204     formValues.bulkSize = this.servicesQty;
205     let dynamicFields: { [dynamicField: string] : string; };
206     dynamicFields = {};
207     this.dynamicInputs.map(function (x) {
208       let dynamicField: string = x.id;
209       dynamicFields[dynamicField] = formValues[dynamicField];
210       delete formValues[dynamicField];
211     });
212     formValues.instanceParams = [];
213     formValues.instanceParams.push(dynamicFields);
214     formValues.modelInfo = new ModelInfo(this._serviceModel);
215     Object.assign(formValues, this.serviceDetails);
216     this.store.dispatch(updateServiceInstance(formValues, this._serviceModel.uuid));
217     if (this.store.getState().global.flags['FLAG_SETTING_DEFAULTS_IN_DRAWING_BOARD']){
218       this._defaultDataGeneratorService.updateReduxOnFirstSet(this._serviceModel.uuid,formValues);
219     }
220     window.parent.postMessage( {
221       eventId: 'submitIframe',
222       data: {
223         serviceModelId: this._serviceModel.uuid
224       }
225     }, "*");
226     this.closePopup.emit(this._serviceModel.uuid);
227   }
228
229   hasApiError(controlName : string, data : Array<any>){
230     if(!isNullOrUndefined(this.servicePopupDataModel) && !isNullOrUndefined(data)){
231       if(!this.serviceInstanceDetailsFormGroup.controls[controlName].disabled && data.length === 0){
232           return true;
233       }
234     }
235     return false;
236   }
237
238 }