GET /evidencia/{id}/exportar?fecha= descarga evidencia_<id_externo>_<fecha>.zip para los tres roles: reconstrucción completa, CSV de evaluaciones, alertas, casos, eventos, documentos, coincidencias y audit trail del cliente hasta la fecha, modelo y reglas vigentes, y manifiesto con usuario, fecha, sha de git y SHA-256 de cada archivo. Sin binarios (solo nombre y hash). La exportación queda en el audit trail con el hash del manifiesto.
114 lines
3.8 KiB
Python
114 lines
3.8 KiB
Python
"""Router `evidencia`: reconstrucción de un cliente a una fecha (paso 7 del recorrido).
|
|
|
|
- `GET /evidencia`: elegir cliente (por `id_externo`) y fecha.
|
|
- `GET /evidencia/{cliente_id}?fecha=AAAA-MM-DD`: lo que el sistema sabía del cliente al final
|
|
de esa fecha (por omisión, hoy). Solo lectura: lo único que se escribe es la fila de acceso
|
|
del audit trail, que deja el middleware. Accesible para los tres roles.
|
|
- `GET /evidencia/{cliente_id}/exportar?fecha=AAAA-MM-DD`: el `.zip` de evidencia
|
|
(`services.evidencia`). Es lectura, va por GET y lo pueden descargar los tres roles; la
|
|
exportación queda en el audit trail con el hash de su manifiesto.
|
|
"""
|
|
|
|
from datetime import date
|
|
from typing import Annotated
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
from starlette.responses import HTMLResponse, RedirectResponse, Response
|
|
|
|
from app.db import get_db
|
|
from app.models import Cliente
|
|
from app.routers import render
|
|
from app.services.agregados import tenant_de_sesion
|
|
from app.services.evidencia import exportar_cliente, nombre_archivo
|
|
from app.services.reconstruccion import (
|
|
ClienteNoEncontradoError,
|
|
hoy_local,
|
|
reconstruir_cliente,
|
|
)
|
|
|
|
router = APIRouter(tags=["evidencia"])
|
|
|
|
|
|
def _fecha(texto: str | None) -> date:
|
|
if not texto:
|
|
return hoy_local()
|
|
try:
|
|
return date.fromisoformat(texto)
|
|
except ValueError as exc:
|
|
raise HTTPException(
|
|
status.HTTP_400_BAD_REQUEST, "La fecha debe tener la forma AAAA-MM-DD."
|
|
) from exc
|
|
|
|
|
|
@router.get("/evidencia", include_in_schema=False)
|
|
def indice(
|
|
request: Request,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
cliente: str | None = None,
|
|
fecha: str | None = None,
|
|
) -> Response:
|
|
dia = _fecha(fecha)
|
|
error = None
|
|
if cliente:
|
|
tenant = tenant_de_sesion(db)
|
|
cliente_id = db.scalar(
|
|
select(Cliente.id).where(
|
|
Cliente.tenant_id == tenant.id, Cliente.id_externo == cliente.strip()
|
|
)
|
|
)
|
|
if cliente_id is not None:
|
|
return RedirectResponse(
|
|
f"/evidencia/{cliente_id}?fecha={dia.isoformat()}", status_code=303
|
|
)
|
|
error = f"No hay ningún cliente con identificador {cliente.strip()}."
|
|
return render(
|
|
request,
|
|
"evidencia/index.html",
|
|
{"fecha": dia, "cliente": cliente or "", "error": error},
|
|
)
|
|
|
|
|
|
@router.get("/evidencia/{cliente_id}", include_in_schema=False)
|
|
def cliente(
|
|
request: Request,
|
|
cliente_id: int,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
fecha: str | None = None,
|
|
) -> HTMLResponse:
|
|
dia = _fecha(fecha)
|
|
try:
|
|
reconstruccion = reconstruir_cliente(db, cliente_id, dia)
|
|
except ClienteNoEncontradoError as exc:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, str(exc)) from exc
|
|
return render(
|
|
request,
|
|
"evidencia/cliente.html",
|
|
{"r": reconstruccion, "d": reconstruccion.como_dict(), "hoy": hoy_local()},
|
|
)
|
|
|
|
|
|
@router.get("/evidencia/{cliente_id}/exportar", include_in_schema=False)
|
|
def exportar(
|
|
request: Request,
|
|
cliente_id: int,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
fecha: str | None = None,
|
|
) -> Response:
|
|
dia = _fecha(fecha)
|
|
try:
|
|
contenido = exportar_cliente(db, cliente_id, dia, request.state.usuario.usuario)
|
|
except ClienteNoEncontradoError as exc:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, str(exc)) from exc
|
|
db.commit()
|
|
id_externo = db.scalar(select(Cliente.id_externo).where(Cliente.id == cliente_id))
|
|
return Response(
|
|
contenido,
|
|
media_type="application/zip",
|
|
headers={
|
|
"Content-Disposition": f'attachment; filename="{nombre_archivo(id_externo, dia)}"',
|
|
"Cache-Control": "no-store",
|
|
},
|
|
)
|