1 import { Action } from '../../../../framework/src/flux/action';
2 import { Dispatch } from '../../../../framework/src/flux/store';
3 import { IApplicationStoreState } from '../../../../framework/src/store/applicationStore';
4 import { PushAction, ReplaceAction } from '../../../../framework/src/actions/navigationActions';
5 import { AddErrorInfoAction } from '../../../../framework/src/actions/errorActions';
7 import { DisplayModeType, DisplaySpecification } from '../handlers/viewDescriptionHandler';
9 import { restService } from '../services/restServices';
10 import { YangParser } from '../yang/yangParser';
11 import { Module } from '../models/yang';
15 isViewElementReference,
18 } from '../models/uiModels';
25 getReferencedDataList,
26 resolveViewDescription,
27 } from '../utilities/viewEngineHelper';
29 export class EnableValueSelector extends Action {
30 constructor(public listSpecification: ViewSpecification, public listData: any[], public keyProperty: string, public onValueSelected : (value: any) => void ) {
35 export class SetCollectingSelectionData extends Action {
36 constructor(public busy: boolean) {
41 export class SetSelectedValue extends Action {
42 constructor(public value: any) {
47 export class UpdateDeviceDescription extends Action {
48 constructor( public nodeId: string, public modules: { [name:string]: Module }, public views: ViewSpecification[]) {
53 export class UpdateViewDescription extends Action {
54 constructor(public vPath: string, public viewData: any, public displaySpecification: DisplaySpecification = { displayMode: DisplayModeType.doNotDisplay }) {
59 export class UpdateOutputData extends Action {
60 constructor(public outputData: any) {
65 export const updateNodeIdAsyncActionCreator = (nodeId: string) => async (dispatch: Dispatch, _getState: () => IApplicationStoreState ) => {
67 dispatch(new UpdateDeviceDescription('', {}, []));
68 dispatch(new SetCollectingSelectionData(true));
70 const { availableCapabilities, unavailableCapabilities, importOnlyModules } = await restService.getCapabilitiesByMountId(nodeId);
72 if (!availableCapabilities || availableCapabilities.length <= 0) {
73 dispatch(new SetCollectingSelectionData(false));
74 dispatch(new UpdateDeviceDescription(nodeId, {}, []));
75 dispatch(new UpdateViewDescription('', [], {
76 displayMode: DisplayModeType.displayAsMessage,
77 renderMessage: `NetworkElement : "${nodeId}" has no capabilities.`,
79 throw new Error(`NetworkElement : [${nodeId}] has no capabilities.`);
82 const parser = new YangParser(
84 availableCapabilities.reduce((acc, cur) => {
85 acc[cur.capability] = cur.version;
87 }, {} as { [key: string]: string }),
88 unavailableCapabilities || undefined,
89 importOnlyModules || undefined,
92 for (let i = 0; i < availableCapabilities.length; ++i) {
93 const capRaw = availableCapabilities[i];
95 await parser.addCapability(capRaw.capability, capRaw.version);
97 console.error(`Error in ${capRaw.capability} ${capRaw.version}`, err);
101 parser.postProcess();
103 dispatch(new SetCollectingSelectionData(false));
105 if (process.env.NODE_ENV === 'development' ) {
106 console.log(parser, parser.modules, parser.views);
109 return dispatch(new UpdateDeviceDescription(nodeId, parser.modules, parser.views));
112 export const postProcessDisplaySpecificationActionCreator = (vPath: string, viewData: any, displaySpecification: DisplaySpecification) => async (dispatch: Dispatch, _getState: () => IApplicationStoreState) => {
114 if (displaySpecification.displayMode === DisplayModeType.displayAsObject) {
115 displaySpecification = {
116 ...displaySpecification,
117 viewSpecification: await filterViewElements(vPath, viewData, displaySpecification.viewSpecification),
121 dispatch(new UpdateViewDescription(vPath, viewData, displaySpecification));
124 export const updateViewActionAsyncCreator = (vPath: string) => async (dispatch: Dispatch, getState: () => IApplicationStoreState) => {
125 const pathParts = splitVPath(vPath, /(?:([^\/\["]+)(?:\[([^\]]*)\])?)/g); // 1 = property / 2 = optional key
126 const { configuration: { deviceDescription: { nodeId, modules, views } } } = getState();
127 let dataPath = `/rests/data/network-topology:network-topology/topology=topology-netconf/node=${nodeId}/yang-ext:mount`;
129 let inputViewSpecification: ViewSpecification | undefined = undefined;
130 let outputViewSpecification: ViewSpecification | undefined = undefined;
132 let viewSpecification: ViewSpecification = views[0];
133 let viewElement: ViewElement;
135 let dataMember: string;
136 let extractList: boolean = false;
138 let currentNS: string | null = null;
139 let defaultNS: string | null = null;
141 dispatch(new SetCollectingSelectionData(true));
143 for (let ind = 0; ind < pathParts.length; ++ind) {
144 const [property, key] = pathParts[ind];
145 const namespaceInd = property && property.indexOf(':') || -1;
146 const namespace: string | null = namespaceInd > -1 ? (currentNS = property.slice(0, namespaceInd)) : currentNS;
148 if (ind === 0) { defaultNS = namespace; }
150 viewElement = viewSpecification.elements[property] || viewSpecification.elements[`${namespace}:${property}`];
151 if (!viewElement) throw Error('Property [' + property + '] does not exist.');
153 if (viewElement.isList && !key) {
154 if (pathParts.length - 1 > ind) {
155 dispatch(new SetCollectingSelectionData(false));
156 throw new Error('No key for list [' + property + ']');
157 } else if (vPath.endsWith('[]') && pathParts.length - 1 === ind) {
159 // empty key is used for new element
160 if (viewElement && 'viewId' in viewElement) viewSpecification = views[+viewElement.viewId];
161 const data = Object.keys(viewSpecification.elements).reduce<{ [name: string]: any }>((acc, cur) => {
162 const elm = viewSpecification.elements[cur];
164 acc[elm.id] = elm.default || '';
169 // create display specification
170 const ds: DisplaySpecification = {
171 displayMode: DisplayModeType.displayAsObject,
172 viewSpecification: resolveViewDescription(defaultNS, vPath, viewSpecification),
173 keyProperty: isViewElementList(viewElement!) && viewElement.key || undefined,
176 // update display specification
177 return dispatch(postProcessDisplaySpecificationActionCreator(vPath, data, ds));
179 if (viewElement && isViewElementList(viewElement) && viewSpecification.parentView === '0') {
180 // check if there is a reference as key
181 const listSpecification = views[+viewElement.viewId];
182 const keyElement = viewElement.key && listSpecification.elements[viewElement.key];
183 if (keyElement && isViewElementReference(keyElement)) {
184 const refList = await getReferencedDataList(keyElement.referencePath, dataPath, modules, views);
186 throw new Error(`Could not find refList for [${keyElement.referencePath}].`);
189 throw new Error(`Key property not found for [${keyElement.referencePath}].`);
191 dispatch(new EnableValueSelector(refList.view, refList.data, refList.key, (refKey) => {
192 window.setTimeout(() => dispatch(new PushAction(`${vPath}[${refKey.replace(/\//ig, '%2F')}]`)));
195 // Found a list at root level of a module w/o a reference key.
196 dataPath += `?content=config&fields=${encodeURIComponent(viewElement.id)}(${encodeURIComponent(viewElement.key || '')})`;
197 const restResult = (await restService.getConfigData(dataPath));
198 if (restResult && restResult.status === 200 && restResult.data && restResult.data[viewElement.id] ) {
199 // spoof the not existing view here
200 const refData = restResult.data[viewElement.id];
201 const refView : ViewSpecification = {
207 [viewElement.key!] : {
211 label: viewElement.key,
213 } as ViewElementString,
216 dispatch(new EnableValueSelector(refView, refData, viewElement.key!, (refKey) => {
217 window.setTimeout(() => dispatch(new PushAction(`${vPath}[${refKey.replace(/\//ig, '%2F')}]`)));
220 throw new Error('Found a list at root level of a module and could not determine the keys.');
222 dispatch(new SetCollectingSelectionData(false));
228 // normal case & replaces unicode %2C if present
229 dataPath += `/${property}${key ? `=${key.replace(/\%2C/g, ',').replace(/\//ig, '%2F')}` : ''}`;
231 // in case of the root element the required namespace will be added later,
232 // while extracting the data
233 dataMember = namespace === defaultNS
235 : `${namespace}:${viewElement.label}`;
239 if (viewElement && 'viewId' in viewElement) {
240 viewSpecification = views[+viewElement.viewId];
241 } else if (viewElement.uiType === 'rpc') {
242 viewSpecification = views[+(viewElement.inputViewId || 0)];
244 // create new instance & flaten
245 inputViewSpecification = viewElement.inputViewId != null && {
246 ...views[+(viewElement.inputViewId || 0)],
247 elements: flattenViewElements(defaultNS, '', views[+(viewElement.inputViewId || 0)].elements, views, viewElement.label),
249 outputViewSpecification = viewElement.outputViewId != null && {
250 ...views[+(viewElement.outputViewId || 0)],
251 elements: flattenViewElements(defaultNS, '', views[+(viewElement.outputViewId || 0)].elements, views, viewElement.label),
258 // do not get any data from netconf if there is no view specified || this is the root element [0] || this is an rpc
259 if (viewSpecification && !(viewSpecification.id === '0' || viewElement!.uiType === 'rpc')) {
260 const restResult = (await restService.getConfigData(dataPath));
261 if (!restResult.data) {
262 // special case: if this is a list without any response
263 if (extractList && restResult.status === 404) {
264 if (!isViewElementList(viewElement!)) {
265 throw new Error(`vPath: [${vPath}]. ViewElement has no key.`);
267 // create display specification
268 const ds: DisplaySpecification = {
269 displayMode: extractList ? DisplayModeType.displayAsList : DisplayModeType.displayAsObject,
270 viewSpecification: resolveViewDescription(defaultNS, vPath, viewSpecification),
271 keyProperty: viewElement.key,
274 // update display specification
275 return dispatch(postProcessDisplaySpecificationActionCreator(vPath, [], ds));
277 throw new Error(`Did not get response from Server. Status: [${restResult.status}]`);
278 } else if (checkResponseCode(restResult)) {
279 const message = restResult.data.errors && restResult.data.errors.error && restResult.data.errors.error[0] && restResult.data.errors.error[0]['error-message'] || '';
280 throw new Error(`Server Error. Status: [${restResult.status}]\n${message}`);
282 // https://tools.ietf.org/html/rfc7951#section-4 the root element may contain a namespace or not !
283 data = restResult.data[`${defaultNS}:${dataMember!}`];
284 if (data === undefined) {
285 data = restResult.data[dataMember!]; // extract dataMember w/o namespace
289 // extract the first element list[key]
290 data = data instanceof Array
294 // extract the list -> key: list
296 ? data[viewElement!.id] || data[viewElement!.label] || [] // if the list is empty, it does not exist
299 } else if (viewElement! && viewElement!.uiType === 'rpc') {
300 // set data to defaults
302 if (inputViewSpecification) {
303 Object.keys(inputViewSpecification.elements).forEach(key => {
304 const elm = inputViewSpecification && inputViewSpecification.elements[key];
305 if (elm && elm.default != undefined) {
306 data[elm.id] = elm.default;
312 // create display specification
313 const ds: DisplaySpecification = viewElement! && viewElement!.uiType === 'rpc'
316 displayMode: DisplayModeType.displayAsRPC,
317 inputViewSpecification: inputViewSpecification && resolveViewDescription(defaultNS, vPath, inputViewSpecification),
318 outputViewSpecification: outputViewSpecification && resolveViewDescription(defaultNS, vPath, outputViewSpecification),
322 displayMode: extractList ? DisplayModeType.displayAsList : DisplayModeType.displayAsObject,
323 viewSpecification: resolveViewDescription(defaultNS, vPath, viewSpecification),
324 keyProperty: isViewElementList(viewElement!) && viewElement.key || undefined,
326 // eslint-disable-next-line max-len
327 apidocPath: isViewElementList(viewElement!) && `/apidoc/explorer/index.html?urls.primaryName=$$$standard$$$#/mounted%20${nodeId}%20${viewElement!.module || 'MODULE_NOT_DEFINED'}/$$$action$$$_${dataPath.replace(/^\//, '').replace(/[\/=\-\:]/g, '_')}_${viewElement! != null ? `${viewElement.id.replace(/[\/=\-\:]/g, '_')}_` : '' }` || undefined,
330 // update display specification
331 return dispatch(postProcessDisplaySpecificationActionCreator(vPath, data, ds));
332 // https://server.com/#/configuration/Sim12600/core-model:network-element/ltp[LTP-MWPS-TTP-01]
333 // https://server.com/#/configuration/Sim12600/core-model:network-element/ltp[LTP-MWPS-TTP-01]/lp
336 dispatch(new AddErrorInfoAction({ title: 'Problem', message: error.message || `Could not process ${dataPath}` }));
337 dispatch(new SetCollectingSelectionData(false));
343 export const updateDataActionAsyncCreator = (vPath: string, data: any) => async (dispatch: Dispatch, getState: () => IApplicationStoreState) => {
344 const pathParts = splitVPath(vPath, /(?:([^\/\["]+)(?:\[([^\]]*)\])?)/g); // 1 = property / 2 = optional key
345 const { configuration: { deviceDescription: { nodeId, views } } } = getState();
346 let dataPath = `/rests/data/network-topology:network-topology/topology=topology-netconf/node=${nodeId}/yang-ext:mount`;
347 let viewSpecification: ViewSpecification = views[0];
348 let viewElement: ViewElement;
349 let dataMember: string;
350 let embedList: boolean = false;
351 let isNew: string | false = false;
353 let currentNS: string | null = null;
354 let defaultNS: string | null = null;
356 dispatch(new SetCollectingSelectionData(true));
358 for (let ind = 0; ind < pathParts.length; ++ind) {
359 let [property, key] = pathParts[ind];
360 const namespaceInd = property && property.indexOf(':') || -1;
361 const namespace: string | null = namespaceInd > -1 ? (currentNS = property.slice(0, namespaceInd)) : currentNS;
363 if (ind === 0) { defaultNS = namespace; }
364 viewElement = viewSpecification.elements[property] || viewSpecification.elements[`${namespace}:${property}`];
365 if (!viewElement) throw Error('Property [' + property + '] does not exist.');
367 if (isViewElementList(viewElement) && !key) {
369 if (viewElement && viewElement.isList && viewSpecification.parentView === '0') {
370 throw new Error('Found a list at root level of a module w/o a refenrece key.');
372 if (pathParts.length - 1 > ind) {
373 dispatch(new SetCollectingSelectionData(false));
374 throw new Error('No key for list [' + property + ']');
375 } else if (vPath.endsWith('[]') && pathParts.length - 1 === ind) {
376 // handle new element with any number of arguments
377 let keyList = viewElement.key?.split(' ');
378 let dataPathParam = keyList?.map(id => data[id]).join(',');
379 key = viewElement.key && String(dataPathParam) || '';
382 dispatch(new SetCollectingSelectionData(false));
383 throw new Error('No value for key [' + viewElement.key + '] in list [' + property + ']');
388 dataPath += `/${property}${key ? `=${key.replace(/\//ig, '%2F')}` : ''}`;
389 dataMember = viewElement.label;
392 if (viewElement && 'viewId' in viewElement) {
393 viewSpecification = views[+viewElement.viewId];
397 // remove read-only elements
398 const removeReadOnlyElements = (pViewSpecification: ViewSpecification, isList: boolean, pData: any) => {
400 return pData.map((elm : any) => removeReadOnlyElements(pViewSpecification, false, elm));
402 return Object.keys(pData).reduce<{ [key: string]: any }>((acc, cur)=>{
403 const [nsOrName, name] = cur.split(':', 1);
404 const element = pViewSpecification.elements[cur] || pViewSpecification.elements[nsOrName] || pViewSpecification.elements[name];
405 if (!element && process.env.NODE_ENV === 'development' ) {
406 throw new Error('removeReadOnlyElements: Could not determine elment for data.');
408 if (element && element.config) {
409 if (element.uiType === 'object') {
410 const view = views[+element.viewId];
412 throw new Error('removeReadOnlyElements: Internal Error could not determine viewId: ' + element.viewId);
414 acc[cur] = removeReadOnlyElements(view, element.isList != null && element.isList, pData[cur]);
416 acc[cur] = pData[cur];
423 data = removeReadOnlyElements(viewSpecification, embedList, data);
426 // embed the list -> key: list
428 ? { [viewElement!.label]: data }
431 // embed the first element list[key]
436 // do not extract root member (0)
437 if (viewSpecification && viewSpecification.id !== '0') {
438 const updateResult = await restService.setConfigData(dataPath, { [`${currentNS}:${dataMember!}`]: data }); // addDataMember using currentNS
439 if (checkResponseCode(updateResult)) {
440 const message = updateResult.data && updateResult.data.errors && updateResult.data.errors.error && updateResult.data.errors.error[0] && updateResult.data.errors.error[0]['error-message'] || '';
441 throw new Error(`Server Error. Status: [${updateResult.status}]\n${message || updateResult.message || ''}`);
446 return dispatch(new ReplaceAction(`/configuration/${nodeId}/${vPath.replace(/\[\]$/i, `[${isNew}]`)}`)); // navigate to new element
449 // create display specification
450 const ds: DisplaySpecification = {
451 displayMode: embedList ? DisplayModeType.displayAsList : DisplayModeType.displayAsObject,
452 viewSpecification: resolveViewDescription(defaultNS, vPath, viewSpecification),
453 keyProperty: isViewElementList(viewElement!) && viewElement.key || undefined,
456 // update display specification
457 return dispatch(new UpdateViewDescription(vPath, data, ds));
460 dispatch(new AddErrorInfoAction({ title: 'Problem', message: error.message || `Could not change ${dataPath}` }));
463 dispatch(new SetCollectingSelectionData(false));
468 export const removeElementActionAsyncCreator = (vPath: string) => async (dispatch: Dispatch, getState: () => IApplicationStoreState) => {
469 const pathParts = splitVPath(vPath, /(?:([^\/\["]+)(?:\[([^\]]*)\])?)/g); // 1 = property / 2 = optional key
470 const { configuration: { deviceDescription: { nodeId, views } } } = getState();
471 let dataPath = `/rests/data/network-topology:network-topology/topology=topology-netconf/node=${nodeId}/yang-ext:mount`;
472 let viewSpecification: ViewSpecification = views[0];
473 let viewElement: ViewElement;
475 let currentNS: string | null = null;
477 dispatch(new SetCollectingSelectionData(true));
479 for (let ind = 0; ind < pathParts.length; ++ind) {
480 let [property, key] = pathParts[ind];
481 const namespaceInd = property && property.indexOf(':') || -1;
482 const namespace: string | null = namespaceInd > -1 ? (currentNS = property.slice(0, namespaceInd)) : currentNS;
484 viewElement = viewSpecification.elements[property] || viewSpecification.elements[`${namespace}:${property}`];
485 if (!viewElement) throw Error('Property [' + property + '] does not exist.');
487 if (isViewElementList(viewElement) && !key) {
488 if (viewElement && viewElement.isList && viewSpecification.parentView === '0') {
489 throw new Error('Found a list at root level of a module w/o a reference key.');
491 if (pathParts.length - 1 > ind) {
492 dispatch(new SetCollectingSelectionData(false));
493 throw new Error('No key for list [' + property + ']');
494 } else if (vPath.endsWith('[]') && pathParts.length - 1 === ind) {
495 // remove the whole table
499 dataPath += `/${property}${key ? `=${key.replace(/\//ig, '%2F')}` : ''}`;
501 if (viewElement && 'viewId' in viewElement) {
502 viewSpecification = views[+viewElement.viewId];
503 } else if (viewElement.uiType === 'rpc') {
504 viewSpecification = views[+(viewElement.inputViewId || 0)];
508 const updateResult = await restService.removeConfigElement(dataPath);
509 if (checkResponseCode(updateResult)) {
510 const message = updateResult.data && updateResult.data.errors && updateResult.data.errors.error && updateResult.data.errors.error[0] && updateResult.data.errors.error[0]['error-message'] || '';
511 throw new Error(`Server Error. Status: [${updateResult.status}]\n${message || updateResult.message || ''}`);
514 dispatch(new AddErrorInfoAction({ title: 'Problem', message: error.message || `Could not remove ${dataPath}` }));
516 dispatch(new SetCollectingSelectionData(false));
520 export const executeRpcActionAsyncCreator = (vPath: string, data: any) => async (dispatch: Dispatch, getState: () => IApplicationStoreState) => {
521 const pathParts = splitVPath(vPath, /(?:([^\/\["]+)(?:\[([^\]]*)\])?)/g); // 1 = property / 2 = optional key
522 const { configuration: { deviceDescription: { nodeId, views } } } = getState();
523 let dataPath = `/rests/operations/network-topology:network-topology/topology=topology-netconf/node=${nodeId}/yang-ext:mount`;
524 let viewSpecification: ViewSpecification = views[0];
525 let viewElement: ViewElement;
526 let dataMember: string;
527 let embedList: boolean = false;
528 let isNew: string | false = false;
530 let currentNS: string | null = null;
531 let defaultNS: string | null = null;
533 dispatch(new SetCollectingSelectionData(true));
535 for (let ind = 0; ind < pathParts.length; ++ind) {
536 let [property, key] = pathParts[ind];
537 const namespaceInd = property && property.indexOf(':') || -1;
538 const namespace: string | null = namespaceInd > -1 ? (currentNS = property.slice(0, namespaceInd)) : currentNS;
540 if (ind === 0) { defaultNS = namespace; }
541 viewElement = viewSpecification.elements[property] || viewSpecification.elements[`${namespace}:${property}`];
542 if (!viewElement) throw Error('Property [' + property + '] does not exist.');
544 if (isViewElementList(viewElement) && !key) {
546 // if (viewElement && viewElement.isList && viewSpecification.parentView === "0") {
547 // throw new Error("Found a list at root level of a module w/o a reference key.");
549 // if (pathParts.length - 1 > ind) {
550 // dispatch(new SetCollectingSelectionData(false));
551 // throw new Error("No key for list [" + property + "]");
552 // } else if (vPath.endsWith("[]") && pathParts.length - 1 === ind) {
553 // // handle new element
554 // key = viewElement.key && String(data[viewElement.key]) || "";
557 // dispatch(new SetCollectingSelectionData(false));
558 // throw new Error("No value for key [" + viewElement.key + "] in list [" + property + "]");
563 dataPath += `/${property}${key ? `=${key.replace(/\//ig, '%2F')}` : ''}`;
564 dataMember = viewElement.label;
567 if (viewElement && 'viewId' in viewElement) {
568 viewSpecification = views[+viewElement.viewId];
569 } else if (viewElement.uiType === 'rpc') {
570 viewSpecification = views[+(viewElement.inputViewId || 0)];
574 // re-inflate formerly flatten rpc data
575 data = data && Object.keys(data).reduce < { [name: string ]: any }>((acc, cur) => {
576 const innerPathParts = cur.split('.');
578 const updatePath = (obj: any, key: string) => {
579 obj[key] = (pos >= innerPathParts.length)
581 : updatePath(obj[key] || {}, innerPathParts[pos++]);
584 updatePath(acc, innerPathParts[pos++]);
588 // embed the list -> key: list
590 ? { [viewElement!.label]: data }
593 // embed the first element list[key]
598 // do not post root member (0)
599 if ((viewSpecification && viewSpecification.id !== '0') || (dataMember! && !data)) {
600 const updateResult = await restService.executeRpc(dataPath, { [`${defaultNS}:input`]: data || {} });
601 if (checkResponseCode(updateResult)) {
602 const message = updateResult.data && updateResult.data.errors && updateResult.data.errors.error && updateResult.data.errors.error[0] && updateResult.data.errors.error[0]['error-message'] || '';
603 throw new Error(`Server Error. Status: [${updateResult.status}]\n${message || updateResult.message || ''}`);
605 dispatch(new UpdateOutputData(updateResult.data));
607 throw new Error('There is NO RPC specified.');
611 // // update display specification
614 dispatch(new AddErrorInfoAction({ title: 'Problem', message: error.message || `Could not change ${dataPath}` }));
617 dispatch(new SetCollectingSelectionData(false));