- app/auth/ : jetons (lien magique aléatoire haché SHA-256, JWT HS256), dépendances get_current_account / current_account_in_edition / require_roles + require_coordinator / require_staff, et ensure_can_write_position/_shift - Endpoints app/api/auth.py : POST .../auth/magic-link (202 constant, pas de divulgation), POST .../auth/verify (JWT, jeton à usage unique), GET /auth/me - Envoi d'email stubé : le lien est journalisé (logger app.auth, identifiants seulement, aucune donnée nominative) - app/api/accounts.py : CRUD des comptes réservé à la COORDINATION - Rôles appliqués sur toute l'API : COORDINATION accès complet ; RÉFÉRENT lecture globale + écriture sur ses seuls postes/créneaux/affectations ; BÉNÉVOLE sa fiche et ses affectations, aucune écriture - imports.py aligné sur la dépendance get_edition (404 avant 403) - Secret JWT porté à >= 32 octets (config, .env.example, docker-compose) - seed : crée un compte VOLUNTEER pour chaque bénévole avec email (104 comptes) - conftest : fixtures make_account / coordinator / as_account / raw_client ; la suite existante s'exécute en COORDINATION - 13 tests d'authentification + de rôles ; 119 tests au total ; alembic check toujours vert (Account / MagicLinkToken déjà dans la migration 0001) Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017uUsRg7XzopkCPWimwg9ZM
148 lines
4.4 KiB
Python
148 lines
4.4 KiB
Python
"""Endpoints d'import : analyse puis exécution."""
|
|
|
|
import datetime as dt
|
|
|
|
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
|
|
from pydantic import ValidationError
|
|
from sqlmodel import Session, select
|
|
|
|
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,
|
|
DayPartInfo,
|
|
ImportMapping,
|
|
ImportReport,
|
|
PreviewRow,
|
|
)
|
|
from app.importing.service import run_import, suggest_mapping, validate_mapping
|
|
from app.models import Account, DayPart, Edition
|
|
|
|
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")
|
|
)
|
|
|
|
|
|
def _edition_dates(edition: Edition) -> list[dt.date]:
|
|
span = (edition.end_date - edition.start_date).days
|
|
return [edition.start_date + dt.timedelta(days=i) for i in range(span + 1)]
|
|
|
|
|
|
def _day_parts(session: Session, edition: Edition) -> list[DayPart]:
|
|
return list(
|
|
session.exec(
|
|
select(DayPart)
|
|
.where(DayPart.edition_id == edition.id)
|
|
.order_by(DayPart.order)
|
|
)
|
|
)
|
|
|
|
|
|
@router.post("/analyze", response_model=AnalyzeResponse)
|
|
async def analyze(
|
|
file: UploadFile = File(...),
|
|
edition: Edition = Depends(get_edition),
|
|
_guard: Account = Depends(require_coordinator),
|
|
session: Session = Depends(get_session),
|
|
) -> 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),
|
|
edition_dates=_edition_dates(edition),
|
|
day_parts=[
|
|
DayPartInfo(
|
|
code=dp.code,
|
|
label=dp.label,
|
|
start_time=dp.start_time,
|
|
end_time=dp.end_time,
|
|
order=dp.order,
|
|
)
|
|
for dp in _day_parts(session, edition)
|
|
],
|
|
)
|
|
|
|
|
|
@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, edition, _day_parts(session, edition)
|
|
)
|
|
if mapping_errors:
|
|
raise HTTPException(
|
|
status_code=422,
|
|
detail={
|
|
"code": "import.mapping.invalid",
|
|
"errors": [e.model_dump() for e in mapping_errors],
|
|
},
|
|
)
|
|
|
|
return run_import(
|
|
session=session,
|
|
edition=edition,
|
|
table=table,
|
|
mapping=parsed_mapping,
|
|
)
|