136 lines
4.2 KiB
Python
136 lines
4.2 KiB
Python
"""Router `auditoria`: consulta del audit trail (oficial y auditor; el analista recibe 403).
|
|
|
|
- `GET /auditoria`: filtros por entidad, acción, usuario, rango de fechas y `entidad_id`,
|
|
paginado.
|
|
- `GET /auditoria/exportar`: las filas que cumplen esos mismos filtros, en CSV y sin paginar. La
|
|
exportación queda en el audit trail.
|
|
- `GET /auditoria/{id}`: una fila con antes y después como diferencias campo por campo.
|
|
"""
|
|
|
|
import tempfile
|
|
from datetime import date
|
|
from typing import Annotated
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
|
from sqlalchemy.orm import Session
|
|
from starlette.background import BackgroundTask
|
|
from starlette.responses import HTMLResponse, StreamingResponse
|
|
|
|
from app import fechas
|
|
from app.auth import requiere_rol
|
|
from app.db import get_db
|
|
from app.models.usuario import Rol
|
|
from app.routers import render
|
|
from app.services.auditoria import (
|
|
CIERRES,
|
|
FiltrosAuditoria,
|
|
consultar,
|
|
detalle,
|
|
exportar_csv,
|
|
opciones,
|
|
)
|
|
|
|
ROLES = (Rol.OFICIAL, Rol.AUDITOR)
|
|
router = APIRouter(tags=["auditoria"], dependencies=[Depends(requiere_rol(*ROLES))])
|
|
|
|
|
|
def _fecha(texto: str | None, campo: str) -> date | None:
|
|
if not texto:
|
|
return None
|
|
try:
|
|
return date.fromisoformat(texto)
|
|
except ValueError as exc:
|
|
raise HTTPException(
|
|
status.HTTP_400_BAD_REQUEST, f"{campo} debe tener la forma AAAA-MM-DD."
|
|
) from exc
|
|
|
|
|
|
def _entero(texto: str | None, campo: str) -> int | None:
|
|
if not texto:
|
|
return None
|
|
try:
|
|
return int(texto)
|
|
except ValueError as exc:
|
|
raise HTTPException(status.HTTP_400_BAD_REQUEST, f"{campo} debe ser un número.") from exc
|
|
|
|
|
|
def _filtros(
|
|
entidad: str | None = None,
|
|
accion: str | None = None,
|
|
usuario: str | None = None,
|
|
desde: str | None = None,
|
|
hasta: str | None = None,
|
|
entidad_id: str | None = None,
|
|
cierre: str | None = None,
|
|
cartera_vigente: str | None = None,
|
|
) -> FiltrosAuditoria:
|
|
return FiltrosAuditoria(
|
|
entidad=entidad or None,
|
|
accion=(accion or "").strip() or None,
|
|
usuario=usuario or None,
|
|
desde=_fecha(desde, "desde"),
|
|
hasta=_fecha(hasta, "hasta"),
|
|
entidad_id=_entero(entidad_id, "entidad_id"),
|
|
cierre=cierre if cierre in CIERRES else None,
|
|
cartera_vigente=(cartera_vigente or "").lower() in ("1", "true"),
|
|
)
|
|
|
|
|
|
@router.get("/auditoria/exportar", include_in_schema=False)
|
|
def exportar(
|
|
request: Request,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
filtros: Annotated[FiltrosAuditoria, Depends(_filtros)],
|
|
) -> StreamingResponse:
|
|
# A un archivo temporal, por bloques: el audit trail completo no cabe en memoria.
|
|
archivo = tempfile.TemporaryFile("w+", encoding="utf-8", newline="") # noqa: SIM115
|
|
try:
|
|
exportar_csv(db, filtros, archivo, request.state.usuario.usuario)
|
|
db.commit()
|
|
archivo.seek(0)
|
|
except BaseException:
|
|
archivo.close()
|
|
raise
|
|
nombre = f"audit_trail_{fechas.hoy():%Y%m%d}.csv"
|
|
return StreamingResponse(
|
|
iter(lambda: archivo.read(1 << 16), ""),
|
|
media_type="text/csv; charset=utf-8",
|
|
headers={
|
|
"Content-Disposition": f'attachment; filename="{nombre}"',
|
|
"Cache-Control": "no-store",
|
|
},
|
|
background=BackgroundTask(archivo.close),
|
|
)
|
|
|
|
|
|
@router.get("/auditoria", include_in_schema=False)
|
|
def lista(
|
|
request: Request,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
filtros: Annotated[FiltrosAuditoria, Depends(_filtros)],
|
|
pagina: int = 1,
|
|
) -> HTMLResponse:
|
|
resultado = consultar(db, filtros, pagina)
|
|
return render(
|
|
request,
|
|
"auditoria/index.html",
|
|
{
|
|
"filtros": filtros,
|
|
"resultado": resultado,
|
|
"opciones": opciones(db),
|
|
"consulta": {k: str(v) for k, v in filtros.activos.items()},
|
|
},
|
|
)
|
|
|
|
|
|
@router.get("/auditoria/{fila_id}", include_in_schema=False)
|
|
def ver(
|
|
request: Request,
|
|
fila_id: int,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
) -> HTMLResponse:
|
|
encontrado = detalle(db, fila_id)
|
|
if encontrado is None:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "No existe esa fila del audit trail.")
|
|
return render(request, "auditoria/detalle.html", {"d": encontrado})
|