From d6de4d98781beaa32f0ae87d9b4ade4da5855338 Mon Sep 17 00:00:00 2001 From: Roland Reich Date: Wed, 18 Nov 2026 21:41:02 +0100 Subject: [PATCH] Version 0.5.5.95: pick MeshCentral source paths from device JSON MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 🔍 button next to every mapping source path (table and new-mapping form) opens a dialog with the stored MeshCentral JSON of a chosen asset as an expandable, searchable tree; already mapped paths are marked, keys the path syntax cannot express are greyed out, list entries produce "list[].key". - Preview evaluates the path with the row's transformation, multiple value mode, separator and "value if empty"/guard using the sync code. - Coverage check across all assets with stored JSON: devices with a value, devices where the mapping writes a value (incl. fallbacks) and the most frequent results. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- VERSION | 2 +- app/i18n.py | 30 ++ app/main.py | 130 +++++++ app/static/css/app.css | 40 ++ app/static/js/mesh-path-picker.js | 477 ++++++++++++++++++++++++ app/templates/meshcentral_sync.html | 22 ++ app/version.py | 2 +- docs/version-history/README.md | 3 +- docs/version-history/UPDATE-0.5.5.95.md | 19 + 10 files changed, 723 insertions(+), 4 deletions(-) create mode 100644 app/static/js/mesh-path-picker.js create mode 100644 docs/version-history/UPDATE-0.5.5.95.md diff --git a/README.md b/README.md index e9e1983..a4267a8 100755 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# AssetManager 0.5.5.94 +# AssetManager 0.5.5.95 AssetManager is a self-hosted web application for managing IT equipment and other organizational assets. It provides asset inventory, software inventory, remote job execution, reporting, privacy/retention documentation, and optional integration with MeshCentral. diff --git a/VERSION b/VERSION index 177ba5d..df7c1ef 100755 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.5.5.94 +0.5.5.95 diff --git a/app/i18n.py b/app/i18n.py index ae64dff..c02333c 100755 --- a/app/i18n.py +++ b/app/i18n.py @@ -216,6 +216,36 @@ BASE_TRANSLATIONS = { "lists.column_resize": ("Drag to change the column width", "Ziehen, um die Spaltenbreite zu ändern"), "lists.multi_value_filter_hint": ("One search value per line; lines within a column are OR-linked. !value excludes rows, =value compares the whole value exactly. Numbers and dates also support >x, =x, <=x and ranges such as 'from x to y'. The ▾ button opens a value list with checkboxes.", "Ein Suchwert pro Zeile; Zeilen einer Spalte sind ODER-verknüpft. !Wert schließt Zeilen aus, =Wert vergleicht den ganzen Wert exakt. Zahlen und Datumswerte unterstützen zusätzlich >x, =x, <=x sowie Bereiche wie ‚von x bis y‘. Der Knopf ▾ öffnet eine Werteliste mit Häkchen."), "lists.advanced_filter.title": ("Advanced filter", "Erweiterter Filter"), +'mesh.picker.open': ('From device', 'Aus Gerät wählen'), +'mesh.picker.open_title': ('Choose the source path in the stored MeshCentral JSON of a device', 'Quellpfad im gespeicherten MeshCentral-JSON eines Geräts auswählen'), +'mesh.picker.mapped': ('mapped', 'gemappt'), +'mesh.picker.unavailable': ("This key contains '.' or '|' and cannot be addressed with the path syntax.", "Dieser Schlüssel enthält '.' oder '|' und lässt sich mit der Pfadsyntax nicht ansprechen."), +'mesh.picker.more': ('Show {count} more', '{count} weitere anzeigen'), +'mesh.picker.no_matches': ('No matches.', 'Keine Treffer.'), +'mesh.picker.matches_limited': ('Only the first {count} matches are shown.', 'Es werden nur die ersten {count} Treffer angezeigt.'), +'mesh.picker.values': ('Values on this device ({count})', 'Werte bei diesem Gerät ({count})'), +'mesh.picker.no_value': ('—', '—'), +'mesh.picker.result': ('Result with these mapping settings', 'Ergebnis mit diesen Mapping-Einstellungen'), +'mesh.picker.no_result': ('(no value, the field is not written)', '(kein Wert, das Feld wird nicht beschrieben)'), +'mesh.picker.fallback': ("The source is empty here; the 'value if empty' is used.", "Die Quelle ist hier leer; es wird der 'Wert, wenn leer' verwendet."), +'mesh.picker.preview_error': ('The preview could not be calculated.', 'Die Vorschau konnte nicht berechnet werden.'), +'mesh.picker.coverage_summary': ('Value present on {with} of {total} devices; the mapping writes a value on {result} devices.', 'Wert bei {with} von {total} Geräten vorhanden; das Mapping schreibt bei {result} Geräten einen Wert.'), +'mesh.picker.coverage_fallback': ("{count} of them via 'value if empty'.", "Davon {count} über 'Wert, wenn leer'."), +'mesh.picker.coverage_top': ('Most frequent results ({count} different)', 'Häufigste Ergebnisse ({count} verschiedene)'), +'mesh.picker.no_asset_match': ('No matching asset', 'Kein passendes Asset'), +'mesh.picker.no_assets': ('No asset with stored MeshCentral data yet. Run a sync first.', 'Noch kein Asset mit gespeicherten MeshCentral-Daten. Bitte zuerst einen Abgleich ausführen.'), +'mesh.picker.last_sync': ('Last sync: {time}', 'Letzter Abgleich: {time}'), +'mesh.picker.load_error': ('The device data could not be loaded.', 'Die Gerätedaten konnten nicht geladen werden.'), +'mesh.picker.save_hint': ('Path applied. Save the mappings to keep it.', 'Pfad übernommen. Zum Behalten die Mappings speichern.'), +'mesh.picker.title': ('Choose source path', 'Quellpfad auswählen'), +'mesh.picker.device': ('Device', 'Gerät'), +'mesh.picker.device_search': ('Search asset', 'Asset suchen'), +'mesh.picker.tree_search': ('Search keys and values', 'Schlüssel und Werte durchsuchen'), +'mesh.picker.path': ('Source path', 'Quellpfad'), +'mesh.picker.help': ("Click an entry to use its path. Entries inside lists produce 'list[].key' (all elements). The preview uses the transformation, multiple-value mode and 'value if empty' of the mapping row.", "Klicke auf einen Eintrag, um seinen Pfad zu übernehmen. Einträge in Listen ergeben 'liste[].schlüssel' (alle Elemente). Die Vorschau verwendet Transformation, Mehrfachwerte und 'Wert, wenn leer' der Mapping-Zeile."), +'mesh.picker.coverage': ('Check coverage across all devices', 'Abdeckung über alle Geräte prüfen'), +'mesh.picker.apply': ('Apply path', 'Pfad übernehmen'), +'errors.mesh_source_missing': ('No stored MeshCentral data was found for this asset.', 'Für dieses Asset wurden keine gespeicherten MeshCentral-Daten gefunden.'), "lists.value_list.open": ("Select values", "Werte auswählen"), "lists.value_list.search": ("Search values", "Werte durchsuchen"), "lists.value_list.select_all": ("(Select all)", "(Alle auswählen)"), diff --git a/app/main.py b/app/main.py index a65951e..90a6a25 100755 --- a/app/main.py +++ b/app/main.py @@ -10175,6 +10175,136 @@ async def meshcentral_category_mapping_save(request: Request, db: Session = Depe return RedirectResponse('/sync/meshcentral?toast_success=' + quote(_translate_request(request, 'settings.mesh_mapping_saved', 'MeshCentral category mapping saved')), status_code=303) +# --------------------------------------------------------------------------- +# v0.5.5.95: pick MeshCentral source paths from a stored device JSON +# --------------------------------------------------------------------------- + +def _assets_with_source_json(db: Session): + """Assets whose last sync stored the MeshCentral device JSON.""" + stored = cast(Asset.mesh_source_data, String) + return db.query(Asset).filter( + Asset.mesh_source_data.isnot(None), + stored.notin_(["{}", "null", ""]), + ) + + +def _picker_mapping(payload: dict[str, Any]) -> dict[str, Any]: + """Mapping settings from the dialog, normalized like the save handler.""" + separator = str(payload.get("separator") if payload.get("separator") is not None else "\\n") + return { + "source_path": str(payload.get("source_path") or "").strip()[:255], + "transform": str(payload.get("transform") or "raw"), + "multi_value_mode": str(payload.get("multi_value_mode") or "first"), + "separator": separator.replace("\\n", "\n").replace("\\t", "\t") or "\n", + "empty_value": str(payload.get("empty_value") or "").strip() or None, + "empty_value_guard": str(payload.get("empty_value_guard") or "").strip() or None, + } + + +def _picker_display(value: Any) -> str: + if value is None: + return "" + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, (dict, list)): + return json.dumps(value, ensure_ascii=False) + return str(value) + + +@app.get("/sync/meshcentral/path-picker/assets") +def mesh_path_picker_assets(request: Request, q: str = "", db: Session = Depends(get_db)): + _require_admin(request) + query = _assets_with_source_json(db).options(load_only(Asset.id, Asset.name, Asset.mesh_node_id, Asset.mesh_last_sync)) + term = q.strip() + if term: + like = f"%{term.lower()}%" + query = query.filter(or_(func.lower(Asset.name).like(like), func.lower(func.coalesce(Asset.hostname, "")).like(like))) + assets = query.order_by(Asset.name).limit(50).all() + return JSONResponse({ + "assets": [{"id": asset.id, "name": asset.name, "last_sync": _utc_iso(asset.mesh_last_sync) or None} for asset in assets], + "total": _assets_with_source_json(db).count(), + }, headers={"Cache-Control": "no-store"}) + + +@app.get("/sync/meshcentral/path-picker/source") +def mesh_path_picker_source(request: Request, asset_id: int, db: Session = Depends(get_db)): + _require_admin(request) + asset = db.get(Asset, asset_id) + if not asset or not asset.mesh_source_data: + raise TranslatedHTTPException(404, "errors.mesh_source_missing", "No stored MeshCentral data was found for this asset.") + mapped = sorted({row.source_path for row in db.query(MeshFieldMapping.source_path).all() if row.source_path}) + return JSONResponse({ + "asset": {"id": asset.id, "name": asset.name, "last_sync": _utc_iso(asset.mesh_last_sync) or None}, + "data": asset.mesh_source_data, + "mapped_paths": mapped, + }, headers={"Cache-Control": "no-store"}) + + +@app.post("/sync/meshcentral/path-picker/preview") +async def mesh_path_picker_preview(request: Request, db: Session = Depends(get_db)): + """Evaluate a mapping for one device exactly like the sync does.""" + _require_admin(request) + payload = await request.json() + mapping = _picker_mapping(payload if isinstance(payload, dict) else {}) + try: + asset_id = int(payload.get("asset_id")) + except (TypeError, ValueError, AttributeError): + raise TranslatedHTTPException(400, "errors.asset_not_found", "Asset not found.") + asset = db.get(Asset, asset_id) + if not asset or not asset.mesh_source_data: + raise TranslatedHTTPException(404, "errors.mesh_source_missing", "No stored MeshCentral data was found for this asset.") + from . import meshcentral as mesh_module + raw = asset.mesh_source_data + values = mesh_module._path_values(raw, mapping["source_path"]) if mapping["source_path"] else [] + result = mesh_module._mapped_value(raw, mapping) if mapping["source_path"] else None + source_empty = not [value for value in values if value not in (None, "", [], {})] + return JSONResponse({ + "values": [_picker_display(value)[:500] for value in values[:50]], + "value_count": len(values), + "result": _picker_display(result)[:2000], + "has_result": result not in (None, "", [], {}), + "fallback_used": source_empty and result not in (None, "", [], {}), + }, headers={"Cache-Control": "no-store"}) + + +@app.post("/sync/meshcentral/path-picker/coverage") +async def mesh_path_picker_coverage(request: Request, db: Session = Depends(get_db)): + """How many synced devices deliver a value for this path (and what the mapping makes of it).""" + _require_admin(request) + payload = await request.json() + mapping = _picker_mapping(payload if isinstance(payload, dict) else {}) + if not mapping["source_path"]: + raise TranslatedHTTPException(400, "mesh.toast.mapping_required", "Source path and target field are required.") + from . import meshcentral as mesh_module + total = with_source = with_result = fallback = 0 + results: dict[str, int] = {} + # Only the JSON column, streamed in chunks: no eager-loaded relationships. + query = _assets_with_source_json(db).with_entities(Asset.id, Asset.mesh_source_data).yield_per(200) + for _asset_id, raw in query: + if not isinstance(raw, dict): + continue + total += 1 + values = [value for value in mesh_module._path_values(raw, mapping["source_path"]) if value not in (None, "", [], {})] + if values: + with_source += 1 + result = mesh_module._mapped_value(raw, mapping) + if result not in (None, "", [], {}): + with_result += 1 + if not values: + fallback += 1 + key = _picker_display(result)[:120] + results[key] = results.get(key, 0) + 1 + top = sorted(results.items(), key=lambda item: (-item[1], item[0].casefold()))[:10] + return JSONResponse({ + "total": total, + "with_source": with_source, + "with_result": with_result, + "fallback": fallback, + "distinct_results": len(results), + "top_results": [{"value": value, "count": count} for value, count in top], + }, headers={"Cache-Control": "no-store"}) + + @app.post('/sync/meshcentral/mappings/save') async def meshcentral_mappings_save(request: Request, db: Session = Depends(get_db)): _require_admin(request) diff --git a/app/static/css/app.css b/app/static/css/app.css index f05cbd9..bdb8822 100755 --- a/app/static/css/app.css +++ b/app/static/css/app.css @@ -3457,3 +3457,43 @@ html[data-theme="dark"] .value-list-count{color:#9aa7b4} .value-list-popup label.value-list-item input[type="checkbox"]{flex:0 0 auto;width:16px;min-width:16px;height:16px;margin:0;padding:0} .value-list-popup label.value-list-all{white-space:nowrap} .value-list-button.is-loading{opacity:.35;cursor:progress} + +/* 0.5.5.95: MeshCentral source path picker */ +.picker-input-wrap{display:flex;gap:4px;align-items:center} +.picker-input-wrap input{flex:1;min-width:0} +.picker-open{white-space:nowrap;flex:0 0 auto} +.picker-open-compact{width:34px;min-width:34px;padding-left:0;padding-right:0} +.mesh-mapping-table .picker-input-wrap input.mapping-path{min-width:300px} +.mesh-path-picker-dialog{width:min(980px,96vw);max-height:92vh} +.mesh-path-picker-dialog[open]{display:flex;flex-direction:column;gap:8px} +.mesh-path-picker-dialog label{display:block;font-weight:600;font-size:13px} +.mesh-path-picker-dialog label input,.mesh-path-picker-dialog label select{width:100%;box-sizing:border-box} +.picker-device-row{display:grid;grid-template-columns:1fr 1fr auto;gap:8px;align-items:end} +.picker-tree{height:min(46vh,460px);overflow:auto;border:1px solid var(--border-color,#d8dde2);border-radius:6px;padding:4px 0;font-size:13px;font-family:ui-monospace,SFMono-Regular,Consolas,monospace} +.picker-node{display:flex;align-items:baseline;gap:6px;padding:2px 8px 2px calc(8px + var(--depth,0) * 16px);cursor:pointer;white-space:nowrap} +.picker-node:hover,.picker-node:focus-visible{background:rgba(0,90,160,.08);outline:none} +.picker-node.is-selected{background:rgba(0,90,160,.18)} +.picker-node.is-unavailable{cursor:default;opacity:.5} +.picker-match{flex-wrap:wrap;white-space:normal} +.picker-toggle{width:16px;min-width:16px;padding:0;margin:0;border:0;background:transparent;color:inherit;cursor:pointer;font-size:12px} +.picker-key{font-weight:600} +.picker-value{color:#1d6b3a;overflow:hidden;text-overflow:ellipsis} +.picker-meta{color:#6b7785} +.picker-mapped{font-family:system-ui,sans-serif;font-size:11px;padding:0 6px;border-radius:8px;background:#e3eefb;color:#1f5d99} +.picker-more{margin:4px 0 4px calc(24px + var(--depth,0) * 16px)} +.picker-path{font-family:ui-monospace,SFMono-Regular,Consolas,monospace} +.picker-preview,.picker-coverage{font-size:13px} +.picker-preview:empty,.picker-coverage:empty{display:none} +.picker-preview{padding:8px;border-radius:6px;background:#f5f7f9} +.picker-preview .picker-value{word-break:break-word;white-space:normal} +.picker-coverage p{margin:4px 0} +.picker-coverage-list{margin:4px 0 0} +input.picker-updated{background:#fff8d6} +html[data-theme="dark"] .picker-tree{border-color:#53606d} +html[data-theme="dark"] .picker-preview{background:#26313c} +html[data-theme="dark"] .picker-value{color:#8fd4a8} +html[data-theme="dark"] .picker-meta{color:#9aa7b4} +html[data-theme="dark"] .picker-mapped{background:#24405e;color:#cfe3fa} +html[data-theme="dark"] input.picker-updated{background:#4a4320} +html[data-theme="dark"] .picker-node:hover,html[data-theme="dark"] .picker-node.is-selected{background:rgba(120,180,240,.18)} +@media (max-width:700px){.picker-device-row{grid-template-columns:1fr}} diff --git a/app/static/js/mesh-path-picker.js b/app/static/js/mesh-path-picker.js new file mode 100644 index 0000000..5da06c7 --- /dev/null +++ b/app/static/js/mesh-path-picker.js @@ -0,0 +1,477 @@ +(() => { + // v0.5.5.95: choose a MeshCentral source path by clicking into the stored + // device JSON of an asset. The generated path uses the same syntax as the + // sync (dotted keys, "[]" for all list elements). + const root = document.querySelector('[data-mesh-path-picker]'); + const dialog = document.getElementById('mesh-path-picker-dialog'); + if (!root || !dialog) return; + + const urls = { + assets: root.dataset.assetsUrl, + source: root.dataset.sourceUrl, + preview: root.dataset.previewUrl, + coverage: root.dataset.coverageUrl + }; + const label = key => root.dataset[key] || ''; + const storageKey = 'assetmanager:mesh-path-picker:asset'; + const MAX_CHILDREN = 60; + const MAX_MATCHES = 200; + + const els = { + assetSearch: dialog.querySelector('[data-picker-asset-search]'), + assetSelect: dialog.querySelector('[data-picker-asset-select]'), + assetInfo: dialog.querySelector('[data-picker-asset-info]'), + treeSearch: dialog.querySelector('[data-picker-tree-search]'), + tree: dialog.querySelector('[data-picker-tree]'), + path: dialog.querySelector('[data-picker-path]'), + preview: dialog.querySelector('[data-picker-preview]'), + coverageButton: dialog.querySelector('[data-picker-coverage-button]'), + coverage: dialog.querySelector('[data-picker-coverage]'), + apply: dialog.querySelector('[data-picker-apply]'), + cancel: dialog.querySelector('[data-picker-cancel]') + }; + + let target = null; // { input, settings() } + let sourceData = null; + let mappedPaths = new Set(); + let currentAssetId = null; + let selectedRow = null; + let previewTimer = null; + let searchTimer = null; + let assetTimer = null; + + const isContainer = value => value !== null && typeof value === 'object'; + // Keys the path syntax cannot express: "." and "|" separate parts/alternatives, + // a trailing "[]" would be read as list expansion. + const expressibleKey = key => key !== '' && !/[.|]/.test(key) && !key.endsWith('[]') && key.trim() === key; + + function childPath(parentPath, key) { + return parentPath ? `${parentPath}.${key}` : key; + } + + function preview(value) { + if (value === null) return 'null'; + if (Array.isArray(value)) return `[${value.length}]`; + if (typeof value === 'object') return `{${Object.keys(value).length}}`; + const text = typeof value === 'string' ? `"${value}"` : String(value); + return text.length > 140 ? `${text.slice(0, 140)}…` : text; + } + + async function getJson(url) { + const response = await fetch(url, { cache: 'no-store', headers: { 'X-Requested-With': 'AssetManagerPathPicker' } }); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + return response.json(); + } + + async function postJson(url, body) { + const response = await fetch(url, { + method: 'POST', + cache: 'no-store', + headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'AssetManagerPathPicker' }, + body: JSON.stringify(body) + }); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + return response.json(); + } + + // --- mapping settings of the row / form the dialog was opened from -------- + function settingsFor(input) { + const row = input.closest('tr'); + if (row && input.name.startsWith('mapping_')) { + const prefix = input.name.replace(/source_path$/, ''); + const field = name => row.querySelector(`[name="${prefix}${name}"]`)?.value ?? ''; + return () => ({ + transform: field('transform'), multi_value_mode: field('multi_value_mode'), separator: field('separator'), + empty_value: field('empty_value'), empty_value_guard: field('empty_value_guard') + }); + } + const form = input.form; + const field = name => form?.elements.namedItem(name)?.value ?? ''; + return () => ({ + transform: field('transform'), multi_value_mode: field('multi_value_mode'), separator: field('separator'), + empty_value: field('empty_value'), empty_value_guard: field('empty_value_guard') + }); + } + + // --- tree ------------------------------------------------------------------ + function makeRow({ key, value, path, expressible, depth, isListElement }) { + const row = document.createElement('div'); + row.className = 'picker-node'; + row.style.setProperty('--depth', String(depth)); + const toggle = document.createElement('button'); + toggle.type = 'button'; + toggle.className = 'picker-toggle'; + toggle.textContent = isContainer(value) && (Array.isArray(value) ? value.length : Object.keys(value).length) ? '▸' : ''; + toggle.tabIndex = -1; + const name = document.createElement('span'); + name.className = 'picker-key'; + name.textContent = isListElement ? `[${key}]` : key; + const info = document.createElement('span'); + info.className = isContainer(value) ? 'picker-meta' : 'picker-value'; + info.textContent = preview(value); + row.append(toggle, name, info); + if (expressible && path && mappedPaths.has(path)) { + const badge = document.createElement('span'); + badge.className = 'picker-mapped'; + badge.textContent = label('mappedLabel') || 'mapped'; + row.appendChild(badge); + } + if (!expressible) { + row.classList.add('is-unavailable'); + row.title = label('unavailableHint'); + } else { + row.dataset.path = path; + row.tabIndex = 0; + row.title = path; + } + + let children = null; + const expand = () => { + if (!isContainer(value)) return; + if (children) { + children.hidden = !children.hidden; + toggle.textContent = children.hidden ? '▸' : '▾'; + return; + } + children = document.createElement('div'); + children.className = 'picker-children'; + renderChildren(children, value, path, expressible, depth + 1); + row.after(children); + toggle.textContent = '▾'; + }; + toggle.addEventListener('click', event => { event.stopPropagation(); expand(); }); + row.addEventListener('click', () => { + if (expressible) select(row, path); + if (isContainer(value) && !children) expand(); + }); + row.addEventListener('keydown', event => { + if (event.key === 'Enter') { event.preventDefault(); row.click(); } + if (event.key === 'ArrowRight' && isContainer(value) && (!children || children.hidden)) expand(); + if (event.key === 'ArrowLeft' && children && !children.hidden) expand(); + }); + return row; + } + + function renderChildren(container, value, path, expressible, depth, offset = 0) { + if (Array.isArray(value)) { + // All elements share one path: "list[]" addresses every element. + const elementPath = path ? `${path}[]` : ''; + const elementExpressible = expressible && Boolean(path) && !path.endsWith('[]'); + value.slice(offset, offset + MAX_CHILDREN).forEach((item, index) => { + container.appendChild(makeRow({ key: offset + index, value: item, path: elementPath, expressible: elementExpressible, depth, isListElement: true })); + }); + if (value.length > offset + MAX_CHILDREN) addMore(container, value, path, expressible, depth, offset + MAX_CHILDREN, value.length); + return; + } + const keys = Object.keys(value); + keys.slice(offset, offset + MAX_CHILDREN).forEach(key => { + const ok = expressible && expressibleKey(key); + container.appendChild(makeRow({ key, value: value[key], path: ok ? childPath(path, key) : '', expressible: ok, depth })); + }); + if (keys.length > offset + MAX_CHILDREN) addMore(container, value, path, expressible, depth, offset + MAX_CHILDREN, keys.length); + } + + function addMore(container, value, path, expressible, depth, offset, total) { + const more = document.createElement('button'); + more.type = 'button'; + more.className = 'button button-secondary button-small picker-more'; + more.style.setProperty('--depth', String(depth)); + more.textContent = (label('moreLabel') || 'Show {count} more').replace('{count}', String(total - offset)); + more.addEventListener('click', () => { + more.remove(); + renderChildren(container, value, path, expressible, depth, offset); + }); + container.appendChild(more); + } + + function renderTree() { + els.tree.replaceChildren(); + if (!isContainer(sourceData)) return; + renderChildren(els.tree, sourceData, '', true, 0); + } + + // Flat result list for the search: key or scalar value matches. + function renderSearch(term) { + const needle = term.toLocaleLowerCase(); + const matches = []; + const walk = (value, path, expressible, keyLabel, depth) => { + if (matches.length >= MAX_MATCHES || depth > 40) return; + const keyHit = keyLabel && String(keyLabel).toLocaleLowerCase().includes(needle); + const valueHit = !isContainer(value) && value !== null && String(value).toLocaleLowerCase().includes(needle); + if ((keyHit || valueHit) && path) matches.push({ path, value, expressible }); + if (!isContainer(value)) return; + if (Array.isArray(value)) { + const ok = expressible && Boolean(path) && !path.endsWith('[]'); + value.forEach(item => walk(item, path ? `${path}[]` : '', ok, '', depth + 1)); + } else { + Object.keys(value).forEach(key => { + const ok = expressible && expressibleKey(key); + walk(value[key], ok ? childPath(path, key) : (path ? `${path}.${key}` : key), ok, key, depth + 1); + }); + } + }; + walk(sourceData, '', true, '', 0); + els.tree.replaceChildren(); + if (!matches.length) { + const empty = document.createElement('p'); + empty.className = 'muted'; + empty.textContent = label('noMatches') || 'No matches.'; + els.tree.appendChild(empty); + return; + } + matches.forEach(match => { + const row = document.createElement('div'); + row.className = 'picker-node picker-match'; + const path = document.createElement('code'); + path.textContent = match.path; + const value = document.createElement('span'); + value.className = isContainer(match.value) ? 'picker-meta' : 'picker-value'; + value.textContent = preview(match.value); + row.append(path, value); + if (match.expressible) { + row.dataset.path = match.path; + row.tabIndex = 0; + if (mappedPaths.has(match.path)) { + const badge = document.createElement('span'); + badge.className = 'picker-mapped'; + badge.textContent = label('mappedLabel') || 'mapped'; + row.appendChild(badge); + } + row.addEventListener('click', () => select(row, match.path)); + row.addEventListener('keydown', event => { if (event.key === 'Enter') select(row, match.path); }); + } else { + row.classList.add('is-unavailable'); + row.title = label('unavailableHint'); + } + els.tree.appendChild(row); + }); + if (matches.length >= MAX_MATCHES) { + const note = document.createElement('p'); + note.className = 'muted'; + note.textContent = (label('matchesLimited') || 'Only the first {count} matches are shown.').replace('{count}', String(MAX_MATCHES)); + els.tree.appendChild(note); + } + } + + function select(row, path) { + selectedRow?.classList.remove('is-selected'); + selectedRow = row; + row.classList.add('is-selected'); + els.path.value = path; + schedulePreview(0); + } + + // --- preview / coverage ------------------------------------------------------ + function requestBody() { + return { asset_id: currentAssetId, source_path: els.path.value.trim(), ...(target?.settings() || {}) }; + } + + function schedulePreview(delay = 300) { + window.clearTimeout(previewTimer); + els.coverage.replaceChildren(); + els.apply.disabled = !els.path.value.trim(); + previewTimer = window.setTimeout(runPreview, delay); + } + + async function runPreview() { + const body = requestBody(); + if (!body.source_path || !currentAssetId) { els.preview.replaceChildren(); return; } + els.preview.textContent = label('loading') || '…'; + try { + const data = await postJson(urls.preview, body); + els.preview.replaceChildren(); + const values = document.createElement('div'); + const valuesLabel = document.createElement('strong'); + valuesLabel.textContent = `${(label('valuesLabel') || 'Values on this device ({count})').replace('{count}', String(data.value_count))}: `; + const valuesText = document.createElement('span'); + valuesText.className = 'picker-value'; + valuesText.textContent = data.values.length ? data.values.join(' | ') : (label('noValue') || '—'); + values.append(valuesLabel, valuesText); + const result = document.createElement('div'); + const resultLabel = document.createElement('strong'); + resultLabel.textContent = `${label('resultLabel') || 'Result with these mapping settings'}: `; + const resultText = document.createElement('code'); + resultText.textContent = data.has_result ? data.result : (label('noResult') || '(no value, field is not written)'); + result.append(resultLabel, resultText); + els.preview.append(values, result); + if (data.fallback_used) { + const note = document.createElement('div'); + note.className = 'muted'; + note.textContent = label('fallbackNote') || 'The source is empty; the "value if empty" is used.'; + els.preview.appendChild(note); + } + } catch (error) { + els.preview.textContent = label('previewError') || 'The preview could not be calculated.'; + } + } + + async function runCoverage() { + const body = requestBody(); + if (!body.source_path) return; + els.coverageButton.disabled = true; + els.coverage.textContent = label('loading') || '…'; + try { + const data = await postJson(urls.coverage, body); + els.coverage.replaceChildren(); + const summary = document.createElement('p'); + summary.textContent = (label('coverageSummary') || 'Value present on {with} of {total} devices; the mapping writes a value on {result} devices.') + .replace('{with}', String(data.with_source)) + .replace('{total}', String(data.total)) + .replace('{result}', String(data.with_result)); + els.coverage.appendChild(summary); + if (data.fallback) { + const fallback = document.createElement('p'); + fallback.className = 'muted'; + fallback.textContent = (label('coverageFallback') || '{count} of them via "value if empty".').replace('{count}', String(data.fallback)); + els.coverage.appendChild(fallback); + } + if (data.top_results.length) { + const list = document.createElement('ul'); + list.className = 'compact-list picker-coverage-list'; + data.top_results.forEach(item => { + const entry = document.createElement('li'); + const code = document.createElement('code'); + code.textContent = item.value; + entry.append(code, document.createTextNode(` · ${item.count}`)); + list.appendChild(entry); + }); + const heading = document.createElement('strong'); + heading.textContent = (label('coverageTop') || 'Most frequent results ({count} different)').replace('{count}', String(data.distinct_results)); + els.coverage.append(heading, list); + } + } catch (error) { + els.coverage.textContent = label('previewError') || 'The preview could not be calculated.'; + } finally { + els.coverageButton.disabled = false; + } + } + + // --- assets -------------------------------------------------------------------- + async function loadAssets(term = '') { + const url = new URL(urls.assets, window.location.origin); + if (term) url.searchParams.set('q', term); + const data = await getJson(url.toString()); + const previous = currentAssetId || Number(window.localStorage.getItem(storageKey) || 0); + els.assetSelect.replaceChildren(); + data.assets.forEach(asset => { + const option = document.createElement('option'); + option.value = String(asset.id); + option.textContent = asset.name; + els.assetSelect.appendChild(option); + }); + if (!data.assets.length) { + const option = document.createElement('option'); + option.value = ''; + option.textContent = data.total ? (label('noAssetMatch') || 'No matching asset') : (label('noAssets') || 'No asset with stored MeshCentral data yet. Run a sync first.'); + els.assetSelect.appendChild(option); + return null; + } + const keep = data.assets.find(asset => asset.id === previous); + els.assetSelect.value = String((keep || data.assets[0]).id); + return Number(els.assetSelect.value); + } + + async function loadSource(assetId) { + if (!assetId) { + sourceData = null; + els.tree.replaceChildren(); + els.assetInfo.textContent = ''; + return; + } + els.tree.textContent = label('loading') || '…'; + const url = new URL(urls.source, window.location.origin); + url.searchParams.set('asset_id', String(assetId)); + const data = await getJson(url.toString()); + currentAssetId = assetId; + window.localStorage.setItem(storageKey, String(assetId)); + sourceData = data.data; + mappedPaths = new Set(data.mapped_paths || []); + els.assetInfo.textContent = data.asset.last_sync + ? (label('lastSync') || 'Last sync: {time}').replace('{time}', new Date(data.asset.last_sync).toLocaleString()) + : ''; + selectedRow = null; + if (els.treeSearch.value.trim().length >= 2) renderSearch(els.treeSearch.value.trim()); + else renderTree(); + if (els.path.value.trim()) schedulePreview(0); + } + + // --- open / apply ---------------------------------------------------------------- + async function open(input) { + target = { input, settings: settingsFor(input) }; + els.path.value = input.value.trim(); + els.preview.replaceChildren(); + els.coverage.replaceChildren(); + els.apply.disabled = !els.path.value; + els.treeSearch.value = ''; + if (typeof dialog.showModal === 'function') dialog.showModal(); else dialog.setAttribute('open', ''); + try { + const assetId = await loadAssets(els.assetSearch.value.trim()); + await loadSource(assetId); + } catch (error) { + els.tree.textContent = label('loadError') || 'The device data could not be loaded.'; + } + } + + function close() { + if (typeof dialog.close === 'function') dialog.close(); else dialog.removeAttribute('open'); + } + + els.apply.addEventListener('click', () => { + const path = els.path.value.trim(); + if (!target || !path) return; + target.input.value = path; + target.input.dispatchEvent(new Event('input', { bubbles: true })); + target.input.dispatchEvent(new Event('change', { bubbles: true })); + target.input.classList.add('picker-updated'); + if (target.input.name.startsWith('mapping_')) { + window.AssetManagerToast?.warning?.(label('saveHint') || 'Path applied. Save the mappings to keep it.'); + } + close(); + target.input.focus(); + }); + els.cancel.addEventListener('click', close); + els.coverageButton.addEventListener('click', runCoverage); + els.path.addEventListener('input', () => schedulePreview()); + els.assetSelect.addEventListener('change', () => { + loadSource(Number(els.assetSelect.value) || null).catch(() => { + els.tree.textContent = label('loadError') || 'The device data could not be loaded.'; + }); + }); + els.assetSearch.addEventListener('input', () => { + window.clearTimeout(assetTimer); + assetTimer = window.setTimeout(async () => { + try { + const assetId = await loadAssets(els.assetSearch.value.trim()); + if (assetId !== currentAssetId) await loadSource(assetId); + } catch (error) { + els.tree.textContent = label('loadError') || 'The device data could not be loaded.'; + } + }, 300); + }); + els.treeSearch.addEventListener('input', () => { + window.clearTimeout(searchTimer); + searchTimer = window.setTimeout(() => { + const term = els.treeSearch.value.trim(); + selectedRow = null; + if (term.length >= 2) renderSearch(term); else renderTree(); + }, 250); + }); + + // A picker button next to every source-path input on the page. + document.querySelectorAll('input.mapping-path, form[action$="/mappings/new"] input[name="source_path"]').forEach(input => { + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'button button-secondary button-small picker-open'; + // Inside the mapping table only the icon fits next to the path field. + const compact = Boolean(input.closest('table')); + button.textContent = compact ? '🔍' : `🔍 ${label('openLabel') || 'From device'}`; + button.title = label('openTitle') || ''; + button.setAttribute('aria-label', label('openTitle') || label('openLabel') || 'From device'); + if (compact) button.classList.add('picker-open-compact'); + button.addEventListener('click', () => open(input)); + const wrap = document.createElement('span'); + wrap.className = 'picker-input-wrap'; + input.replaceWith(wrap); + wrap.append(input, button); + }); +})(); diff --git a/app/templates/meshcentral_sync.html b/app/templates/meshcentral_sync.html index 7308477..3489b04 100755 --- a/app/templates/meshcentral_sync.html +++ b/app/templates/meshcentral_sync.html @@ -147,4 +147,26 @@ async function startJob(url){setBusy(true);logBox.innerHTML='';offset=0;try{cons startButton.onclick=()=>startJob('/sync/meshcentral/start'); if(dryButton)dryButton.onclick=()=>startJob('/sync/meshcentral/dry-run'); })(); + + + +

