feat(csv-import): Add CSV import diagnosis endpoint and related functionality
- Implemented a new endpoint for diagnosing CSV imports without writing to the database, allowing users to validate mappings and type conversions. - Introduced the `diagnose_vitals_row` function to analyze vital metrics and provide detailed feedback on data validity. - Enhanced the CSV import logic to include alias handling for vital fields, improving compatibility with different CSV formats. - Updated the frontend to support the new diagnosis feature, including UI elements for displaying diagnosis results and error details. - Added tests to ensure the correctness of the new diagnosis functionality and its integration with existing import processes.
This commit is contained in:
1 parent
1855f6e57a
commit
c5b0540b11
6 files changed
+394
-18
No files matched your search
@@ -15,15 +15,17 @@ from auth import require_auth, check_feature_access, increment_feature_usage
|
||||
from feature_logger import log_feature_usage
|
||||
from db import get_db, get_cursor, r2d
|
||||
from routers.profiles import get_pid
|
||||
from csv_parser.executor import run_universal_csv_import
|
||||
from csv_parser.executor import diagnose_vitals_row, run_universal_csv_import
|
||||
from csv_parser.core import (
|
||||
decode_raw_bytes,
|
||||
column_signature,
|
||||
get_csv_import_limits,
|
||||
headers_signature_rank_metrics,
|
||||
iter_csv_dict_rows,
|
||||
normalize_header_for_signature,
|
||||
parse_csv_sample,
|
||||
)
|
||||
from csv_parser.type_converter import build_row_after_mapping, diagnose_row_mapping
|
||||
from csv_parser.field_units import source_unit_choices_for_field
|
||||
from csv_parser.module_registry import get_module_definition, list_modules, validate_field_mappings
|
||||
from csv_parser.sleep_apple_import import detect_apple_sleep_csv_format
|
||||
@@ -339,6 +341,70 @@ async def analyze_csv(
|
||||
}
|
||||
|
||||
|
||||
@router.post("/import-diagnose")
|
||||
async def csv_import_diagnose(
|
||||
file: UploadFile = File(...),
|
||||
mapping_id: int = Form(...),
|
||||
module: Optional[str] = Form(default=None),
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Kein Import, keine Quota: gleiche Datei + gewählte Vorlage wie beim Import,
|
||||
aber nur die ersten Zeilen durch Mapping/Typkonvertierung (und Vital-Checks).
|
||||
Zum Debugging wenn «Datum fehlt» o. Ä. ohne DB-Zugriff.
|
||||
"""
|
||||
pid = get_pid(x_profile_id)
|
||||
raw = await file.read()
|
||||
limits = _load_import_limits()
|
||||
max_bytes = limits.get("max_file_bytes", 52_428_800)
|
||||
if len(raw) > max_bytes:
|
||||
raise HTTPException(413, f"Datei zu groß (max. {max_bytes} Bytes)")
|
||||
text = decode_raw_bytes(raw)
|
||||
if not text.strip():
|
||||
raise HTTPException(400, "Leere Datei")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
m = _fetch_mapping_row(cur, mapping_id, pid, module)
|
||||
|
||||
if not get_module_definition(m["module"]):
|
||||
raise HTTPException(400, f"Modul nicht unterstützt: {m['module']}")
|
||||
|
||||
fm = m.get("field_mappings") or {}
|
||||
if isinstance(fm, str):
|
||||
fm = {}
|
||||
tc = m.get("type_conversions")
|
||||
if not isinstance(tc, dict):
|
||||
tc = {}
|
||||
delim = str(m.get("delimiter") or ",")
|
||||
exec_module = str(m["module"])
|
||||
|
||||
rows_out: list[dict[str, Any]] = []
|
||||
for i, row in enumerate(iter_csv_dict_rows(text, delim, has_header=True)):
|
||||
if i >= 5:
|
||||
break
|
||||
typed = build_row_after_mapping(row, fm, tc, module=exec_module)
|
||||
dm = diagnose_row_mapping(row, fm, tc, module=exec_module, mapped_typed=typed)
|
||||
entry: dict[str, Any] = {
|
||||
"row_index": i + 1,
|
||||
**dm,
|
||||
}
|
||||
if exec_module == "vitals_baseline":
|
||||
entry["vitals"] = diagnose_vitals_row(typed)
|
||||
rows_out.append(entry)
|
||||
|
||||
return {
|
||||
"mapping_id": mapping_id,
|
||||
"mapping_name": m.get("mapping_name"),
|
||||
"module": exec_module,
|
||||
"delimiter_used": delim,
|
||||
"has_header": bool(m.get("has_header", True)),
|
||||
"rows_diagnosed": len(rows_out),
|
||||
"rows": rows_out,
|
||||
}
|
||||
|
||||
|
||||
def _fetch_mapping_row(
|
||||
cur,
|
||||
mapping_id: int,
|
||||
|
||||
Reference in new issue
Block a user