feat(csv-parser): Implement CSV import functionality with mapping and type conversion
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s

- Added permissions for editing and deleting CSV field mappings.
- Created type converter for CSV cells to handle various data types.
- Implemented database migrations for CSV field mappings and import logs.
- Seeded initial system templates for nutrition and activity data imports.
- Developed admin endpoints for managing system CSV templates.
- Introduced user endpoints for CSV import analysis and mapping retrieval.
- Added tests for core CSV parser functionalities, including delimiter detection and value conversion.
This commit is contained in:
Lars committed 2026-04-09 21:37:19 +02:00
1 parent 73963e7140
commit 4a771f6a83
16 files changed
+3252 -1

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
"""Universal CSV import foundation (Issue #21)."""
from csv_parser.core import (
decode_raw_bytes,
sniff_delimiter,
parse_csv_sample,
column_signature,
normalize_header_for_signature,
)
from csv_parser.module_registry import MODULE_DEFINITIONS, get_module_definition, list_modules
from csv_parser.type_converter import convert_value, build_row_after_mapping
from csv_parser.permissions import user_may_delete_mapping, user_may_edit_mapping_row
__all__ = [
"decode_raw_bytes",
"sniff_delimiter",
"parse_csv_sample",
"column_signature",
"normalize_header_for_signature",
"MODULE_DEFINITIONS",
"get_module_definition",
"list_modules",
"convert_value",
"build_row_after_mapping",
"user_may_delete_mapping",
"user_may_edit_mapping_row",
]
+137
View File
@@ -0,0 +1,137 @@
"""
CSV bytes → text, delimiter sniffing, strukturierte Erstzeilen für Analyse (Issue #21).
"""
from __future__ import annotations
import csv
import io
import re
from typing import Any, List, Tuple
_DEFAULT_DELIMS = [",", ";", "\t"]
def decode_raw_bytes(raw: bytes) -> str:
"""UTF-8 bevorzugt, Fallback Latin-1; BOM entfernen."""
if not raw:
return ""
for enc in ("utf-8-sig", "utf-8", "latin-1"):
try:
text = raw.decode(enc)
break
except UnicodeDecodeError:
text = ""
continue
else:
text = raw.decode("utf-8", errors="replace")
if text.startswith("\ufeff"):
text = text[1:]
return text
def sniff_delimiter(sample_line: str) -> str:
"""
Heuristik: Zähle Vorkommen der Kandidaten in der ersten Datenzeile.
Kein csv.Sniffer (robuster gegen kurze Zeilen).
"""
if not sample_line or not sample_line.strip():
return ","
best = ","
best_count = -1
for d in _DEFAULT_DELIMS:
c = sample_line.count(d)
if c > best_count:
best_count = c
best = d
return best
def _split_first_lines(text: str, max_lines: int = 5) -> List[str]:
lines: List[str] = []
for line in text.splitlines():
if line.strip():
lines.append(line)
if len(lines) >= max_lines:
break
return lines
def parse_csv_sample(
text: str,
delimiter: str | None = None,
has_header: bool = True,
max_data_rows: int = 5,
) -> Tuple[List[str], List[dict[str, str]], str]:
"""
Gibt (headers, rows_as_dicts, verwendetes_delimiter) zurück.
rows sind Rohstrings pro Zelle.
"""
lines = _split_first_lines(text, max_lines=50)
if not lines:
return [], [], ","
delim = delimiter if delimiter is not None else sniff_delimiter(lines[0])
reader = csv.reader(io.StringIO(text.replace("\r\n", "\n").replace("\r", "\n")), delimiter=delim)
rows_raw: List[List[str]] = []
for i, row in enumerate(reader):
if i >= 1 + max_data_rows + (1 if has_header else 0):
break
if not any(c.strip() for c in row):
continue
rows_raw.append(row)
if not rows_raw:
return [], [], delim
if has_header:
headers = [h.strip() for h in rows_raw[0]]
data = rows_raw[1 : 1 + max_data_rows]
else:
n = len(rows_raw[0])
headers = [f"col_{i}" for i in range(n)]
data = rows_raw[:max_data_rows]
dict_rows: List[dict[str, str]] = []
for r in data:
row_dict: dict[str, str] = {}
for j, h in enumerate(headers):
row_dict[h] = r[j].strip() if j < len(r) else ""
dict_rows.append(row_dict)
return headers, dict_rows, delim
def normalize_header_for_signature(name: str) -> str:
s = name.strip().lower()
s = re.sub(r"\s+", "_", s)
s = re.sub(r"[^a-z0-9_äöüß().%-]+", "_", s)
return s.strip("_")
def column_signature(headers: List[str]) -> List[str]:
"""Sortierte normalisierte Spaltennamen für Signatur-Vergleich."""
return sorted({normalize_header_for_signature(h) for h in headers if h is not None and str(h).strip()})
def headers_signature_match_score(sig_csv: List[str], sig_template: List[str]) -> float:
"""Jaccard-Überlappung 0..1."""
a, b = set(sig_csv), set(sig_template)
if not a and not b:
return 1.0
if not a or not b:
return 0.0
inter = len(a & b)
union = len(a | b)
return inter / union if union else 0.0
def get_csv_import_limits(conn_row: dict | None) -> dict[str, int]:
"""Liest Limits aus system_config.csv_import; Fallback bei fehlendem Key."""
defaults = {"max_rows_per_file": 50_000, "max_file_bytes": 52_428_800}
if not conn_row or "value" not in conn_row:
return defaults
val = conn_row["value"]
if isinstance(val, dict):
out = {**defaults, **{k: int(v) for k, v in val.items() if k in defaults}}
return out
return defaults
+88
View File
@@ -0,0 +1,88 @@
"""
Ziel-Module für CSV-Import: Tabellen-Felder, Pflichtfelder, Duplikat-Strategie (Issue #21).
Hinweis: blood_pressure nutzt in der DB measured_at; Logik-Felder measured_date + measured_time
werden im Executor zu measured_at zusammengefügt (Phase Import-Executor).
Activity: date kann aus start_time (ISO-Datetime) abgeleitet werden, wenn nur start_time gesetzt ist.
"""
from __future__ import annotations
from typing import Any, Dict, cast
MODULE_DEFINITIONS: Dict[str, Dict[str, Any]] = {
"nutrition": {
"table": "nutrition_log",
"fields": {
"date": {"type": "date", "required": True},
"kcal": {"type": "float", "required": False},
"protein_g": {"type": "float", "required": False, "min": 0},
"fat_g": {"type": "float", "required": False, "min": 0},
"carbs_g": {"type": "float", "required": False, "min": 0},
},
"duplicate_key": ["profile_id", "date"],
"duplicate_strategy": "update",
},
"activity": {
"table": "activity_log",
"fields": {
"date": {"type": "date", "required": True},
"start_time": {"type": "time", "required": False},
"end_time": {"type": "time", "required": False},
"activity_type": {"type": "string", "required": True},
"duration_min": {"type": "float", "required": False, "min": 0},
"kcal_active": {"type": "float", "required": False},
"distance_km": {"type": "float", "required": False},
"hr_avg": {"type": "float", "required": False, "min": 30, "max": 220},
},
"derive_date_from_datetime_field": "start_time",
"duplicate_key": ["profile_id", "date", "start_time"],
"duplicate_strategy": "update",
},
"blood_pressure": {
"table": "blood_pressure_log",
"fields": {
"measured_date": {"type": "date", "required": True},
"measured_time": {"type": "time", "required": True},
"systolic": {"type": "int", "required": True},
"diastolic": {"type": "int", "required": True},
"pulse": {"type": "int", "required": False},
},
"logical_to_db": "blood_pressure_composite_measured_at",
"duplicate_key": ["profile_id", "measured_at"],
"duplicate_strategy": "update",
},
"weight": {
"table": "weight_log",
"fields": {
"date": {"type": "date", "required": True},
"weight": {"type": "float", "required": True, "min": 20, "max": 400},
"note": {"type": "string", "required": False, "max_length": 2000},
},
"duplicate_key": ["profile_id", "date"],
"duplicate_strategy": "update",
},
}
def get_module_definition(module: str) -> Dict[str, Any] | None:
return MODULE_DEFINITIONS.get(module)
def list_modules() -> list[str]:
return sorted(MODULE_DEFINITIONS.keys())
def validate_field_mappings(module: str, field_mappings: dict) -> None:
"""Wirft ValueError bei unbekanntem Modul oder unbekanntem DB-Feld."""
mod = get_module_definition(module)
if not mod:
raise ValueError(f"Unbekanntes Modul: {module}")
fields = cast(dict, mod["fields"])
allowed = set(fields.keys())
for _csv_col, db_field in field_mappings.items():
if db_field in ("", None, "-"):
continue
if db_field not in allowed:
raise ValueError(f"Ungültiges Zielfeld '{db_field}' für Modul '{module}'")
+19
View File
@@ -0,0 +1,19 @@
"""Zugriffsregeln für csv_field_mappings (Issue #21)."""
from __future__ import annotations
from typing import Any, Mapping
def user_may_edit_mapping_row(row: Mapping[str, Any], session: Mapping[str, Any]) -> bool:
if session.get("role") == "admin":
return True
if row.get("is_system"):
return False
return str(row.get("profile_id")) == str(session.get("profile_id"))
def user_may_delete_mapping(row: Mapping[str, Any], session: Mapping[str, Any]) -> bool:
if row.get("is_system"):
return False
return str(row.get("profile_id")) == str(session.get("profile_id"))
+142
View File
@@ -0,0 +1,142 @@
"""
Typkonvertierung für CSV-Zellen gemäß type_conversions-JSON (Issue #21).
"""
from __future__ import annotations
import datetime as dt
import re
from decimal import Decimal, InvalidOperation
from typing import Any, Mapping
# Alias → strptime (JSON in Kleinbuchstaben)
DATE_FORMAT_STRPTIME: dict[str, str] = {
"yyyy-mm-dd": "%Y-%m-%d",
"mm/dd/yyyy": "%m/%d/%Y",
"dd/mm/yyyy": "%d/%m/%Y",
"dd.mm.yyyy": "%d.%m.%Y",
"dd.mm.yyyy HH:MM": "%d.%m.%Y %H:%M",
"yyyy-mm-dd HH:MM:SS": "%Y-%m-%d %H:%M:%S",
"yyyy-mm-dd hh:mm:ss": "%Y-%m-%d %H:%M:%S",
}
TIME_FORMAT_STRPTIME: dict[str, str] = {
"HH:MM": "%H:%M",
"HH:MM:SS": "%H:%M:%S",
}
def _parse_float(raw: str, decimal_sep: str = ".") -> float:
s = raw.strip()
if not s:
raise ValueError("leer")
if decimal_sep == ",":
s = s.replace(".", "").replace(",", ".")
else:
s = s.replace(",", "")
return float(Decimal(s))
def _parse_int(raw: str) -> int:
s = re.sub(r"[^\d-]", "", raw.strip())
if not s:
raise ValueError("leer")
return int(s)
def convert_value(
raw: str,
db_field: str,
spec: Mapping[str, Any] | None,
) -> Any:
"""
Konvertiert eine Roh-Zelle in einen Python-Wert.
spec kommt aus type_conversions[db_field].
"""
if spec is None:
return raw.strip() if raw else None
if raw is None:
return None
s = raw.strip()
if s == "":
return None
t = spec.get("type", "string")
if t == "string":
return s
if t in ("float", "number"):
dec = spec.get("decimal_separator", ".")
v = _parse_float(s, dec)
factor = spec.get("conversion_factor")
if factor is not None:
v = float(v) * float(factor)
return v
if t == "int":
return _parse_int(s)
if t == "date":
fmt_key = str(spec.get("format", "yyyy-mm-dd"))
fmt = DATE_FORMAT_STRPTIME.get(fmt_key.lower())
if not fmt:
raise ValueError(f"Unbekanntes Datumsformat: {fmt_key}")
part = dt.datetime.strptime(s, fmt)
extract = spec.get("extract", "date_only")
if extract == "date_only":
return part.date()
return part
if t == "time":
fmt_key = str(spec.get("format", "HH:MM"))
fmt = TIME_FORMAT_STRPTIME.get(fmt_key, fmt_key)
part = dt.datetime.strptime(s, fmt)
return part.time()
if t == "datetime":
fmt_key = str(spec.get("format", "yyyy-mm-dd HH:MM:SS"))
fmt = DATE_FORMAT_STRPTIME.get(fmt_key.lower())
if not fmt:
raise ValueError(f"Unbekanntes Datetime-Format: {fmt_key}")
return dt.datetime.strptime(s, fmt)
if t == "duration":
# z. B. HH:MM:SS → Minuten
fmt_key = str(spec.get("format", "HH:MM:SS"))
target = spec.get("target_unit", "minutes")
parts = s.split(":")
if fmt_key == "HH:MM:SS" and len(parts) == 3:
h, m, sec = int(parts[0]), int(parts[1]), int(parts[2])
total_min = h * 60 + m + sec / 60.0
if target == "minutes":
return round(total_min, 4)
raise ValueError(f"Unbekannte duration target_unit: {target}")
if fmt_key == "HH:MM" and len(parts) == 2:
h, m = int(parts[0]), int(parts[1])
return h * 60 + m
raise ValueError(f"Duration nicht parsbar: {s!r}")
return s
def build_row_after_mapping(
csv_row: Mapping[str, str],
field_mappings: Mapping[str, str],
type_conversions: Mapping[str, Any] | None,
) -> dict[str, Any]:
"""
Wendet Zuordnung csv_spalte → db_feld und Typkonvertierung an.
Unzugeordnete oder „—“ werden übersprungen.
"""
out: dict[str, Any] = {}
tc = type_conversions or {}
for csv_col, raw in csv_row.items():
db_field = field_mappings.get(csv_col)
if not db_field or db_field in ("-", "_skip"):
continue
spec = tc.get(db_field)
try:
out[db_field] = convert_value(raw, db_field, spec if isinstance(spec, dict) else None)
except Exception:
out[db_field] = None
return out