{{ t('mesh.picker.title') }}

+

{{ t('mesh.picker.help') }}

+
+ + + +
+ +
+ +
+
+
+ + + +
+
+ {% endblock %} diff --git a/app/version.py b/app/version.py index b4047a6..7ca855a 100755 --- a/app/version.py +++ b/app/version.py @@ -1,2 +1,2 @@ -APP_VERSION = "0.5.5.94" +APP_VERSION = "0.5.5.95" __version__ = APP_VERSION diff --git a/docs/version-history/README.md b/docs/version-history/README.md index c18d755..f29cdc8 100755 --- a/docs/version-history/README.md +++ b/docs/version-history/README.md @@ -1,3 +1,4 @@ +- [0.5.5.95](UPDATE-0.5.5.95.md) - choose MeshCentral mapping source paths by clicking into the stored device JSON, with preview and coverage check. - [0.5.5.94](UPDATE-0.5.5.94.md) - data type conversion for custom fields with preview, exclusion filters and Excel-like value lists in tables, bulk edit for custom fields, MeshCentral fallback values for empty sources. - [0.5.5.93](UPDATE-0.5.5.93.md) - custom fields in asset lists, MeshCentral sync flag for statuses, enforced session secret and translated UI texts. - [0.5.5.92](UPDATE-0.5.5.92.md) - startup diagnostics with runtime, database and callback endpoint information. @@ -30,7 +31,7 @@ Release notes are stored outside the project root to keep the repository overview compact. -The current release is **0.5.5.94**. +The current release is **0.5.5.95**. Older notes are concise English summaries migrated from the original release documents. Git history remains authoritative for exact implementation details. diff --git a/docs/version-history/UPDATE-0.5.5.95.md b/docs/version-history/UPDATE-0.5.5.95.md new file mode 100644 index 0000000..14cbaa6 --- /dev/null +++ b/docs/version-history/UPDATE-0.5.5.95.md @@ -0,0 +1,19 @@ +# Update 0.5.5.95 + +Version 0.5.5.95 lets administrators choose the source path of a MeshCentral field mapping by clicking into the stored device JSON of an asset. + +## Changes + +- **Source path picker:** every source path field in **Sync → MeshCentral → Field mappings** and in the form for a new mapping has a 🔍 button. It opens a dialog with + - a device selection (search over all assets with stored MeshCentral JSON; the last device is remembered), + - the device JSON as an expandable tree with search over keys and values; paths that are already mapped are marked, + - the generated path, editable before applying. Entries inside lists produce `list[].key` (all elements), matching the existing path syntax. Keys containing `.` or `|` cannot be addressed with the path syntax and are shown greyed out. +- **Preview:** for the selected device the dialog shows the raw values of the path and the result of the mapping with the transformation, multiple-value mode, separator and "value if empty"/guard of the mapping row, calculated with the same code as the sync. +- **Coverage check:** "Check coverage across all devices" evaluates the path for every asset with stored JSON: on how many devices a value exists, on how many the mapping writes a value (and how many of them via "value if empty"), plus the most frequent results. +- Applying writes the path into the field; mapping rows still have to be saved with "Save mappings". +- Version updated to 0.5.5.95. + +## Notes + +- The picker uses the JSON stored at the last sync. It requires **Store source JSON on asset** (enabled by default); assets that were never synchronized do not appear. +- No database changes.