feat(csv_import): Enhance CSV import functionality with new endpoint and parsing improvements
- Updated version for csv_import to 0.2.0, reflecting new features. - Implemented a new POST endpoint for universal CSV import, supporting nutrition, weight, and blood pressure modules. - Added CSV parsing function to yield rows as dictionaries for easier data handling. - Enhanced error handling and logging for import operations. - Introduced tests for the new CSV parsing functionality to ensure reliability.
This commit is contained in:
1 parent
36417bfdf3
commit
851018b3b9
6 files changed
+637
-4
No files matched your search
@@ -6,13 +6,16 @@ from __future__ import annotations
|
||||
import logging
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
|
||||
from fastapi import APIRouter, Depends, File, Form, Header, HTTPException, UploadFile
|
||||
from pydantic import BaseModel
|
||||
|
||||
from psycopg2.extras import Json
|
||||
|
||||
from auth import require_auth
|
||||
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.core import (
|
||||
decode_raw_bytes,
|
||||
column_signature,
|
||||
@@ -252,3 +255,211 @@ async def analyze_csv(
|
||||
"detected_mappings": ranked[:5],
|
||||
"available_fields": available_fields,
|
||||
}
|
||||
|
||||
|
||||
def _fetch_mapping_row(cur, mapping_id: int, profile_id: str, module: str) -> dict:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT * FROM csv_field_mappings WHERE id = %s
|
||||
""",
|
||||
(mapping_id,),
|
||||
)
|
||||
m = r2d(cur.fetchone())
|
||||
if not m:
|
||||
raise HTTPException(404, "Mapping nicht gefunden")
|
||||
if m.get("module") != module:
|
||||
raise HTTPException(400, "Mapping gehört zu einem anderen Modul")
|
||||
if not m.get("is_system"):
|
||||
if str(m.get("profile_id") or "") != profile_id:
|
||||
raise HTTPException(403, "Kein Zugriff auf dieses Mapping")
|
||||
return m
|
||||
|
||||
|
||||
def _check_module_feature_access(pid: str, module: str) -> None:
|
||||
if module == "nutrition":
|
||||
access = check_feature_access(pid, "nutrition_entries")
|
||||
log_feature_usage(pid, "nutrition_entries", access, "csv_universal_import")
|
||||
if not access["allowed"]:
|
||||
raise HTTPException(
|
||||
403,
|
||||
f"Limit erreicht (Ernährungseinträge): {access.get('used')}/{access.get('limit')}",
|
||||
)
|
||||
elif module == "weight":
|
||||
access = check_feature_access(pid, "weight_entries")
|
||||
log_feature_usage(pid, "weight_entries", access, "csv_universal_import")
|
||||
if not access["allowed"]:
|
||||
raise HTTPException(
|
||||
403,
|
||||
f"Limit erreicht (Gewichtseinträge): {access.get('used')}/{access.get('limit')}",
|
||||
)
|
||||
|
||||
|
||||
@router.post("/import")
|
||||
async def csv_import_execute(
|
||||
file: UploadFile = File(...),
|
||||
module: str = Form(...),
|
||||
mapping_id: int = Form(...),
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Universal-CSV-Import mit gespeichertem Mapping (Issue #21).
|
||||
Unterstützt: nutrition, weight, blood_pressure. activity: noch nicht.
|
||||
"""
|
||||
if module == "activity":
|
||||
raise HTTPException(
|
||||
501,
|
||||
"Aktivitäts-CSV über den Universal-Importer ist noch nicht freigeschaltet "
|
||||
"(Training-Type-Mapping). Bitte weiterhin /api/activity/import nutzen.",
|
||||
)
|
||||
if not get_module_definition(module):
|
||||
raise HTTPException(400, f"Unbekanntes oder nicht unterstütztes Modul: {module}")
|
||||
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
access_di = check_feature_access(pid, "data_import")
|
||||
log_feature_usage(pid, "data_import", access_di, "csv_universal_import")
|
||||
if not access_di["allowed"]:
|
||||
raise HTTPException(
|
||||
403,
|
||||
"Limit erreicht (Daten importieren): "
|
||||
f"{access_di.get('used')}/{access_di.get('limit')}",
|
||||
)
|
||||
|
||||
_check_module_feature_access(pid, module)
|
||||
|
||||
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 laut Systemkonfiguration)",
|
||||
)
|
||||
text = decode_raw_bytes(raw)
|
||||
if not text.strip():
|
||||
raise HTTPException(400, "Leere Datei")
|
||||
max_rows = limits.get("max_rows_per_file", 50_000)
|
||||
if text.count("\n") > max_rows + 5:
|
||||
raise HTTPException(
|
||||
413,
|
||||
f"Zu viele Zeilen (>{max_rows}) laut Systemkonfiguration",
|
||||
)
|
||||
|
||||
log_id: int | None = None
|
||||
err_response: HTTPException | None = None
|
||||
result: dict | None = None
|
||||
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
m = _fetch_mapping_row(cur, mapping_id, pid, module)
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO csv_import_log (
|
||||
profile_id, mapping_id, module, filename,
|
||||
rows_total, rows_imported, rows_updated, rows_skipped, rows_errors,
|
||||
status, error_details, affected_ids
|
||||
) VALUES (
|
||||
%s::uuid, %s, %s, %s,
|
||||
0, 0, 0, 0, 0,
|
||||
'running', NULL, NULL
|
||||
) RETURNING id
|
||||
""",
|
||||
(pid, mapping_id, module, file.filename or "upload.csv"),
|
||||
)
|
||||
log_id = cur.fetchone()["id"]
|
||||
|
||||
cur.execute("SAVEPOINT csv_import_exec")
|
||||
try:
|
||||
result = run_universal_csv_import(
|
||||
cur,
|
||||
pid,
|
||||
module,
|
||||
text,
|
||||
file.filename or "upload.csv",
|
||||
m,
|
||||
)
|
||||
except Exception as exec_err:
|
||||
cur.execute("ROLLBACK TO SAVEPOINT csv_import_exec")
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE csv_import_log SET
|
||||
finished_at = CURRENT_TIMESTAMP,
|
||||
status = 'failed',
|
||||
error_details = %s
|
||||
WHERE id = %s
|
||||
""",
|
||||
(Json([{"error": str(exec_err)}]), log_id),
|
||||
)
|
||||
err_response = HTTPException(500, f"Import fehlgeschlagen: {exec_err}")
|
||||
else:
|
||||
cur.execute("RELEASE SAVEPOINT csv_import_exec")
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE csv_import_log SET
|
||||
finished_at = CURRENT_TIMESTAMP,
|
||||
status = 'success',
|
||||
rows_total = %s,
|
||||
rows_imported = %s,
|
||||
rows_updated = %s,
|
||||
rows_skipped = %s,
|
||||
rows_errors = %s,
|
||||
error_details = %s,
|
||||
affected_ids = %s
|
||||
WHERE id = %s
|
||||
""",
|
||||
(
|
||||
result["rows_total"],
|
||||
result["rows_imported"],
|
||||
result["rows_updated"],
|
||||
result["rows_skipped"],
|
||||
result["rows_errors"],
|
||||
Json(result["error_details"]),
|
||||
Json(result["affected_ids"]),
|
||||
log_id,
|
||||
),
|
||||
)
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE csv_field_mappings SET
|
||||
usage_count = usage_count + 1,
|
||||
last_used_at = CURRENT_TIMESTAMP,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = %s
|
||||
""",
|
||||
(mapping_id,),
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
|
||||
if err_response:
|
||||
raise err_response
|
||||
|
||||
assert result is not None
|
||||
|
||||
increment_feature_usage(pid, "data_import")
|
||||
|
||||
ne = result.get("new_entries", result["rows_imported"])
|
||||
if module == "nutrition":
|
||||
for _ in range(ne):
|
||||
increment_feature_usage(pid, "nutrition_entries")
|
||||
elif module == "weight":
|
||||
for _ in range(ne):
|
||||
increment_feature_usage(pid, "weight_entries")
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"import_log_id": log_id,
|
||||
"stats": {
|
||||
"total_rows": result["rows_total"],
|
||||
"imported": result["rows_imported"],
|
||||
"updated": result["rows_updated"],
|
||||
"skipped": result["rows_skipped"],
|
||||
"errors": result["rows_errors"],
|
||||
},
|
||||
"error_details": result["error_details"],
|
||||
}
|
||||
Reference in new issue
Block a user