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