Compétences supprimées de bout en bout :
- tables `skill`, `volunteer_skill`, `shift_required_skill` ;
- `Volunteer.skill_codes`, `Shift.required_skill_codes`, colonne `skills`
de l'import, règle de validation `MISSING_REQUIRED_SKILL`, jeu de démo.
Disponibilités repensées : `Availability` passe de (`day_part_id`,
`status` tri-état) à une **fenêtre horaire libre** (`date`, `start_time`,
`end_time` ; `end <= start` ⇒ passe minuit), plusieurs par jour.
- Nouveaux endpoints `GET`/`PUT /editions/{id}/volunteers/{vid}/availability`
(PUT = remplacement complet, COORDINATION) et
`GET /editions/{id}/availability` (toute l'édition, pour la grille).
- `OUTSIDE_AVAILABILITY` (toujours WARNING) : compare le créneau à l'union
des fenêtres du bénévole ce jour-là ; renvoie `date` + `uncovered_minutes`.
`DayPart` ne sert plus qu'à la borne de « journée » du cumul 8 h.
- L'import ne gère plus les disponibilités (fenêtres saisies dans l'app) :
`values.py` supprimé, mapping réduit à nom/email/téléphone/commentaire.
Migration 0007 (recrée `availability`). `AvailabilityStatus` supprimé.
158 tests, `alembic check` et `ruff` au vert. Front à suivre.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017uUsRg7XzopkCPWimwg9ZM
116 lines
3.4 KiB
Python
116 lines
3.4 KiB
Python
"""Endpoints d'import : analyse puis exécution."""
|
|
|
|
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
|
|
|
|
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],
|
|
},
|
|
)
|
|
|
|
return run_import(
|
|
session=session,
|
|
edition=edition,
|
|
table=table,
|
|
mapping=parsed_mapping,
|
|
)
|