- Une ligne de log par requête (route modèle, statut, durée, code d'erreur, compte), identifiant X-Request-ID repris dans chaque log et affiché à l'utilisateur sous une erreur, exceptions non gérées tracées (500 JSON) - Journal d'accès d'uvicorn coupé : il exposait le jeton du formulaire public - Logs métier : paiement SumUp, connexion, import, plannings, solveur - Nom du bénévole dans la description du checkout SumUp - Code et identifiant de transaction SumUp enregistrés au paiement (migration 0023), affichés sur la fiche et dans l'export Excel Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
130 lines
3.8 KiB
Python
130 lines
3.8 KiB
Python
"""Endpoints d'import : analyse puis exécution."""
|
|
|
|
import logging
|
|
|
|
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
|
|
from pydantic import ValidationError
|
|
from sqlmodel import Session
|
|
|
|
from app.api.deps import get_edition
|
|
from app.auth.deps import require_coordinator
|
|
from app.db import get_session
|
|
from app.importing.parser import ImportParseError, parse_upload
|
|
from app.importing.schemas import (
|
|
AnalyzeResponse,
|
|
ImportMapping,
|
|
ImportReport,
|
|
PreviewRow,
|
|
)
|
|
from app.importing.service import run_import, suggest_mapping, validate_mapping
|
|
from app.models import Account, Edition
|
|
|
|
logger = logging.getLogger("app.importing")
|
|
|
|
router = APIRouter(prefix="/editions/{edition_id}/import", tags=["import"])
|
|
|
|
_PREVIEW_ROWS = 5
|
|
_MAX_BYTES = 5 * 1024 * 1024
|
|
|
|
|
|
async def _read_upload(file: UploadFile) -> bytes:
|
|
content = await file.read()
|
|
if not content:
|
|
raise HTTPException(
|
|
status_code=400, detail={"code": "import.error.empty_file"}
|
|
)
|
|
if len(content) > _MAX_BYTES:
|
|
raise HTTPException(
|
|
status_code=413, detail={"code": "import.error.file_too_large"}
|
|
)
|
|
return content
|
|
|
|
|
|
def _is_xlsx(filename: str, content: bytes) -> bool:
|
|
return content[:4] == b"PK\x03\x04" or (filename or "").lower().endswith(
|
|
(".xlsx", ".xlsm")
|
|
)
|
|
|
|
|
|
@router.post("/analyze", response_model=AnalyzeResponse)
|
|
async def analyze(
|
|
file: UploadFile = File(...),
|
|
_edition: Edition = Depends(get_edition),
|
|
_guard: Account = Depends(require_coordinator),
|
|
) -> AnalyzeResponse:
|
|
content = await _read_upload(file)
|
|
try:
|
|
table = parse_upload(file.filename or "", content)
|
|
except ImportParseError as exc:
|
|
raise HTTPException(
|
|
status_code=422,
|
|
detail={"code": exc.code, "params": exc.params},
|
|
) from exc
|
|
|
|
preview = [
|
|
PreviewRow(line=i + 2, values=values)
|
|
for i, values in enumerate(table.as_dicts()[:_PREVIEW_ROWS])
|
|
]
|
|
return AnalyzeResponse(
|
|
filename=file.filename or "",
|
|
format="xlsx" if _is_xlsx(file.filename or "", content) else "csv",
|
|
headers=table.headers,
|
|
row_count=len(table.rows),
|
|
preview=preview,
|
|
suggested_mapping=suggest_mapping(table.headers),
|
|
)
|
|
|
|
|
|
@router.post("/execute", response_model=ImportReport)
|
|
async def execute(
|
|
file: UploadFile = File(...),
|
|
mapping: str = Form(...),
|
|
edition: Edition = Depends(get_edition),
|
|
_guard: Account = Depends(require_coordinator),
|
|
session: Session = Depends(get_session),
|
|
) -> ImportReport:
|
|
content = await _read_upload(file)
|
|
|
|
try:
|
|
parsed_mapping = ImportMapping.model_validate_json(mapping)
|
|
except ValidationError as exc:
|
|
raise HTTPException(
|
|
status_code=422,
|
|
detail={"code": "import.mapping.invalid", "errors": exc.errors()},
|
|
) from exc
|
|
|
|
try:
|
|
table = parse_upload(file.filename or "", content)
|
|
except ImportParseError as exc:
|
|
raise HTTPException(
|
|
status_code=422,
|
|
detail={"code": exc.code, "params": exc.params},
|
|
) from exc
|
|
|
|
mapping_errors = validate_mapping(table, parsed_mapping)
|
|
if mapping_errors:
|
|
raise HTTPException(
|
|
status_code=422,
|
|
detail={
|
|
"code": "import.mapping.invalid",
|
|
"errors": [e.model_dump() for e in mapping_errors],
|
|
},
|
|
)
|
|
|
|
report = run_import(
|
|
session=session,
|
|
edition=edition,
|
|
table=table,
|
|
mapping=parsed_mapping,
|
|
)
|
|
logger.info(
|
|
"Import %s (édition %s) : %d lignes — %d créés, %d mis à jour, %d ignorés",
|
|
"simulé" if report.dry_run else "exécuté",
|
|
edition.id,
|
|
report.total_rows,
|
|
report.created,
|
|
report.updated,
|
|
report.skipped,
|
|
)
|
|
return report
|