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