File size: 3,313 Bytes
f6c0922
 
 
 
 
f564ed8
f6c0922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f564ed8
f6c0922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
"""
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