Angular upgrade
[osm/NG-UI.git] / src / app / utilities / ns-update / NsUpdateComponent.ts
1 /*
2  Copyright 2020 TATA ELXSI
3
4  Licensed under the Apache License, Version 2.0 (the 'License');
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8     http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15
16  Author: SANDHYA JS (sandhya.j@tataelxsi.co.in)
17 */
18 /**
19  * @file Ns Update Component
20  */
21 import { HttpHeaders } from '@angular/common/http';
22 import { Component, Injector, Input, OnInit } from '@angular/core';
23 import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
24 import { Router } from '@angular/router';
25 import { NgbActiveModal, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
26 import { TranslateService } from '@ngx-translate/core';
27 import { APIURLHEADER, CONFIGCONSTANT, ERRORDATA, MODALCLOSERESPONSEDATA, URLPARAMS } from 'CommonModel';
28 import { environment } from 'environment';
29 import { NSUPDATE, TERMINATEVNF } from 'NSInstanceModel';
30 import { RestService } from 'RestService';
31 import { SharedService, isNullOrUndefined } from 'SharedService';
32 import { VNFD } from 'VNFDModel';
33 import { InstanceData, VNFInstanceDetails } from 'VNFInstanceModel';
34 import { WarningComponent } from 'WarningComponent';
35
36 /**
37  * Creating component
38  * @Component takes NsUpdateComponent.html as template url
39  */
40 @Component({
41     selector: 'app-ns-update',
42     templateUrl: './NsUpdateComponent.html',
43     styleUrls: ['./NsUpdateComponent.scss']
44 })
45 export class NsUpdateComponent implements OnInit {
46     /** To inject services @public */
47     public injector: Injector;
48     /** Instance for active modal service @public */
49     public activeModal: NgbActiveModal;
50     /** Check the loading results @public */
51     public isLoadingResults: Boolean = false;
52     /** Give the message for the loading @public */
53     public message: string = 'PLEASEWAIT';
54     /** FormGroup instance added to the form @ html @public */
55     public nsUpdateForm: FormGroup;
56     /** Items for the member types @public */
57     public memberTypes: {}[];
58     /** Contains objects that is used to hold types of primitive @public */
59     public updateTypeList: {}[] = [];
60     /** Form valid on submit trigger @public */
61     public submitted: boolean = false;
62     /** Give the update type @public */
63     public terminateVnf: string;
64     /** Model value used to hold selected MemberVNFIndex @public */
65     public memberIndexValue: string;
66     /** Form Check vnfdId Section @public */
67     public vnfdIdShow: boolean = false;
68     /** Contains MemberVNFIndex values @public */
69     public memberVnfIndex: {}[] = [];
70     /** Contains MemberVNFIndex content @public */
71     public selectedVnf: {}[];
72     /** Array holds VNFR Data filtered with nsr ID @public */
73     public nsIdFilteredData: {}[] = [];
74     /** Contains vnfdId value @public */
75     public vnfdId: string;
76     /** Contains vnfId value of the selected MemberVnfIndex @public */
77     public vnfID: string;
78     /** Contains version of the selected MemberVnfIndex @public */
79     public version: string;
80     /** Contains version of the vnfId @public */
81     public vnfversion: string;
82     /** Contains vnfInstanceId of the selected MemberVnfIndex  @public */
83     public instanceId: string;
84     /** Selected VNFInstanceId @public */
85     public selectedvnfId: string = '';
86     /** Input contains component objects @private */
87     @Input() private params: URLPARAMS;
88     /** FormBuilder instance added to the formBuilder @private */
89     private formBuilder: FormBuilder;
90     /** Contains tranlsate instance @private */
91     private translateService: TranslateService;
92     /** Instance of the rest service @private */
93     private restService: RestService;
94     /** Controls the header form @private */
95     private headers: HttpHeaders;
96     /** Contains all methods related to shared @private */
97     private sharedService: SharedService;
98     /** Holds the instance of AuthService class of type AuthService @private */
99     private router: Router;
100     /** Instance of the modal service @private */
101     private modalService: NgbModal;
102     constructor(injector: Injector) {
103         this.injector = injector;
104         this.restService = this.injector.get(RestService);
105         this.activeModal = this.injector.get(NgbActiveModal);
106         this.formBuilder = this.injector.get(FormBuilder);
107         this.sharedService = this.injector.get(SharedService);
108         this.translateService = this.injector.get(TranslateService);
109         this.router = this.injector.get(Router);
110         this.modalService = this.injector.get(NgbModal);
111         this.updateTypeList = [
112             {
113                 title: this.translateService.instant('VNFPKGCHANGE'),
114                 value: 'CHANGE_VNFPKG'
115             },
116             {
117                 title: this.translateService.instant('REMOVEVNF'),
118                 value: 'REMOVE_VNF'
119             }
120         ];
121     }
122     /** convenience getter for easy access to form fields */
123     get f(): FormGroup['controls'] { return this.nsUpdateForm.controls; }
124     /**
125      * Lifecyle Hooks the trigger before component is instantiate
126      */
127     public ngOnInit(): void {
128         this.initializeForm();
129         this.getMemberVnfIndex();
130         this.headers = new HttpHeaders({
131             'Content-Type': 'application/json',
132             Accept: 'application/json',
133             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
134         });
135     }
136
137     /** Initialize Ns Update Forms @public */
138     public initializeForm(): void {
139         this.nsUpdateForm = this.formBuilder.group({
140             updateType: [null, [Validators.required]],
141             memberVnfIndex: [null, [Validators.required]],
142             vnfdId: [null, [Validators.required]]
143         });
144     }
145
146     /** Getting MemberVnfIndex using NSDescriptor API @public */
147     public getMemberVnfIndex(): void {
148         this.isLoadingResults = true;
149         const vnfInstanceData: {}[] = [];
150         this.restService.getResource(environment.VNFINSTANCES_URL).subscribe((vnfInstancesData: VNFInstanceDetails[]): void => {
151             vnfInstancesData.forEach((vnfData: VNFInstanceDetails): void => {
152                 const vnfdRef: string = 'vnfd-ref';
153                 const memberIndex: string = 'member-vnf-index-ref';
154                 const nsrId: string = 'nsr-id-ref';
155                 const vnfId: string = 'vnfd-id';
156                 const vnfDataObj: {} =
157                 {
158                     // eslint-disable-next-line security/detect-object-injection
159                     VNFD: vnfData[vnfdRef],
160                     VNFInstanceId: vnfData._id,
161                     // eslint-disable-next-line security/detect-object-injection
162                     MemberIndex: vnfData[memberIndex],
163                     // eslint-disable-next-line security/detect-object-injection
164                     NS: vnfData[nsrId],
165                     // eslint-disable-next-line security/detect-object-injection
166                     VNFID: vnfData[vnfId]
167                 };
168                 vnfInstanceData.push(vnfDataObj);
169             });
170             const nsId: string = 'NS';
171             // eslint-disable-next-line security/detect-object-injection
172             this.nsIdFilteredData = vnfInstanceData.filter((vnfdData: {}[]): boolean => vnfdData[nsId] === this.params.id);
173             this.nsIdFilteredData.forEach((resVNF: InstanceData): void => {
174                 const assignMemberIndex: {} = {
175                     id: resVNF.MemberIndex,
176                     vnfinstanceId: resVNF.VNFInstanceId
177                 };
178                 this.memberVnfIndex.push(assignMemberIndex);
179             });
180             this.memberTypes = this.memberVnfIndex;
181             this.isLoadingResults = false;
182         }, (error: ERRORDATA): void => {
183             this.restService.handleError(error, 'get');
184             this.isLoadingResults = false;
185         });
186     }
187
188     /**
189      *  Fetching the VNFR Information filtered with MemberVnfIndex
190      *  Get the selected VNF Instance ID
191      */
192     public getSelectedVNF(id: string): void {
193         this.instanceId = id;
194         let memberIndexFilteredData: {}[] = [];
195         const memberIndex: string = 'MemberIndex';
196         memberIndexFilteredData = this.nsIdFilteredData.filter((vnfdData: {}[]): boolean =>
197             // eslint-disable-next-line security/detect-object-injection
198             vnfdData[memberIndex] === this.memberIndexValue);
199         const vnfId: string = 'VNFID';
200         const selectedvnfId: string = 'VNFD';
201         this.selectedVnf = memberIndexFilteredData;
202         for (const data of memberIndexFilteredData) {
203             // eslint-disable-next-line security/detect-object-injection
204             this.vnfID = data[vnfId];
205             // eslint-disable-next-line security/detect-object-injection
206             this.selectedvnfId = data[selectedvnfId];
207         }
208     }
209
210     /** Trigger NsUpdate on submit */
211     public triggerNsUpdate(): void {
212         this.submitted = true;
213         this.sharedService.cleanForm(this.nsUpdateForm);
214         if (this.nsUpdateForm.invalid) { return; } // Proceed, onces form is valid
215         this.vnfdId = this.nsUpdateForm.value.vnfdId;
216         this.checkUpdateType();
217     }
218
219     /** Ns Update on submit */
220     public onSubmit(): void {
221         if (this.terminateVnf === 'REMOVE_VNF') {
222             const nsUpdateTerminatePayload: TERMINATEVNF = {
223                 lcmOperationType: 'update',
224                 updateType: this.nsUpdateForm.value.updateType,
225                 nsInstanceId: this.params.id,
226                 removeVnfInstanceId: this.instanceId
227             };
228             this.nsUpdateInitialization(nsUpdateTerminatePayload);
229         } else {
230             const nsUpdatePayload: NSUPDATE = {
231                 lcmOperationType: 'update',
232                 updateType: this.nsUpdateForm.value.updateType,
233                 nsInstanceId: this.params.id,
234                 changeVnfPackageData: {
235                     vnfInstanceId: this.instanceId,
236                     vnfdId: this.nsUpdateForm.value.vnfdId
237                 }
238             };
239             this.nsUpdateInitialization(nsUpdatePayload);
240         }
241     }
242
243     /**
244      *  Open Modal based on selected NS-UPDATE Type
245      */
246     public checkUpdateType(): void {
247         this.isLoadingResults = true;
248         if (this.nsUpdateForm.value.updateType === 'CHANGE_VNFPKG') {
249             this.checkVersion();
250         } else {
251             // eslint-disable-next-line security/detect-non-literal-fs-filename
252             const modalRef: NgbModalRef = this.modalService.open(WarningComponent, { backdrop: 'static' });
253             modalRef.componentInstance.heading = this.translateService.instant('TERMINATEVNF');
254             modalRef.componentInstance.confirmationMessage = this.translateService.instant('TERMINATEVNFCONTENT');
255             modalRef.componentInstance.submitMessage = this.translateService.instant('TERMINATEVNF');
256             modalRef.result.then((result: MODALCLOSERESPONSEDATA): void => {
257                 if (result.message === CONFIGCONSTANT.done) {
258                     this.onSubmit();
259                 }
260             }).catch((): void => {
261                 // Catch Navigation Error
262             });
263         }
264         this.isLoadingResults = false;
265     }
266
267     /** To check the versions are matching or not for 'CHANGE_VNFPKG' type */
268     public checkVersion(): void {
269         this.isLoadingResults = true;
270         const vnfDetails: {}[] = [];
271         this.restService.getResource(environment.VNFPACKAGESCONTENT_URL + '/' + this.vnfdId).subscribe((vnfData: VNFD[]): void => {
272             if (!isNullOrUndefined(vnfData['software-version'])) {
273                 this.version = vnfData['software-version'];
274             }
275             this.restService.getResource(environment.VNFPACKAGESCONTENT_URL).subscribe((vnfDetail: VNFD[]): void => {
276                 vnfDetail.forEach((vnfDatas: VNFD): void => {
277                     const vnfDataObj: {} =
278                     {
279                         VNFID: vnfDatas._id,
280                         version: vnfDatas['software-version']
281                     };
282                     vnfDetails.push(vnfDataObj);
283                 });
284                 let vnfIdFilteredData: {}[] = [];
285                 const vnfID: string = 'VNFID';
286                 const version: string = 'version';
287                 // eslint-disable-next-line security/detect-object-injection
288                 vnfIdFilteredData = vnfDetails.filter((vnfdData: {}[]): boolean => vnfdData[vnfID] === this.vnfID);
289                 for (const data of vnfIdFilteredData) {
290                     // eslint-disable-next-line security/detect-object-injection
291                     this.vnfversion = data[version];
292                 }
293                 if (this.version === this.vnfversion) {
294                     // eslint-disable-next-line security/detect-non-literal-fs-filename
295                     const modalRef: NgbModalRef = this.modalService.open(WarningComponent, { backdrop: 'static' });
296                     modalRef.componentInstance.heading = this.translateService.instant('UPDATENS');
297                     modalRef.componentInstance.confirmationMessage = this.translateService.instant('GENERICCONTENT');
298                     modalRef.componentInstance.submitMessage = this.translateService.instant('UPDATENS');
299                     modalRef.result.then((result: MODALCLOSERESPONSEDATA): void => {
300                         if (result.message === CONFIGCONSTANT.done) {
301                             this.onSubmit();
302                         }
303                     }).catch((): void => { //empty
304                     }
305                     );
306                 } else {
307                     // eslint-disable-next-line security/detect-non-literal-fs-filename
308                     const modalRef: NgbModalRef = this.modalService.open(WarningComponent, { backdrop: 'static' });
309                     modalRef.componentInstance.heading = this.translateService.instant('REDEPLOY');
310                     modalRef.componentInstance.confirmationMessage = this.translateService.instant('REDEPLOYCONTENT');
311                     modalRef.componentInstance.submitMessage = this.translateService.instant('REDEPLOY');
312                     modalRef.result.then((result: MODALCLOSERESPONSEDATA): void => {
313                         if (result.message === CONFIGCONSTANT.done) {
314                             this.onSubmit();
315                         }
316                     }).catch((): void => { //empty
317                     });
318                 }
319             }, (error: ERRORDATA): void => {
320                 this.restService.handleError(error, 'get');
321                 this.isLoadingResults = false;
322             });
323             this.isLoadingResults = false;
324         }, (error: ERRORDATA): void => {
325             this.restService.handleError(error, 'get');
326             this.isLoadingResults = false;
327         });
328     }
329
330     /** Initialize the Ns Update @public */
331     public nsUpdateInitialization(nsUpdatePayload: object): void {
332         this.isLoadingResults = true;
333         const apiURLHeader: APIURLHEADER = {
334             url: environment.NSDINSTANCES_URL + '/' + this.params.id + '/update',
335             httpOptions: { headers: this.headers }
336         };
337         const modalData: MODALCLOSERESPONSEDATA = {
338             message: 'Done'
339         };
340         this.restService.postResource(apiURLHeader, nsUpdatePayload).subscribe((result: {}): void => {
341             this.activeModal.close(modalData);
342             this.router.navigate(['/instances/ns/history-operations/' + this.params.id]).catch((): void => {
343                 // Catch Navigation Error
344             });
345         }, (error: ERRORDATA): void => {
346             this.restService.handleError(error, 'post');
347             this.isLoadingResults = false;
348         });
349     }
350
351     /** To enable or disable vnfdId field @public */
352     public terminateVNF(value: string): void {
353         this.terminateVnf = value;
354         if (this.terminateVnf === 'REMOVE_VNF') {
355             this.vnfdIdShow = true;
356             this.getFormControl('vnfdId').disable();
357         } else {
358             this.vnfdIdShow = false;
359             this.getFormControl('vnfdId').enable();
360         }
361     }
362
363     /** Used to get the AbstractControl of controlName passed @private */
364     private getFormControl(controlName: string): AbstractControl {
365         // eslint-disable-next-line security/detect-object-injection
366         return this.nsUpdateForm.controls[controlName];
367     }
368 }