9dd0d530b8f12fba30c9a0b5bd7ae1c814a6d472
[portal/nonrtric-controlpanel.git] / webapp-frontend / src / app / policy / no-type-policy-instance-dialog / no-type-policy-instance-dialog.component.ts
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2020 Nordix Foundation
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20 import { Component, Inject, OnInit } from '@angular/core';
21 import { FormControl, FormGroup, Validators, ValidatorFn, AbstractControl } from '@angular/forms';
22 import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
23 import { PolicyService } from '../../services/policy/policy.service';
24 import { NotificationService } from '../../services/ui/notification.service';
25 import { UiService } from '../../services/ui/ui.service';
26 import { HttpErrorResponse } from '@angular/common/http';
27 import { ErrorDialogService } from '../../services/ui/error-dialog.service';
28 import * as uuid from 'uuid';
29 import { Rics } from '../../interfaces/ric';
30 import { CreatePolicyInstance } from '../../interfaces/policy.types';
31
32 @Component({
33   selector: 'nrcp-no-type-policy-instance-dialog',
34   templateUrl: './no-type-policy-instance-dialog.component.html',
35   styleUrls: ['./no-type-policy-instance-dialog.component.scss']
36 })
37 export class NoTypePolicyInstanceDialogComponent implements OnInit {
38   instanceForm: FormGroup;
39
40   policyInstanceId: string; // null if not yet created
41   policyJson: string;
42   darkMode: boolean;
43   ric: string;
44   allRicIds: string[] = [];
45
46   constructor(
47     public dialogRef: MatDialogRef<NoTypePolicyInstanceDialogComponent>,
48     private policySvc: PolicyService,
49     private errorService: ErrorDialogService,
50     private notificationService: NotificationService,
51     @Inject(MAT_DIALOG_DATA) private data,
52     private ui: UiService) {
53     this.policyInstanceId = data.instanceId;
54     this.policyJson = data.instanceJson ? this.formatJsonString(data.instanceJson) : '';
55     this.ric = data.ric;
56   }
57
58   ngOnInit() {
59     this.ui.darkModeState.subscribe((isDark) => {
60       this.darkMode = isDark;
61     });
62     this.instanceForm = new FormGroup({
63       'ricSelector': new FormControl(this.ric, [
64         Validators.required
65       ]),
66       'policyJsonTextArea': new FormControl(this.policyJson, [
67         Validators.required,
68         jsonValidator()
69       ])
70     });
71     if (!this.policyInstanceId) {
72       this.getRicIds();
73     }
74   }
75
76   get policyJsonTextArea() { return this.instanceForm.get('policyJsonTextArea'); }
77
78   get ricSelector() { return this.instanceForm.get('ricSelector'); }
79
80   onSubmit() {
81     if (this.policyInstanceId == null) {
82       this.policyInstanceId = uuid.v4();
83     }
84     const self: NoTypePolicyInstanceDialogComponent = this;
85     let createPolicyInstance: CreatePolicyInstance = this.createPolicyInstance(this.policyJsonTextArea.value);
86     this.policySvc.putPolicy(createPolicyInstance).subscribe(
87       {
88         next(_) {
89           self.notificationService.success('Policy without type:' + self.policyInstanceId + ' submitted');
90           self.dialogRef.close();
91         },
92         error(error: HttpErrorResponse) {
93           self.errorService.displayError('Submit failed: ' + error.error);
94         },
95         complete() { }
96       });
97   }
98
99   private createPolicyInstance(policyJson: string): CreatePolicyInstance {
100     let createPolicyInstance = {} as CreatePolicyInstance;
101     createPolicyInstance.policy_data = JSON.parse(policyJson);
102     createPolicyInstance.policy_id = this.policyInstanceId;
103     createPolicyInstance.policytype_id = '';
104     createPolicyInstance.ric_id = (!this.ricSelector.value.ric_id) ? this.ric : this.ricSelector.value.ric_id;
105     createPolicyInstance.service_id = 'controlpanel';
106     return createPolicyInstance;
107   }
108
109   getRicIds() {
110     const self: NoTypePolicyInstanceDialogComponent = this;
111     this.policySvc.getRics('').subscribe(
112       {
113         next(value: Rics) {
114           value.rics.forEach(ric => {
115             self.allRicIds.push(ric.ric_id);
116           });
117         }
118       });
119   }
120
121   private formatJsonString(jsonToFormat: any): string {
122     return JSON.stringify(jsonToFormat, null, 2);
123   }
124
125   formatJsonInput() {
126     this.policyJson = this.formatJsonString(JSON.parse(this.policyJsonTextArea.value));
127   }
128 }
129
130 export function jsonValidator(): ValidatorFn {
131   return (control: AbstractControl): { [key: string]: any } | null => {
132     const notValid = !isJsonValid(control.value);
133     return notValid ? { 'invalidJson': { value: control.value } } : null;
134   };
135 }
136
137 export function isJsonValid(json: string): boolean {
138   try {
139     if (json != null) {
140       JSON.parse(json);
141       return true;
142     } else {
143       return false;
144     }
145   } catch (jsonError) {
146     return false;
147   }
148 }