54 lines
1.7 KiB
Python
54 lines
1.7 KiB
Python
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.database import get_db
|
|
from app.crud import audit as audit_crud
|
|
from app.deps import require_permission
|
|
from app.models.user import User
|
|
from app.schemas.scope_import import ScopeImportResult
|
|
from app.services import scope_import as scope_import_service
|
|
|
|
router = APIRouter()
|
|
|
|
_XLSX_TYPES = {
|
|
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
"application/octet-stream",
|
|
"",
|
|
}
|
|
|
|
|
|
@router.post("", response_model=ScopeImportResult)
|
|
async def import_scopes(
|
|
file: UploadFile = File(...),
|
|
db: AsyncSession = Depends(get_db),
|
|
actor: User = Depends(require_permission("augmented_parts:write")),
|
|
):
|
|
filename = file.filename or ""
|
|
if not filename.lower().endswith(".xlsx"):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
detail="Expected an .xlsx spreadsheet.",
|
|
)
|
|
data = await file.read()
|
|
try:
|
|
result = await scope_import_service.import_from_bytes(db, data)
|
|
except Exception as exc: # openpyxl / malformed workbook
|
|
raise HTTPException(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
detail=f"Could not read spreadsheet: {exc}",
|
|
) from exc
|
|
|
|
await audit_crud.log(
|
|
db,
|
|
actor=actor,
|
|
action="update",
|
|
resource_type="AugmentedPart",
|
|
resource_id=None,
|
|
description=(
|
|
f"Scope import ({filename}): {result.created} created, "
|
|
f"{result.updated} updated, {result.skipped} skipped, "
|
|
f"{result.errors} errors"
|
|
),
|
|
)
|
|
return result
|