Feature 10912, 10916: NS Update
[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 } from 'SharedService';
32 import { isNullOrUndefined } from 'util';
33 import { VNFD } from 'VNFDModel';
34 import { VNFInstanceDetails } from 'VNFInstanceModel';
35 import { WarningComponent } from 'WarningComponent';
36
37 /**
38  * Creating component
39  * @Component takes NsUpdateComponent.html as template url
40  */
41 @Component({
42     selector: 'app-ns-update',
43     templateUrl: './NsUpdateComponent.html',
44     styleUrls: ['./NsUpdateComponent.scss']
45 })
46 export class NsUpdateComponent implements OnInit {
47     /** To inject services @public */
48     public injector: Injector;
49     /** Instance for active modal service @public */
50     public activeModal: NgbActiveModal;
51     /** Check the loading results @public */
52     public isLoadingResults: Boolean = false;
53     /** Give the message for the loading @public */
54     public message: string = 'PLEASEWAIT';
55     /** FormGroup instance added to the form @ html @public */
56     public nsUpdateForm: FormGroup;
57     /** Items for the member types @public */
58     public memberTypes: {}[];
59     /** Contains objects that is used to hold types of primitive @public */
60     public updateTypeList: {}[] = [];
61     /** Form valid on submit trigger @public */
62     public submitted: boolean = false;
63     /** Give the update type @public */
64     public terminateVnf: string;
65     /** Model value used to hold selected MemberVNFIndex @public */
66     public memberIndexValue: string;
67     /** Form Check vnfdId Section @public */
68     public vnfdIdShow: boolean = false;
69     /** Contains MemberVNFIndex values @public */
70     public memberVnfIndex: {}[] = [];
71     /** Array holds VNFR Data filtered with nsr ID @public */
72     public nsIdFilteredData: {}[] = [];
73     /** Contains vnfdId value @public */
74     public vnfdId: string;
75     /** Contains vnfId value of the selected MemberVnfIndex @public */
76     public vnfID: string;
77     /** Contains version of the selected MemberVnfIndex @public */
78     public version: string;
79     /** Contains version of the vnfId @public */
80     public vnfversion: string;
81     /** Contains vnfInstanceId of the selected MemberVnfIndex  @public */
82     public instanceId: string;
83     /** Selected VNFInstanceId @public */
84     public selectedvnfId: string = '';
85     /** Input contains component objects @private */
86     @Input() private params: URLPARAMS;
87     /** FormBuilder instance added to the formBuilder @private */
88     private formBuilder: FormBuilder;
89     /** Contains tranlsate instance @private */
90     private translateService: TranslateService;
91     /** Instance of the rest service @private */
92     private restService: RestService;
93     /** Controls the header form @private */
94     private headers: HttpHeaders;
95     /** Contains all methods related to shared @private */
96     private sharedService: SharedService;
97     /** Holds the instance of AuthService class of type AuthService @private */
98     private router: Router;
99     /** Instance of the modal service @private */
100     private modalService: NgbModal;
101     constructor(injector: Injector) {
102         this.injector = injector;
103         this.restService = this.injector.get(RestService);
104         this.activeModal = this.injector.get(NgbActiveModal);
105         this.formBuilder = this.injector.get(FormBuilder);
106         this.sharedService = this.injector.get(SharedService);
107         this.translateService = this.injector.get(TranslateService);
108         this.router = this.injector.get(Router);
109         this.modalService = this.injector.get(NgbModal);
110         this.updateTypeList = [
111             {
112                 title: this.translateService.instant('VNFPKGCHANGE'),
113                 value: 'CHANGE_VNFPKG'
114             },
115             {
116                 title: this.translateService.instant('REMOVEVNF'),
117                 value: 'REMOVE_VNF'
118             }
119         ];
120     }
121     /** convenience getter for easy access to form fields */
122     get f(): FormGroup['controls'] { return this.nsUpdateForm.controls; }
123     /**
124      * Lifecyle Hooks the trigger before component is instantiate
125      */
126     public ngOnInit(): void {
127         this.initializeForm();
128         this.getMemberVnfIndex();
129         this.headers = new HttpHeaders({
130             'Content-Type': 'application/json',
131             Accept: 'application/json',
132             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
133         });
134     }
135
136     /** Initialize Ns Update Forms @public */
137     public initializeForm(): void {
138         this.nsUpdateForm = this.formBuilder.group({
139             updateType: [null, [Validators.required]],
140             memberVnfIndex: [null, [Validators.required]],
141             vnfdId: [null, [Validators.required]]
142         });
143     }
144
145     /** Getting MemberVnfIndex using NSDescriptor API @public */
146     public getMemberVnfIndex(): void {
147         const vnfInstanceData: {}[] = [];
148         this.restService.getResource(environment.VNFINSTANCES_URL).subscribe((vnfInstancesData: VNFInstanceDetails[]): void => {
149             vnfInstancesData.forEach((vnfData: VNFInstanceDetails): void => {
150                 const vnfDataObj: {} =
151                 {
152                     VNFD: vnfData['vnfd-ref'],
153                     VNFInstanceId: vnfData._id,
154                     MemberIndex: vnfData['member-vnf-index-ref'],
155                     NS: vnfData['nsr-id-ref'],
156                     VNFID: vnfData['vnfd-id']
157                 };
158                 vnfInstanceData.push(vnfDataObj);
159             });
160             const nsId: string = 'NS';
161             this.nsIdFilteredData = vnfInstanceData.filter((vnfdData: {}[]): boolean => vnfdData[nsId] === this.params.id);
162             this.nsIdFilteredData.forEach((resVNF: {}[]): void => {
163                 const memberIndex: string = 'MemberIndex';
164                 const vnfinstanceID: string = 'VNFInstanceId';
165                 const assignMemberIndex: {} = {
166                     id: resVNF[memberIndex],
167                     vnfinstanceId: resVNF[vnfinstanceID]
168                 };
169                 this.memberVnfIndex.push(assignMemberIndex);
170             });
171             this.memberTypes = this.memberVnfIndex;
172             this.isLoadingResults = false;
173         }, (error: ERRORDATA): void => {
174             this.restService.handleError(error, 'get');
175             this.isLoadingResults = false;
176         });
177     }
178
179     /**
180      *  Fetching the VNFR Information filtered with MemberVnfIndex
181      *  Get the selected VNF Instance ID
182      */
183     public getSelectedVNF(id: string): void {
184         this.instanceId = id;
185         let memberIndexFilteredData: {}[] = [];
186         const memberIndex: string = 'MemberIndex';
187         memberIndexFilteredData = this.nsIdFilteredData.filter((vnfdData: {}[]): boolean =>
188             vnfdData[memberIndex] === this.memberIndexValue);
189         const vnfId: string = 'VNFID';
190         const selectedvnfId: string = 'VNFD';
191         for (const data of memberIndexFilteredData) {
192             this.vnfID = data[vnfId];
193             this.selectedvnfId = data[selectedvnfId];
194         }
195     }
196
197     /** Trigger NsUpdate on submit */
198     public triggerNsUpdate(): void {
199         this.submitted = true;
200         this.sharedService.cleanForm(this.nsUpdateForm);
201         if (this.nsUpdateForm.invalid) { return; } // Proceed, onces form is valid
202         this.vnfdId = this.nsUpdateForm.value.vnfdId;
203         this.checkUpdateType();
204     }
205
206     /** Ns Update on submit */
207     public onSubmit(): void {
208         if (this.terminateVnf === 'REMOVE_VNF') {
209             const nsUpdateTerminatePayload: TERMINATEVNF = {
210                 lcmOperationType: 'update',
211                 updateType: this.nsUpdateForm.value.updateType,
212                 nsInstanceId: this.params.id,
213                 removeVnfInstanceId: this.instanceId
214             };
215             this.nsUpdateInitialization(nsUpdateTerminatePayload);
216         } else {
217             const nsUpdatePayload: NSUPDATE = {
218                 lcmOperationType: 'update',
219                 updateType: this.nsUpdateForm.value.updateType,
220                 nsInstanceId: this.params.id,
221                 changeVnfPackageData: {
222                     vnfInstanceId: this.instanceId,
223                     vnfdId: this.nsUpdateForm.value.vnfdId
224                 }
225             };
226             this.nsUpdateInitialization(nsUpdatePayload);
227         }
228     }
229
230     /**
231      *  Open Modal based on selected NS-UPDATE Type
232      */
233     public checkUpdateType(): void {
234         this.isLoadingResults = true;
235         if (this.nsUpdateForm.value.updateType === 'CHANGE_VNFPKG') {
236             this.checkVersion();
237         } else {
238             const modalRef: NgbModalRef = this.modalService.open(WarningComponent, { backdrop: 'static' });
239             modalRef.componentInstance.heading = this.translateService.instant('TERMINATEVNF');
240             modalRef.componentInstance.confirmationMessage = this.translateService.instant('TERMINATEVNFCONTENT');
241             modalRef.componentInstance.submitMessage = this.translateService.instant('TERMINATEVNF');
242             modalRef.result.then((result: MODALCLOSERESPONSEDATA): void => {
243                 if (result.message === CONFIGCONSTANT.done) {
244                     this.onSubmit();
245                 }
246             }).catch();
247         }
248         this.isLoadingResults = false;
249     }
250
251     /** To check the versions are matching or not for 'CHANGE_VNFPKG' type */
252     public checkVersion(): void {
253         this.isLoadingResults = true;
254         const vnfDetails: {}[] = [];
255         this.restService.getResource(environment.VNFPACKAGESCONTENT_URL + '/' + this.vnfdId).subscribe((vnfData: VNFD[]): void => {
256             if (!isNullOrUndefined(vnfData['software-version'])) {
257                 this.version = vnfData['software-version'];
258             }
259             this.restService.getResource(environment.VNFPACKAGESCONTENT_URL).subscribe((vnfDetail: VNFD[]): void => {
260                 vnfDetail.forEach((vnfDatas: VNFD): void => {
261                     const vnfDataObj: {} =
262                     {
263                         VNFID: vnfDatas._id,
264                         version: vnfDatas['software-version']
265                     };
266                     vnfDetails.push(vnfDataObj);
267                 });
268                 let vnfIdFilteredData: {}[] = [];
269                 const vnfID: string = 'VNFID';
270                 const version: string = 'version';
271                 vnfIdFilteredData = vnfDetails.filter((vnfdData: {}[]): boolean => vnfdData[vnfID] === this.vnfID);
272                 for (const data of vnfIdFilteredData) {
273                     this.vnfversion = data[version];
274                 }
275                 if (this.version === this.vnfversion) {
276                     const modalRef: NgbModalRef = this.modalService.open(WarningComponent, { backdrop: 'static' });
277                     modalRef.componentInstance.heading = this.translateService.instant('UPDATEPOLICIES');
278                     modalRef.componentInstance.confirmationMessage = this.translateService.instant('UPDATEPOLICIESCONTENT');
279                     modalRef.componentInstance.submitMessage = this.translateService.instant('UPDATEPOLICIES');
280                     modalRef.result.then((result: MODALCLOSERESPONSEDATA): void => {
281                         if (result.message === CONFIGCONSTANT.done) {
282                             this.onSubmit();
283                         }
284                     }).catch();
285                 } else {
286                     const modalRef: NgbModalRef = this.modalService.open(WarningComponent, { backdrop: 'static' });
287                     modalRef.componentInstance.heading = this.translateService.instant('REDEPLOY');
288                     modalRef.componentInstance.confirmationMessage = this.translateService.instant('REDEPLOYCONTENT');
289                     modalRef.componentInstance.submitMessage = this.translateService.instant('REDEPLOY');
290                     modalRef.result.then((result: MODALCLOSERESPONSEDATA): void => {
291                         if (result.message === CONFIGCONSTANT.done) {
292                             this.onSubmit();
293                         }
294                     }).catch();
295                 }
296             }, (error: ERRORDATA): void => {
297                 this.restService.handleError(error, 'get');
298                 this.isLoadingResults = false;
299             });
300             this.isLoadingResults = false;
301         }, (error: ERRORDATA): void => {
302             this.restService.handleError(error, 'get');
303             this.isLoadingResults = false;
304         });
305     }
306
307     /** Initialize the Ns Update @public */
308     public nsUpdateInitialization(nsUpdatePayload: object): void {
309         this.isLoadingResults = true;
310         const apiURLHeader: APIURLHEADER = {
311             url: environment.NSDINSTANCES_URL + '/' + this.params.id + '/update',
312             httpOptions: { headers: this.headers }
313         };
314         const modalData: MODALCLOSERESPONSEDATA = {
315             message: 'Done'
316         };
317         this.restService.postResource(apiURLHeader, nsUpdatePayload).subscribe((result: {}): void => {
318             this.activeModal.close(modalData);
319             this.router.navigate(['/instances/ns/history-operations/' + this.params.id]).catch();
320         }, (error: ERRORDATA): void => {
321             this.restService.handleError(error, 'post');
322             this.isLoadingResults = false;
323         });
324     }
325
326     /** To enable or disable vnfdId field @public */
327     public terminateVNF(value: string): void {
328         this.terminateVnf = value;
329         if (this.terminateVnf === 'REMOVE_VNF') {
330             this.vnfdIdShow = true;
331             this.getFormControl('vnfdId').disable();
332         } else {
333             this.vnfdIdShow = false;
334             this.getFormControl('vnfdId').enable();
335         }
336     }
337
338     /** Used to get the AbstractControl of controlName passed @private */
339     private getFormControl(controlName: string): AbstractControl {
340         return this.nsUpdateForm.controls[controlName];
341     }
342 }