288ba2e112429c90991d7f1e9035f4487a315124
[portal/nonrtric-controlpanel.git] / webapp-frontend / src / app / policy-control / 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 { 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 { Ric } 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   allRics: Ric[];
45
46   constructor(
47     private policySvc: PolicyService,
48     private errorService: ErrorDialogService,
49     private notificationService: NotificationService,
50     @Inject(MAT_DIALOG_DATA) private data,
51     private ui: UiService) {
52     this.policyInstanceId = data.instanceId;
53     this.policyJson = data.instanceJson ? this.formatJsonString(data.instanceJson) : '';
54     this.ric = data.ric;
55   }
56
57   ngOnInit() {
58     this.ui.darkModeState.subscribe((isDark) => {
59       this.darkMode = isDark;
60     });
61     this.instanceForm = new FormGroup({
62       'ricSelector': new FormControl(this.ric, [
63         Validators.required
64       ]),
65       'policyJsonTextArea': new FormControl(this.policyJson, [
66         Validators.required,
67         jsonValidator()
68       ])
69     });
70     if (!this.policyInstanceId) {
71       this.fetchRics();
72     }
73   }
74
75   get policyJsonTextArea() { return this.instanceForm.get('policyJsonTextArea'); }
76
77   get ricSelector() { return this.instanceForm.get('ricSelector'); }
78
79   onSubmit() {
80     if (this.policyInstanceId == null) {
81       this.policyInstanceId = uuid.v4();
82     }
83     const self: NoTypePolicyInstanceDialogComponent = this;
84     let createPolicyInstance = this.createPolicyInstance(this.policyJsonTextArea.value);
85     this.policySvc.putPolicy(createPolicyInstance).subscribe(
86       {
87         next(_) {
88           self.notificationService.success('Policy without type:' + self.policyInstanceId + ' submitted');
89         },
90         error(error: HttpErrorResponse) {
91           self.errorService.displayError('Submit failed: ' + error.error);
92         },
93         complete() { }
94       });
95   }
96
97   private createPolicyInstance(policyJson: string) {
98     let createPolicyInstance = {} as CreatePolicyInstance;
99     createPolicyInstance.policy_data = JSON.parse(policyJson);
100     createPolicyInstance.policy_id = this.policyInstanceId;
101     createPolicyInstance.policytype_id = '';
102     createPolicyInstance.ric_id = (!this.ricSelector.value.ric_id) ? this.ric : this.ricSelector.value.ric_id;
103     createPolicyInstance.service_id = 'controlpanel';
104     return createPolicyInstance;
105   }
106
107   private fetchRics() {
108     const self: NoTypePolicyInstanceDialogComponent = this;
109     this.policySvc.getRics('').subscribe(
110       {
111         next(value: Ric[]) {
112           self.allRics = value;
113           console.log(value);
114         },
115         error(error: HttpErrorResponse) {
116           self.errorService.displayError('Fetching of rics failed: ' + error.message);
117         },
118         complete() { }
119       });
120   }
121
122   private formatJsonString(jsonToFormat: any) {
123     return JSON.stringify(jsonToFormat, null, 2);
124   }
125
126   formatJsonInput() {
127     this.policyJson = this.formatJsonString(JSON.parse(this.policyJsonTextArea.value));
128   }
129 }
130
131 export function jsonValidator(): ValidatorFn {
132   return (control: AbstractControl): { [key: string]: any } | null => {
133     const notValid = !isJsonValid(control.value);
134     return notValid ? { 'invalidJson': { value: control.value } } : null;
135   };
136 }
137
138 export function isJsonValid(json: string) {
139   try {
140     if (json != null) {
141       JSON.parse(json);
142       return true;
143     }
144   } catch (jsonError) {
145     return false;
146   }
147 }