""" Acceso a datos para la tabla de auditoría. ``registrar`` es *best-effort*: ante cualquier fallo loguea y NUNCA propaga, de modo que la auditoría jamás interrumpe la operación de negocio que la disparó. El push en tiempo real lo maneja Supabase Realtime directamente sobre la tabla. """ from __future__ import annotations import logging from datetime import datetime, timezone from typing import Any from supabase import Client from app.models.auditoria import Auditoria logger = logging.getLogger(__name__) _TABLE = "auditoria" def registrar( db: Client, *, entidad: str, entidad_id: Any, evento: str, cama_id: int | None = None, estado_anterior: str | None = None, estado_nuevo: str | None = None, paciente_id: int | None = None, actor: dict | None = None, origen: str = "API", descripcion: str | None = None, detalle: dict | None = None, hospital_id: str | None = None, ) -> None: try: usuario_id = None rol = "SISTEMA" if actor: raw = actor.get("usuario_id") usuario_id = str(raw) if raw is not None else None rol = actor.get("rol") or "SISTEMA" row = { "entidad": entidad, "entidad_id": str(entidad_id), "cama_id": cama_id, "evento": evento, "estado_anterior": estado_anterior, "estado_nuevo": estado_nuevo, "paciente_id": paciente_id, "usuario_id": usuario_id, "rol": rol, "origen": origen, "descripcion": descripcion, "detalle": detalle, "hospital_id": hospital_id, "creado_en": datetime.now(timezone.utc).isoformat(), } db.table(_TABLE).insert(row).execute() except Exception as e: logger.warning("No se pudo registrar evento de auditoría (%s/%s): %s", entidad, evento, e) def get_all( db: Client, *, cama_id: int | None = None, entidad: str | None = None, entidad_id: str | None = None, paciente_id: int | None = None, evento: str | None = None, rol: str | None = None, usuario_id: str | None = None, hospital_id: str | None = None, fecha_desde: str | None = None, fecha_hasta: str | None = None, limit: int = 100, offset: int = 0, ) -> tuple[list[Auditoria], int]: q = db.table(_TABLE).select("*", count="exact") if cama_id is not None: q = q.eq("cama_id", cama_id) if entidad: q = q.eq("entidad", entidad) if entidad_id: q = q.eq("entidad_id", str(entidad_id)) if paciente_id is not None: q = q.eq("paciente_id", paciente_id) if evento: q = q.eq("evento", evento) if rol: q = q.eq("rol", rol) if usuario_id: q = q.eq("usuario_id", usuario_id) if hospital_id: q = q.eq("hospital_id", hospital_id) if fecha_desde: q = q.gte("creado_en", fecha_desde) if fecha_hasta: q = q.lte("creado_en", fecha_hasta) q = q.order("creado_en", desc=True).range(offset, offset + limit - 1) resp = q.execute() filas = [Auditoria.from_dict(r) for r in (resp.data or [])] total = getattr(resp, "count", None) if total is None: total = len(filas) return filas, total