feat(csv-templates): Introduce CSV template analysis and validation features
- Added a new endpoint for analyzing uploaded CSV files, providing suggestions for field mappings and type conversions. - Implemented validation for required field targets to ensure all mandatory fields are mapped correctly. - Enhanced the admin CSV templates interface with new routes and navigation options in the frontend. - Updated API utility functions to support the new CSV analysis functionality. - Improved error handling for CSV uploads, including file size and row count checks.
This commit is contained in:
1 parent
338163ac0b
commit
c10da55ec6
9 files changed
+1017
-4
No files matched your search
@@ -5,14 +5,26 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
|
||||
from pydantic import BaseModel, Field
|
||||
from psycopg2.extras import Json
|
||||
|
||||
from auth import require_admin
|
||||
from db import get_db, get_cursor, r2d
|
||||
from csv_parser.core import get_csv_import_limits
|
||||
from csv_parser.module_registry import get_module_definition, validate_field_mappings
|
||||
from csv_parser.core import (
|
||||
column_signature,
|
||||
decode_raw_bytes,
|
||||
get_csv_import_limits,
|
||||
headers_signature_match_score,
|
||||
normalize_header_for_signature,
|
||||
parse_csv_sample,
|
||||
)
|
||||
from csv_parser.mapping_suggest import build_type_conversions_for_mapping, suggest_field_mappings
|
||||
from csv_parser.module_registry import (
|
||||
get_module_definition,
|
||||
validate_field_mappings,
|
||||
validate_required_field_targets,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/admin/csv-templates", tags=["admin", "csv-import"])
|
||||
|
||||
@@ -112,6 +124,127 @@ def list_system_templates(
|
||||
return {"templates": [_row_full(m) for m in rows]}
|
||||
|
||||
|
||||
@router.post("/analyze-upload")
|
||||
async def admin_analyze_csv_for_template(
|
||||
file: UploadFile = File(...),
|
||||
module: str = Form(...),
|
||||
delimiter: Optional[str] = Form(default=None),
|
||||
seed_template_id: Optional[int] = Form(default=None),
|
||||
session: dict = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
CSV hochladen wie im Nutzer-Import: Spalten + Vorschau + Vorschläge für field_mappings
|
||||
und type_conversions. Optional Seed-Vorlage (ID) oder beste Jaccard-Systemvorlage für das Modul.
|
||||
"""
|
||||
_ = session
|
||||
if not get_module_definition(module):
|
||||
raise HTTPException(400, f"Unbekanntes Modul: {module}")
|
||||
|
||||
raw = await file.read()
|
||||
limits = _admin_csv_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",
|
||||
)
|
||||
|
||||
delim = delimiter if delimiter in (",", ";", "\t") else None
|
||||
headers, sample_rows, used_delim = parse_csv_sample(text, delimiter=delim, max_data_rows=5)
|
||||
if not headers:
|
||||
raise HTTPException(400, "Keine Kopfzeile oder leeres CSV")
|
||||
|
||||
sig = column_signature(headers)
|
||||
|
||||
seed_row: dict | None = None
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if seed_template_id is not None:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT * FROM csv_field_mappings
|
||||
WHERE id = %s AND is_system = true AND profile_id IS NULL AND module = %s
|
||||
""",
|
||||
(seed_template_id, module),
|
||||
)
|
||||
seed_row = r2d(cur.fetchone())
|
||||
if not seed_row:
|
||||
raise HTTPException(404, "Seed-Vorlage nicht gefunden oder falsches Modul")
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT * FROM csv_field_mappings
|
||||
WHERE is_system = true AND profile_id IS NULL AND module = %s
|
||||
""",
|
||||
(module,),
|
||||
)
|
||||
rows = [r2d(r) for r in cur.fetchall()]
|
||||
best: dict | None = None
|
||||
best_score = -1.0
|
||||
for t in rows:
|
||||
t_sig = list(t.get("column_signature") or [])
|
||||
t_norm = sorted({normalize_header_for_signature(str(s)) for s in t_sig})
|
||||
score = headers_signature_match_score(sig, t_norm)
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best = t
|
||||
if best and best_score > 0:
|
||||
seed_row = best
|
||||
|
||||
seed_fm = (seed_row or {}).get("field_mappings") or {}
|
||||
if isinstance(seed_fm, str):
|
||||
seed_fm = {}
|
||||
seed_tc = (seed_row or {}).get("type_conversions")
|
||||
if not isinstance(seed_tc, dict):
|
||||
seed_tc = {}
|
||||
|
||||
field_mappings = suggest_field_mappings(headers, module, seed_fm if seed_fm else None)
|
||||
type_conversions = build_type_conversions_for_mapping(module, field_mappings, seed_tc if seed_tc else None)
|
||||
|
||||
seed_meta = None
|
||||
if seed_row:
|
||||
t_sig = [normalize_header_for_signature(str(s)) for s in (seed_row.get("column_signature") or [])]
|
||||
seed_meta = {
|
||||
"id": seed_row["id"],
|
||||
"mapping_name": seed_row.get("mapping_name"),
|
||||
"confidence": round(headers_signature_match_score(sig, sorted(set(t_sig))), 4)
|
||||
if t_sig
|
||||
else 0.0,
|
||||
}
|
||||
|
||||
return {
|
||||
"filename": file.filename,
|
||||
"module": module,
|
||||
"delimiter": used_delim,
|
||||
"encoding": "utf-8",
|
||||
"columns": headers,
|
||||
"column_signature_normalized": sig,
|
||||
"sample_rows": sample_rows,
|
||||
"seed_template": seed_meta,
|
||||
"field_mappings": field_mappings,
|
||||
"type_conversions": type_conversions,
|
||||
}
|
||||
|
||||
|
||||
def _admin_csv_limits() -> dict[str, int]:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT value FROM system_config WHERE key = %s", ("csv_import",))
|
||||
row = cur.fetchone()
|
||||
return get_csv_import_limits(r2d(row) if row else None)
|
||||
|
||||
|
||||
@router.get("/{template_id}")
|
||||
def get_system_template(template_id: int, session: dict = Depends(require_admin)):
|
||||
with get_db() as conn:
|
||||
@@ -132,6 +265,7 @@ def create_system_template(body: CsvSystemTemplateCreate, session: dict = Depend
|
||||
raise HTTPException(400, f"Unbekanntes Modul: {body.module}")
|
||||
try:
|
||||
validate_field_mappings(body.module, body.field_mappings)
|
||||
validate_required_field_targets(body.module, body.field_mappings)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e))
|
||||
|
||||
@@ -187,6 +321,7 @@ def update_system_template(
|
||||
if "field_mappings" in patch:
|
||||
try:
|
||||
validate_field_mappings(existing["module"], fm)
|
||||
validate_required_field_targets(existing["module"], fm)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e))
|
||||
|
||||
|
||||
Reference in new issue
Block a user