Version 0.5.5.95: pick MeshCentral source paths from device JSON
- 🔍 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 <noreply@anthropic.com>
This commit is contained in:
1 parent
40cd88871f
commit
d6de4d9878
10 files changed
+723
-4
No files matched your search
+130
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user