60ffbd3e724760022f98d863c704e9c2c8269cfe
[portal/nonrtric-controlpanel.git] / webapp-frontend / src / app / policy-control / policy-instance-dialog.component.ts
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 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 { animate, state, style, transition, trigger } from '@angular/animations';
21 import { AfterViewInit, Component, Inject, OnInit, ViewChild } from '@angular/core';
22 import { MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
23 import { MatMenuTrigger } from '@angular/material/menu';
24 import { JsonPointer } from 'angular6-json-schema-form';
25 import * as uuid from 'uuid';
26 import { PolicyInstance, PolicyType } from '../interfaces/policy.types';
27 import { PolicyService } from '../services/policy/policy.service';
28 import { ErrorDialogService } from '../services/ui/error-dialog.service';
29 import { NotificationService } from './../services/ui/notification.service';
30 import { UiService } from '../services/ui/ui.service';
31 import { HttpErrorResponse } from '@angular/common/http';
32
33
34 @Component({
35     selector: 'rd-policy-instance-dialog',
36     templateUrl: './policy-instance-dialog.component.html',
37     styleUrls: ['./policy-instance-dialog.component.scss'],
38     animations: [
39         trigger('expandSection', [
40             state('in', style({ height: '*' })),
41             transition(':enter', [
42                 style({ height: 0 }), animate(100),
43             ]),
44             transition(':leave', [
45                 style({ height: '*' }),
46                 animate(100, style({ height: 0 })),
47             ]),
48         ]),
49     ],
50 })
51 export class PolicyInstanceDialogComponent implements OnInit, AfterViewInit {
52
53     formActive = false;
54     isVisible = {
55         form: true,
56         json: false,
57         schema: false
58     };
59
60     jsonFormStatusMessage = 'Loading form...';
61     jsonSchemaObject: any = {};
62     jsonObject: any = {};
63
64
65     jsonFormOptions: any = {
66         addSubmit: false, // Add a submit button if layout does not have one
67         debug: false, // Don't show inline debugging information
68         loadExternalAssets: true, // Load external css and JavaScript for frameworks
69         returnEmptyFields: false, // Don't return values for empty input fields
70         setSchemaDefaults: true, // Always use schema defaults for empty fields
71         defautWidgetOptions: { feedback: true }, // Show inline feedback icons
72     };
73
74     liveFormData: any = {};
75     formValidationErrors: any;
76     formIsValid = false;
77
78     @ViewChild(MatMenuTrigger, { static: true }) menuTrigger: MatMenuTrigger;
79
80     policyInstanceId: string; // null if not yet created
81     policyTypeName: string;
82     darkMode: boolean;
83     ric: string;
84     allRics: string[];
85
86     private fetchRics() {
87         console.log('fetchRics ' + this.policyTypeName);
88         const self: PolicyInstanceDialogComponent = this;
89         this.dataService.getRics(this.policyTypeName).subscribe(
90             {
91                 next(value) {
92                     self.allRics = value;
93                     console.log(value);
94                 },
95                 error(error: HttpErrorResponse) {
96                     self.errorService.displayError('Fetching of rics failed: ' + error.message);
97                 },
98                 complete() { }
99             });
100     }
101
102     constructor(
103         private dataService: PolicyService,
104         private errorService: ErrorDialogService,
105         private notificationService: NotificationService,
106         @Inject(MAT_DIALOG_DATA) private data,
107         private dialogRef: MatDialogRef<PolicyInstanceDialogComponent>,
108         private ui: UiService) {
109         this.formActive = false;
110         this.policyInstanceId = data.instanceId;
111         this.policyTypeName = data.name;
112         this.jsonSchemaObject = data.createSchema;
113         this.jsonObject = this.parseJson(data.instanceJson);
114         this.ric = data.ric;
115     }
116
117     ngOnInit() {
118         this.jsonFormStatusMessage = 'Init';
119         this.formActive = true;
120         this.ui.darkModeState.subscribe((isDark) => {
121             this.darkMode = isDark;
122         });
123         if (!this.policyInstanceId) {
124             this.fetchRics();
125         }
126         if (this.isSchemaEmpty()) {
127             // Empty schema, hide form, show json instead
128             this.isVisible.form = false;
129             this.isVisible.json = true;
130         }
131     }
132
133     ngAfterViewInit() {
134     }
135
136     private isSchemaEmpty(): boolean {
137         return Object.keys(this.jsonSchemaObject).length === 0;
138     }
139
140     onSubmit() {
141         if (this.policyInstanceId == null) {
142             this.policyInstanceId = uuid.v4();
143         }
144         const policyJson: string = this.prettyLiveFormData;
145         const self: PolicyInstanceDialogComponent = this;
146         this.dataService.putPolicy(this.policyTypeName, this.policyInstanceId, policyJson, this.ric).subscribe(
147             {
148                 next(value) {
149                     self.notificationService.success('Policy ' + self.policyTypeName + ':' + self.policyInstanceId + ' submitted');
150                 },
151                 error(error: HttpErrorResponse) {
152                     self.errorService.displayError('Submit failed: ' + error.error);
153                 },
154                 complete() { }
155             });
156     }
157
158     onClose() {
159         this.dialogRef.close();
160     }
161
162     public onChanges(formData: any) {
163         this.liveFormData = formData;
164     }
165
166     get prettyLiveFormData(): string {
167         if (this.isSchemaEmpty()) {
168             return this.jsonAsString;
169         }
170         return JSON.stringify(this.liveFormData, null, 2);
171     }
172
173     get schemaAsString(): string {
174         return JSON.stringify(this.jsonSchemaObject, null, 2);
175     }
176
177     get jsonAsString(): string {
178         return JSON.stringify(this.jsonObject, null, 2);
179     }
180
181     isValid(isValid: boolean): void {
182         this.formIsValid = isValid;
183     }
184
185     validationErrors(validationErrors: any): void {
186         this.formValidationErrors = validationErrors;
187     }
188
189     get prettyValidationErrors() {
190         if (!this.formValidationErrors) { return null; }
191         const errorArray = [];
192         for (const error of this.formValidationErrors) {
193             const message = error.message;
194             const dataPathArray = JsonPointer.parse(error.dataPath);
195             if (dataPathArray.length) {
196                 let field = dataPathArray[0];
197                 for (let i = 1; i < dataPathArray.length; i++) {
198                     const key = dataPathArray[i];
199                     field += /^\d+$/.test(key) ? `[${key}]` : `.${key}`;
200                 }
201                 errorArray.push(`${field}: ${message}`);
202             } else {
203                 errorArray.push(message);
204             }
205         }
206         return errorArray.join('<br>');
207     }
208
209     private parseJson(str: string): string {
210         try {
211             if (str != null) {
212                 return JSON.parse(str);
213             }
214         } catch (jsonError) {
215             this.jsonFormStatusMessage =
216                 'Invalid JSON\n' +
217                 'parser returned:\n\n' + jsonError;
218         }
219         return null;
220     }
221
222     public toggleVisible(item: string) {
223         this.isVisible[item] = !this.isVisible[item];
224     }
225 }
226
227 export function getPolicyDialogProperties(policyType: PolicyType, instance: PolicyInstance, darkMode: boolean): MatDialogConfig {
228     const createSchema = policyType.schemaObject;
229     const instanceId = instance ? instance.id : null;
230     const instanceJson = instance ? instance.json : null;
231     const name = policyType.name;
232     const ric = instance ? instance.ric : null;
233     return {
234         maxWidth: '1200px',
235         maxHeight: '900px',
236         width: '900px',
237         role: 'dialog',
238         disableClose: false,
239         panelClass: darkMode ? 'dark-theme' : '',
240         data: {
241             createSchema,
242             instanceId,
243             instanceJson,
244             name,
245             ric
246         }
247     };
248 }
249