- Tabla activity_log en SQLite (migración automática) - Registra: login, login_fallido, rda_enviado, rda_masivo, rda_directo, automation_run, contrato_creado, contrato_editado, contrato_toggle - Endpoint GET /logs/actividad con filtros por usuario, acción y fecha - UI /logs/actividad con badges de color por tipo de acción - Enlace "Actividad" en navegación lateral Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
161 lines
5.1 KiB
Python
161 lines
5.1 KiB
Python
import json as json_lib
|
|
from fastapi import APIRouter, Request, Depends
|
|
from fastapi.responses import JSONResponse
|
|
from app.database import get_connection
|
|
from app.auth import get_current_user
|
|
from app.services.json_generator import _clean_times
|
|
|
|
router = APIRouter(prefix="/logs", tags=["logs"])
|
|
|
|
|
|
def _limpiar_json_enviado(raw: str) -> str:
|
|
if not raw:
|
|
return raw
|
|
try:
|
|
return json_lib.dumps(_clean_times(json_lib.loads(raw)), ensure_ascii=False, indent=2)
|
|
except Exception:
|
|
return raw
|
|
|
|
PAGE_SIZE = 50
|
|
|
|
|
|
@router.get("")
|
|
async def logs_page(
|
|
request: Request,
|
|
user: dict = Depends(get_current_user),
|
|
tipo: str = "",
|
|
status: str = "",
|
|
factura: str = "",
|
|
paciente: str = "",
|
|
fecha_desde: str = "",
|
|
fecha_hasta: str = "",
|
|
offset: int = 0,
|
|
):
|
|
conn = get_connection()
|
|
where = ["1=1"]
|
|
params = []
|
|
|
|
if tipo:
|
|
where.append("e.tipo = ?")
|
|
params.append(tipo)
|
|
if status:
|
|
where.append("e.status = ?")
|
|
params.append(status)
|
|
if factura:
|
|
where.append("e.factura LIKE ?")
|
|
params.append(f"%{factura}%")
|
|
if paciente:
|
|
where.append("(CAST(e.idrecepcion AS TEXT) LIKE ? OR e.contrato LIKE ?)")
|
|
params += [f"%{paciente}%", f"%{paciente}%"]
|
|
if fecha_desde:
|
|
where.append("DATE(e.created_at) >= ?")
|
|
params.append(fecha_desde)
|
|
if fecha_hasta:
|
|
where.append("DATE(e.created_at) <= ?")
|
|
params.append(fecha_hasta)
|
|
|
|
w = " AND ".join(where)
|
|
|
|
total = conn.execute(f"SELECT COUNT(*) FROM envios e WHERE {w}", params).fetchone()[0]
|
|
|
|
envios = conn.execute(f"""
|
|
SELECT e.*, u.username FROM envios e
|
|
LEFT JOIN users u ON e.user_id = u.id
|
|
WHERE {w}
|
|
ORDER BY e.created_at DESC
|
|
LIMIT ? OFFSET ?
|
|
""", params + [PAGE_SIZE, offset]).fetchall()
|
|
|
|
stats = conn.execute("""
|
|
SELECT tipo, status, COUNT(*) as cnt
|
|
FROM envios
|
|
GROUP BY tipo, status
|
|
ORDER BY tipo, status
|
|
""").fetchall()
|
|
|
|
conn.close()
|
|
|
|
has_more = (offset + PAGE_SIZE) < total
|
|
|
|
return request.app.state.templates.TemplateResponse("logs.html", {
|
|
"request": request, "user": user,
|
|
"envios": envios, "stats": stats, "total": total,
|
|
"filtro_tipo": tipo, "filtro_status": status,
|
|
"filtro_factura": factura, "filtro_paciente": paciente,
|
|
"filtro_fecha_desde": fecha_desde, "filtro_fecha_hasta": fecha_hasta,
|
|
"offset": offset, "page_size": PAGE_SIZE, "has_more": has_more,
|
|
})
|
|
|
|
|
|
@router.get("/actividad")
|
|
async def actividad_page(
|
|
request: Request,
|
|
user: dict = Depends(get_current_user),
|
|
username: str = "",
|
|
accion: str = "",
|
|
fecha_desde: str = "",
|
|
fecha_hasta: str = "",
|
|
offset: int = 0,
|
|
):
|
|
conn = get_connection()
|
|
where = ["1=1"]
|
|
params = []
|
|
if username:
|
|
where.append("a.username = ?")
|
|
params.append(username)
|
|
if accion:
|
|
where.append("a.accion = ?")
|
|
params.append(accion)
|
|
if fecha_desde:
|
|
where.append("DATE(a.created_at) >= ?")
|
|
params.append(fecha_desde)
|
|
if fecha_hasta:
|
|
where.append("DATE(a.created_at) <= ?")
|
|
params.append(fecha_hasta)
|
|
w = " AND ".join(where)
|
|
total = conn.execute(f"SELECT COUNT(*) FROM activity_log a WHERE {w}", params).fetchone()[0]
|
|
rows = conn.execute(f"""
|
|
SELECT a.* FROM activity_log a
|
|
WHERE {w} ORDER BY a.created_at DESC LIMIT ? OFFSET ?
|
|
""", params + [PAGE_SIZE, offset]).fetchall()
|
|
usuarios = conn.execute("SELECT DISTINCT username FROM activity_log ORDER BY username").fetchall()
|
|
acciones = conn.execute("SELECT DISTINCT accion FROM activity_log ORDER BY accion").fetchall()
|
|
conn.close()
|
|
return request.app.state.templates.TemplateResponse("actividad.html", {
|
|
"request": request, "user": user,
|
|
"rows": rows, "total": total,
|
|
"usuarios": [u["username"] for u in usuarios],
|
|
"acciones": [a["accion"] for a in acciones],
|
|
"filtro_username": username, "filtro_accion": accion,
|
|
"filtro_fecha_desde": fecha_desde, "filtro_fecha_hasta": fecha_hasta,
|
|
"offset": offset, "page_size": PAGE_SIZE,
|
|
"has_more": (offset + PAGE_SIZE) < total,
|
|
})
|
|
|
|
|
|
@router.get("/detalle/{envio_id}")
|
|
async def detalle_envio(envio_id: int, request: Request, user: dict = Depends(get_current_user)):
|
|
conn = get_connection()
|
|
row = conn.execute(
|
|
"SELECT e.*, u.username FROM envios e LEFT JOIN users u ON e.user_id = u.id WHERE e.id = ?",
|
|
(envio_id,)
|
|
).fetchone()
|
|
conn.close()
|
|
if not row:
|
|
return JSONResponse({"error": "No encontrado"}, status_code=404)
|
|
return JSONResponse({
|
|
"id": row["id"],
|
|
"tipo": row["tipo"],
|
|
"factura": row["factura"],
|
|
"idrecepcion": row["idrecepcion"],
|
|
"contrato": row["contrato"],
|
|
"status": row["status"],
|
|
"mensaje_tns": row["mensaje_tns"],
|
|
"respuesta_api": row["respuesta_api"],
|
|
"json_enviado": _limpiar_json_enviado(row["json_enviado"]),
|
|
"fecha_inicio": row["fecha_inicio"],
|
|
"fecha_fin": row["fecha_fin"],
|
|
"created_at": row["created_at"],
|
|
"username": row["username"],
|
|
})
|