Mateo Ferreyra commited on
Commit
f6c0922
Β·
1 Parent(s): ee18ee7

Agega ultimoas modificaciones

Browse files
.claude/settings.local.json CHANGED
@@ -18,7 +18,8 @@
18
  "Bash(/tmp/m6venv/bin/pip install *)",
19
  "Bash(pip3 install *)",
20
  "Bash(curl -s -m 20 -o /dev/null -w \"%{http_code}\\\\n\" https://modulo-6-api.hf.space/health)",
21
- "Bash(curl -s -m 20 \"https://modulo-6-api.hf.space/api/v1/auth/token?usuario=ADMINISTRATIVO&password=x\" -w \"\\\\nHTTP %{http_code}\\\\n\")"
 
22
  ]
23
  }
24
  }
 
18
  "Bash(/tmp/m6venv/bin/pip install *)",
19
  "Bash(pip3 install *)",
20
  "Bash(curl -s -m 20 -o /dev/null -w \"%{http_code}\\\\n\" https://modulo-6-api.hf.space/health)",
21
+ "Bash(curl -s -m 20 \"https://modulo-6-api.hf.space/api/v1/auth/token?usuario=ADMINISTRATIVO&password=x\" -w \"\\\\nHTTP %{http_code}\\\\n\")",
22
+ "Bash(grep -iE '\\\\.\\(sql|md\\)$|schema|migration|seed')"
23
  ]
24
  }
25
  }
README.md CHANGED
@@ -60,6 +60,7 @@ La app usa **Supabase** (PostgreSQL). Al arrancar, `create_all` crea las tablas
60
 
61
  ```sql
62
  -- Ejecutar en Supabase SQL Editor
 
63
  DROP TABLE IF EXISTS reservas_quirofano CASCADE;
64
  DROP TABLE IF EXISTS solicitudes CASCADE;
65
  DROP TABLE IF EXISTS camas CASCADE;
@@ -67,6 +68,54 @@ DROP TABLE IF EXISTS camas CASCADE;
67
 
68
  Luego reiniciar el contenedor para que las recree.
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  ---
71
 
72
  ## DocumentaciΓ³n interactiva
 
60
 
61
  ```sql
62
  -- Ejecutar en Supabase SQL Editor
63
+ DROP TABLE IF EXISTS auditoria CASCADE;
64
  DROP TABLE IF EXISTS reservas_quirofano CASCADE;
65
  DROP TABLE IF EXISTS solicitudes CASCADE;
66
  DROP TABLE IF EXISTS camas CASCADE;
 
68
 
69
  Luego reiniciar el contenedor para que las recree.
70
 
71
+ ### Tabla de auditorΓ­a
72
+
73
+ El historial de eventos de camas (solicitudes, asignaciones, traslados, cambios
74
+ de estado, bajas y reservas) se guarda en la tabla `auditoria`. Como `supabase-py`
75
+ no ejecuta DDL, se crea con un script idempotente que se conecta por `psycopg2`:
76
+
77
+ ```bash
78
+ # Requiere DATABASE_URL en el .env (postgresql://USER:PASS@HOST/DB?sslmode=require)
79
+ python scripts/create_auditoria_table.py
80
+ ```
81
+
82
+ Alternativamente, pegar este SQL en el Supabase SQL Editor:
83
+
84
+ ```sql
85
+ CREATE TABLE IF NOT EXISTS auditoria (
86
+ id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
87
+ entidad TEXT NOT NULL, -- CAMA | SOLICITUD | RESERVA_QUIROFANO
88
+ entidad_id TEXT NOT NULL,
89
+ cama_id BIGINT, -- denormalizado: historial por cama
90
+ evento TEXT NOT NULL,
91
+ estado_anterior TEXT,
92
+ estado_nuevo TEXT,
93
+ paciente_id BIGINT,
94
+ usuario_id TEXT,
95
+ rol TEXT, -- ADMINISTRATIVO | MEDICO | LIMPIEZA | SISTEMA
96
+ origen TEXT NOT NULL DEFAULT 'API', -- API | WEBHOOK | SISTEMA
97
+ descripcion TEXT,
98
+ detalle JSONB,
99
+ hospital_id TEXT,
100
+ creado_en TIMESTAMPTZ NOT NULL DEFAULT now()
101
+ );
102
+
103
+ CREATE INDEX IF NOT EXISTS idx_auditoria_cama_id ON auditoria (cama_id);
104
+ CREATE INDEX IF NOT EXISTS idx_auditoria_entidad ON auditoria (entidad, entidad_id);
105
+ CREATE INDEX IF NOT EXISTS idx_auditoria_paciente_id ON auditoria (paciente_id);
106
+ CREATE INDEX IF NOT EXISTS idx_auditoria_creado_en ON auditoria (creado_en DESC);
107
+ CREATE INDEX IF NOT EXISTS idx_auditoria_hospital_id ON auditoria (hospital_id);
108
+ ```
109
+
110
+ Consulta del historial:
111
+
112
+ - `GET /api/v1/auditoria` β€” listado REST con filtros (`cama_id`, `entidad`,
113
+ `paciente_id`, `evento`, `fecha_desde`, `fecha_hasta`, `limit`, `offset`).
114
+ - `WS /api/v1/auditoria/ws?token=<JWT>` β€” envΓ­a un snapshot del historial
115
+ filtrado al conectar y luego empuja cada nuevo evento en tiempo real. Acepta
116
+ los mismos filtros como query params. El JWT va en `token` (el navegador no
117
+ puede setear el header `Authorization` en WebSocket).
118
+
119
  ---
120
 
121
  ## DocumentaciΓ³n interactiva
app/crud/auditoria.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Acceso a datos para la tabla de auditorΓ­a.
3
+
4
+ ``registrar`` es *best-effort*: ante cualquier fallo loguea y NUNCA propaga, de
5
+ modo que la auditorΓ­a jamΓ‘s interrumpe la operaciΓ³n de negocio que la disparΓ³.
6
+ Tras insertar, publica el evento al hub de WebSocket para los clientes en vivo.
7
+ """
8
+ from __future__ import annotations
9
+ import logging
10
+ from datetime import datetime, timezone
11
+ from typing import Any
12
+
13
+ from supabase import Client
14
+
15
+ from app.models.auditoria import Auditoria
16
+ from app.realtime import hub
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ _TABLE = "auditoria"
21
+
22
+
23
+ def registrar(
24
+ db: Client,
25
+ *,
26
+ entidad: str,
27
+ entidad_id: Any,
28
+ evento: str,
29
+ cama_id: int | None = None,
30
+ estado_anterior: str | None = None,
31
+ estado_nuevo: str | None = None,
32
+ paciente_id: int | None = None,
33
+ actor: dict | None = None,
34
+ origen: str = "API",
35
+ descripcion: str | None = None,
36
+ detalle: dict | None = None,
37
+ hospital_id: str | None = None,
38
+ ) -> None:
39
+ try:
40
+ usuario_id = None
41
+ rol = "SISTEMA"
42
+ if actor:
43
+ raw = actor.get("usuario_id")
44
+ usuario_id = str(raw) if raw is not None else None
45
+ rol = actor.get("rol") or "SISTEMA"
46
+
47
+ row = {
48
+ "entidad": entidad,
49
+ "entidad_id": str(entidad_id),
50
+ "cama_id": cama_id,
51
+ "evento": evento,
52
+ "estado_anterior": estado_anterior,
53
+ "estado_nuevo": estado_nuevo,
54
+ "paciente_id": paciente_id,
55
+ "usuario_id": usuario_id,
56
+ "rol": rol,
57
+ "origen": origen,
58
+ "descripcion": descripcion,
59
+ "detalle": detalle,
60
+ "hospital_id": hospital_id,
61
+ "creado_en": datetime.now(timezone.utc).isoformat(),
62
+ }
63
+
64
+ resp = db.table(_TABLE).insert(row).execute()
65
+
66
+ evento_pub = dict(row)
67
+ data = getattr(resp, "data", None)
68
+ if isinstance(data, list) and data and isinstance(data[0], dict) and "id" in data[0]:
69
+ evento_pub["id"] = data[0]["id"]
70
+
71
+ hub.publish(evento_pub)
72
+ except Exception as e:
73
+ logger.warning("No se pudo registrar evento de auditorΓ­a (%s/%s): %s", entidad, evento, e)
74
+
75
+
76
+ def get_all(
77
+ db: Client,
78
+ *,
79
+ cama_id: int | None = None,
80
+ entidad: str | None = None,
81
+ entidad_id: str | None = None,
82
+ paciente_id: int | None = None,
83
+ evento: str | None = None,
84
+ rol: str | None = None,
85
+ usuario_id: str | None = None,
86
+ hospital_id: str | None = None,
87
+ fecha_desde: str | None = None,
88
+ fecha_hasta: str | None = None,
89
+ limit: int = 100,
90
+ offset: int = 0,
91
+ ) -> tuple[list[Auditoria], int]:
92
+ q = db.table(_TABLE).select("*", count="exact")
93
+
94
+ if cama_id is not None:
95
+ q = q.eq("cama_id", cama_id)
96
+ if entidad:
97
+ q = q.eq("entidad", entidad)
98
+ if entidad_id:
99
+ q = q.eq("entidad_id", str(entidad_id))
100
+ if paciente_id is not None:
101
+ q = q.eq("paciente_id", paciente_id)
102
+ if evento:
103
+ q = q.eq("evento", evento)
104
+ if rol:
105
+ q = q.eq("rol", rol)
106
+ if usuario_id:
107
+ q = q.eq("usuario_id", usuario_id)
108
+ if hospital_id:
109
+ q = q.eq("hospital_id", hospital_id)
110
+ if fecha_desde:
111
+ q = q.gte("creado_en", fecha_desde)
112
+ if fecha_hasta:
113
+ q = q.lte("creado_en", fecha_hasta)
114
+
115
+ q = q.order("creado_en", desc=True).range(offset, offset + limit - 1)
116
+ resp = q.execute()
117
+
118
+ filas = [Auditoria.from_dict(r) for r in (resp.data or [])]
119
+ total = getattr(resp, "count", None)
120
+ if total is None:
121
+ total = len(filas)
122
+ return filas, total
app/main.py CHANGED
@@ -3,6 +3,7 @@ Health Grid - MΓ³dulo 6: InternaciΓ³n y GestiΓ³n de Camas
3
  API REST: http://localhost:8006/api/v1
4
  """
5
 
 
6
  import logging
7
  from contextlib import asynccontextmanager
8
  from fastapi import FastAPI, Request, status
@@ -11,8 +12,9 @@ from fastapi.responses import JSONResponse
11
 
12
  from app.config import settings
13
  from app.dependencies import create_access_token
 
14
 
15
- from app.routers import camas, quirofanos, solicitudes, webhooks
16
  from app.routers.webhooks import router_turnos
17
 
18
  logger = logging.getLogger(__name__)
@@ -28,6 +30,9 @@ logging.basicConfig(
28
 
29
  @asynccontextmanager
30
  async def lifespan(app: FastAPI):
 
 
 
31
  logger.info("Conectado a Supabase β€” listo para operar")
32
  yield
33
 
@@ -61,6 +66,7 @@ app.include_router(quirofanos.router, prefix=PREFIX)
61
  app.include_router(solicitudes.router, prefix=PREFIX)
62
  app.include_router(webhooks.router, prefix=PREFIX)
63
  app.include_router(router_turnos, prefix=PREFIX)
 
64
 
65
 
66
  # ─── Endpoint de auth local (mock de M10 β€” solo para desarrollo) ───────────
 
3
  API REST: http://localhost:8006/api/v1
4
  """
5
 
6
+ import asyncio
7
  import logging
8
  from contextlib import asynccontextmanager
9
  from fastapi import FastAPI, Request, status
 
12
 
13
  from app.config import settings
14
  from app.dependencies import create_access_token
15
+ from app.realtime import hub
16
 
17
+ from app.routers import camas, quirofanos, solicitudes, webhooks, auditoria
18
  from app.routers.webhooks import router_turnos
19
 
20
  logger = logging.getLogger(__name__)
 
30
 
31
  @asynccontextmanager
32
  async def lifespan(app: FastAPI):
33
+ # Captura el event loop para que la auditorΓ­a (cΓ³digo sΓ­ncrono) pueda
34
+ # publicar eventos a los clientes WebSocket conectados.
35
+ hub.bind_loop(asyncio.get_running_loop())
36
  logger.info("Conectado a Supabase β€” listo para operar")
37
  yield
38
 
 
66
  app.include_router(solicitudes.router, prefix=PREFIX)
67
  app.include_router(webhooks.router, prefix=PREFIX)
68
  app.include_router(router_turnos, prefix=PREFIX)
69
+ app.include_router(auditoria.router, prefix=PREFIX)
70
 
71
 
72
  # ─── Endpoint de auth local (mock de M10 β€” solo para desarrollo) ───────────
app/models/auditoria.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from datetime import datetime
3
+ from typing import Optional
4
+
5
+
6
+ def _parse_dt(v) -> Optional[datetime]:
7
+ if v is None:
8
+ return None
9
+ if isinstance(v, datetime):
10
+ return v
11
+ return datetime.fromisoformat(str(v))
12
+
13
+
14
+ class Auditoria:
15
+ """Evento de auditorΓ­a sobre una cama / solicitud / reserva de quirΓ³fano."""
16
+
17
+ def __init__(
18
+ self,
19
+ id: Optional[int] = None,
20
+ entidad: str = "",
21
+ entidad_id: str = "",
22
+ cama_id: Optional[int] = None,
23
+ evento: str = "",
24
+ estado_anterior: Optional[str] = None,
25
+ estado_nuevo: Optional[str] = None,
26
+ paciente_id: Optional[int] = None,
27
+ usuario_id: Optional[str] = None,
28
+ rol: Optional[str] = None,
29
+ origen: str = "API",
30
+ descripcion: Optional[str] = None,
31
+ detalle: Optional[dict] = None,
32
+ hospital_id: Optional[str] = None,
33
+ creado_en: Optional[datetime] = None,
34
+ ):
35
+ self.id = id
36
+ self.entidad = entidad
37
+ self.entidad_id = entidad_id
38
+ self.cama_id = cama_id
39
+ self.evento = evento
40
+ self.estado_anterior = estado_anterior
41
+ self.estado_nuevo = estado_nuevo
42
+ self.paciente_id = paciente_id
43
+ self.usuario_id = usuario_id
44
+ self.rol = rol
45
+ self.origen = origen
46
+ self.descripcion = descripcion
47
+ self.detalle = detalle
48
+ self.hospital_id = hospital_id
49
+ self.creado_en = _parse_dt(creado_en)
50
+
51
+ @classmethod
52
+ def from_dict(cls, d: dict) -> "Auditoria":
53
+ return cls(
54
+ id=d.get("id"),
55
+ entidad=d.get("entidad", ""),
56
+ entidad_id=d.get("entidad_id", ""),
57
+ cama_id=d.get("cama_id"),
58
+ evento=d.get("evento", ""),
59
+ estado_anterior=d.get("estado_anterior"),
60
+ estado_nuevo=d.get("estado_nuevo"),
61
+ paciente_id=d.get("paciente_id"),
62
+ usuario_id=d.get("usuario_id"),
63
+ rol=d.get("rol"),
64
+ origen=d.get("origen", "API"),
65
+ descripcion=d.get("descripcion"),
66
+ detalle=d.get("detalle"),
67
+ hospital_id=d.get("hospital_id"),
68
+ creado_en=d.get("creado_en"),
69
+ )
app/realtime.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Broadcast in-process de eventos de auditorΓ­a hacia clientes WebSocket.
3
+
4
+ VΓ‘lido para despliegue de un solo proceso (uvicorn sin ``--workers``, como el
5
+ Dockerfile actual). Si se escala horizontalmente a varios workers/procesos,
6
+ reemplazar este hub por Supabase Realtime o un pub/sub externo (Redis), porque
7
+ cada proceso solo conoce sus propias conexiones.
8
+ """
9
+ from __future__ import annotations
10
+ import asyncio
11
+ import logging
12
+ from typing import Any
13
+
14
+ from fastapi import WebSocket
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ # Campos por los que un cliente puede filtrar su stream en vivo.
20
+ _FILTRABLES = (
21
+ "cama_id", "entidad", "entidad_id", "paciente_id",
22
+ "evento", "rol", "usuario_id", "hospital_id",
23
+ )
24
+
25
+
26
+ def _match(evento: dict[str, Any], filtros: dict[str, Any]) -> bool:
27
+ """True si el evento pasa los filtros del cliente (None = sin filtrar)."""
28
+ for campo in _FILTRABLES:
29
+ esperado = filtros.get(campo)
30
+ if esperado is None:
31
+ continue
32
+ if str(evento.get(campo)) != str(esperado):
33
+ return False
34
+ return True
35
+
36
+
37
+ class AuditoriaHub:
38
+ def __init__(self) -> None:
39
+ self._clients: dict[WebSocket, dict[str, Any]] = {}
40
+ self._loop: asyncio.AbstractEventLoop | None = None
41
+
42
+ def bind_loop(self, loop: asyncio.AbstractEventLoop) -> None:
43
+ """Captura el event loop principal para publicar desde cΓ³digo sΓ­ncrono."""
44
+ self._loop = loop
45
+
46
+ async def connect(self, ws: WebSocket, filtros: dict[str, Any] | None = None) -> None:
47
+ await ws.accept()
48
+ self._clients[ws] = filtros or {}
49
+
50
+ def disconnect(self, ws: WebSocket) -> None:
51
+ self._clients.pop(ws, None)
52
+
53
+ async def _broadcast(self, evento: dict[str, Any]) -> None:
54
+ muertos: list[WebSocket] = []
55
+ for ws, filtros in list(self._clients.items()):
56
+ if not _match(evento, filtros):
57
+ continue
58
+ try:
59
+ await ws.send_json({"tipo": "evento", "evento": evento})
60
+ except Exception:
61
+ muertos.append(ws)
62
+ for ws in muertos:
63
+ self._clients.pop(ws, None)
64
+
65
+ def publish(self, evento: dict[str, Any]) -> None:
66
+ """Encola un broadcast desde contexto sΓ­ncrono. Best-effort: nunca lanza."""
67
+ if self._loop is None or not self._clients:
68
+ return
69
+ try:
70
+ asyncio.run_coroutine_threadsafe(self._broadcast(evento), self._loop)
71
+ except Exception as e:
72
+ logger.warning("No se pudo publicar evento de auditorΓ­a al WS: %s", e)
73
+
74
+
75
+ hub = AuditoriaHub()
app/routers/auditoria.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AuditorΓ­a de camas: historial de eventos.
3
+
4
+ - ``GET /auditoria`` β†’ listado REST con filtros y paginaciΓ³n (fallback).
5
+ - ``WS /auditoria/ws`` β†’ snapshot inicial filtrado + eventos en vivo.
6
+ """
7
+ from datetime import datetime
8
+ from typing import Optional
9
+
10
+ from fastapi import APIRouter, Depends, Query, WebSocket, WebSocketDisconnect
11
+ from supabase import Client
12
+
13
+ from app.dependencies import get_db, require_roles, decode_token
14
+ from app.schemas.auditoria import AuditoriaResponse, AuditoriaListResponse
15
+ from app.schemas.enums import EntidadAuditoriaEnum, TipoEventoAuditoriaEnum
16
+ from app.crud import auditoria as auditoria_crud
17
+ from app.realtime import hub
18
+
19
+ router = APIRouter(prefix="/auditoria", tags=["AuditorΓ­a"])
20
+
21
+ _ROLES_PERMITIDOS = ("ADMINISTRATIVO", "MEDICO")
22
+
23
+
24
+ def _serializar(filas) -> list[dict]:
25
+ return [AuditoriaResponse.model_validate(f).model_dump(mode="json") for f in filas]
26
+
27
+
28
+ @router.get(
29
+ "",
30
+ response_model=AuditoriaListResponse,
31
+ summary="Listar el historial de auditorΓ­a de camas",
32
+ responses={401: {"description": "No autenticado"}, 403: {"description": "Sin permisos"}},
33
+ )
34
+ def get_auditoria(
35
+ cama_id: Optional[int] = Query(None),
36
+ entidad: Optional[EntidadAuditoriaEnum] = Query(None),
37
+ entidad_id: Optional[str] = Query(None),
38
+ paciente_id: Optional[int] = Query(None),
39
+ evento: Optional[TipoEventoAuditoriaEnum] = Query(None),
40
+ rol: Optional[str] = Query(None),
41
+ usuario_id: Optional[str] = Query(None),
42
+ hospital_id: Optional[str] = Query(None),
43
+ fecha_desde: Optional[datetime] = Query(None),
44
+ fecha_hasta: Optional[datetime] = Query(None),
45
+ limit: int = Query(100, ge=1, le=500),
46
+ offset: int = Query(0, ge=0),
47
+ db: Client = Depends(get_db),
48
+ user: dict = Depends(require_roles(*_ROLES_PERMITIDOS)),
49
+ ):
50
+ filas, total = auditoria_crud.get_all(
51
+ db,
52
+ cama_id=cama_id,
53
+ entidad=entidad.value if entidad else None,
54
+ entidad_id=entidad_id,
55
+ paciente_id=paciente_id,
56
+ evento=evento.value if evento else None,
57
+ rol=rol,
58
+ usuario_id=usuario_id,
59
+ hospital_id=hospital_id,
60
+ fecha_desde=fecha_desde.isoformat() if fecha_desde else None,
61
+ fecha_hasta=fecha_hasta.isoformat() if fecha_hasta else None,
62
+ limit=limit,
63
+ offset=offset,
64
+ )
65
+ return AuditoriaListResponse(
66
+ total=total,
67
+ eventos=[AuditoriaResponse.model_validate(f) for f in filas],
68
+ )
69
+
70
+
71
+ @router.websocket("/ws")
72
+ async def auditoria_ws(
73
+ websocket: WebSocket,
74
+ token: Optional[str] = Query(None),
75
+ cama_id: Optional[int] = Query(None),
76
+ entidad: Optional[str] = Query(None),
77
+ entidad_id: Optional[str] = Query(None),
78
+ paciente_id: Optional[int] = Query(None),
79
+ evento: Optional[str] = Query(None),
80
+ hospital_id: Optional[str] = Query(None),
81
+ limit: int = Query(100, ge=1, le=500),
82
+ db: Client = Depends(get_db),
83
+ ):
84
+ """
85
+ El JWT se pasa como query param ``token`` (el navegador no puede setear el
86
+ header Authorization en WebSocket). Al conectar envΓ­a un snapshot del
87
+ historial filtrado y luego empuja cada nuevo evento que coincida.
88
+ """
89
+ user = _autenticar(token)
90
+ if user is None or user.get("rol") not in _ROLES_PERMITIDOS:
91
+ await websocket.close(code=4401) # Unauthorized
92
+ return
93
+
94
+ filtros = {
95
+ "cama_id": cama_id,
96
+ "entidad": entidad,
97
+ "entidad_id": entidad_id,
98
+ "paciente_id": paciente_id,
99
+ "evento": evento,
100
+ "hospital_id": hospital_id,
101
+ }
102
+ await hub.connect(websocket, filtros)
103
+ try:
104
+ filas, total = auditoria_crud.get_all(
105
+ db,
106
+ cama_id=cama_id,
107
+ entidad=entidad,
108
+ entidad_id=entidad_id,
109
+ paciente_id=paciente_id,
110
+ evento=evento,
111
+ hospital_id=hospital_id,
112
+ limit=limit,
113
+ )
114
+ await websocket.send_json(
115
+ {"tipo": "snapshot", "total": total, "eventos": _serializar(filas)}
116
+ )
117
+ # Mantener viva la conexiΓ³n; los eventos en vivo los empuja el hub.
118
+ while True:
119
+ await websocket.receive_text()
120
+ except WebSocketDisconnect:
121
+ pass
122
+ except Exception:
123
+ pass
124
+ finally:
125
+ hub.disconnect(websocket)
126
+
127
+
128
+ def _autenticar(token: Optional[str]) -> Optional[dict]:
129
+ if not token:
130
+ return None
131
+ try:
132
+ payload = decode_token(token)
133
+ except ValueError:
134
+ return None
135
+ if "sub" not in payload or "rol" not in payload:
136
+ return None
137
+ return payload
app/routers/camas.py CHANGED
@@ -59,7 +59,7 @@ def crear_cama(
59
  db: Client = Depends(get_db),
60
  user: dict = Depends(require_roles("ADMINISTRATIVO")),
61
  ):
62
- cama = cama_service.create_cama(db, data)
63
  return CamaResponse.model_validate(cama)
64
 
65
 
@@ -90,7 +90,9 @@ def update_cama(
90
  db: Client = Depends(get_db),
91
  user: dict = Depends(require_roles("ADMINISTRATIVO", "LIMPIEZA")),
92
  ):
93
- cama = cama_service.update_cama(db, cama_id, data, user["rol"])
 
 
94
  return CamaResponse.model_validate(cama)
95
 
96
 
@@ -105,7 +107,7 @@ def delete_cama(
105
  db: Client = Depends(get_db),
106
  user: dict = Depends(require_roles("ADMINISTRATIVO")),
107
  ):
108
- cama = cama_service.delete_cama(db, cama_id)
109
  return CamaResponse.model_validate(cama)
110
 
111
 
@@ -123,7 +125,10 @@ def asignar_cama(
123
  db: Client = Depends(get_db),
124
  user: dict = Depends(require_roles("ADMINISTRATIVO")),
125
  ):
126
- cama = cama_service.asignar_cama(db, cama_id, data.tipo, data.paciente_id, data.cama_origen_id)
 
 
 
127
  return AsignacionCamaResponse(
128
  mensaje=f"Paciente {data.paciente_id} asignado a la cama {cama_id}",
129
  cama_id=cama.id,
 
59
  db: Client = Depends(get_db),
60
  user: dict = Depends(require_roles("ADMINISTRATIVO")),
61
  ):
62
+ cama = cama_service.create_cama(db, data, actor={"usuario_id": user["sub"], "rol": user["rol"]})
63
  return CamaResponse.model_validate(cama)
64
 
65
 
 
90
  db: Client = Depends(get_db),
91
  user: dict = Depends(require_roles("ADMINISTRATIVO", "LIMPIEZA")),
92
  ):
93
+ cama = cama_service.update_cama(
94
+ db, cama_id, data, user["rol"], actor={"usuario_id": user["sub"], "rol": user["rol"]}
95
+ )
96
  return CamaResponse.model_validate(cama)
97
 
98
 
 
107
  db: Client = Depends(get_db),
108
  user: dict = Depends(require_roles("ADMINISTRATIVO")),
109
  ):
110
+ cama = cama_service.delete_cama(db, cama_id, actor={"usuario_id": user["sub"], "rol": user["rol"]})
111
  return CamaResponse.model_validate(cama)
112
 
113
 
 
125
  db: Client = Depends(get_db),
126
  user: dict = Depends(require_roles("ADMINISTRATIVO")),
127
  ):
128
+ cama = cama_service.asignar_cama(
129
+ db, cama_id, data.tipo, data.paciente_id, data.cama_origen_id,
130
+ actor={"usuario_id": user["sub"], "rol": user["rol"]},
131
+ )
132
  return AsignacionCamaResponse(
133
  mensaje=f"Paciente {data.paciente_id} asignado a la cama {cama_id}",
134
  cama_id=cama.id,
app/routers/quirofanos.py CHANGED
@@ -93,7 +93,9 @@ def crear_quirofano(
93
  db: Client = Depends(get_db),
94
  user: dict = Depends(require_roles("ADMINISTRATIVO")),
95
  ):
96
- quirofano = cama_service.create_quirofano(db, data)
 
 
97
  return QuirofanoResponse.model_validate(quirofano)
98
 
99
 
@@ -124,7 +126,9 @@ def update_quirofano(
124
  db: Client = Depends(get_db),
125
  user: dict = Depends(require_roles("ADMINISTRATIVO")),
126
  ):
127
- quirofano = cama_service.update_quirofano(db, quirofano_id, data)
 
 
128
  return QuirofanoResponse.model_validate(quirofano)
129
 
130
 
@@ -168,7 +172,9 @@ def crear_reserva(
168
  db: Client = Depends(get_db),
169
  user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
170
  ):
171
- reserva, created = cama_service.create_reserva(db, quirofano_id, data)
 
 
172
  resp = ReservaQuirofanoResponse.model_validate(reserva)
173
  http_status = status.HTTP_201_CREATED if created else status.HTTP_200_OK
174
  return JSONResponse(content=resp.model_dump(mode="json"), status_code=http_status)
@@ -203,5 +209,7 @@ def update_reserva(
203
  db: Client = Depends(get_db),
204
  user: dict = Depends(require_roles("ADMINISTRATIVO")),
205
  ):
206
- reserva = cama_service.update_reserva_estado(db, quirofano_id, reserva_id, data)
 
 
207
  return ReservaQuirofanoResponse.model_validate(reserva)
 
93
  db: Client = Depends(get_db),
94
  user: dict = Depends(require_roles("ADMINISTRATIVO")),
95
  ):
96
+ quirofano = cama_service.create_quirofano(
97
+ db, data, actor={"usuario_id": user["sub"], "rol": user["rol"]}
98
+ )
99
  return QuirofanoResponse.model_validate(quirofano)
100
 
101
 
 
126
  db: Client = Depends(get_db),
127
  user: dict = Depends(require_roles("ADMINISTRATIVO")),
128
  ):
129
+ quirofano = cama_service.update_quirofano(
130
+ db, quirofano_id, data, actor={"usuario_id": user["sub"], "rol": user["rol"]}
131
+ )
132
  return QuirofanoResponse.model_validate(quirofano)
133
 
134
 
 
172
  db: Client = Depends(get_db),
173
  user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
174
  ):
175
+ reserva, created = cama_service.create_reserva(
176
+ db, quirofano_id, data, actor={"usuario_id": user["sub"], "rol": user["rol"]}
177
+ )
178
  resp = ReservaQuirofanoResponse.model_validate(reserva)
179
  http_status = status.HTTP_201_CREATED if created else status.HTTP_200_OK
180
  return JSONResponse(content=resp.model_dump(mode="json"), status_code=http_status)
 
209
  db: Client = Depends(get_db),
210
  user: dict = Depends(require_roles("ADMINISTRATIVO")),
211
  ):
212
+ reserva = cama_service.update_reserva_estado(
213
+ db, quirofano_id, reserva_id, data, actor={"usuario_id": user["sub"], "rol": user["rol"]}
214
+ )
215
  return ReservaQuirofanoResponse.model_validate(reserva)
app/routers/solicitudes.py CHANGED
@@ -71,6 +71,7 @@ def resolver_solicitud(
71
  user: dict = Depends(require_roles("ADMINISTRATIVO")),
72
  ):
73
  sol = solicitud_service.resolver_solicitud(
74
- db, solicitud_id, data, resuelto_por=int(user["sub"])
 
75
  )
76
  return SolicitudResponse.model_validate({**sol.__dict__, "id": sol.solicitud_id})
 
71
  user: dict = Depends(require_roles("ADMINISTRATIVO")),
72
  ):
73
  sol = solicitud_service.resolver_solicitud(
74
+ db, solicitud_id, data, resuelto_por=int(user["sub"]),
75
+ actor={"usuario_id": user["sub"], "rol": user["rol"]},
76
  )
77
  return SolicitudResponse.model_validate({**sol.__dict__, "id": sol.solicitud_id})
app/schemas/auditoria.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from datetime import datetime
3
+ from typing import Optional
4
+ from pydantic import BaseModel, ConfigDict
5
+
6
+ from app.schemas.enums import EntidadAuditoriaEnum, OrigenAuditoriaEnum, TipoEventoAuditoriaEnum
7
+
8
+
9
+ class AuditoriaResponse(BaseModel):
10
+ model_config = ConfigDict(from_attributes=True)
11
+
12
+ id: Optional[int] = None
13
+ entidad: EntidadAuditoriaEnum
14
+ entidad_id: str
15
+ cama_id: Optional[int] = None
16
+ evento: TipoEventoAuditoriaEnum
17
+ estado_anterior: Optional[str] = None
18
+ estado_nuevo: Optional[str] = None
19
+ paciente_id: Optional[int] = None
20
+ usuario_id: Optional[str] = None
21
+ rol: Optional[str] = None
22
+ origen: OrigenAuditoriaEnum
23
+ descripcion: Optional[str] = None
24
+ detalle: Optional[dict] = None
25
+ hospital_id: Optional[str] = None
26
+ creado_en: datetime
27
+
28
+
29
+ class AuditoriaListResponse(BaseModel):
30
+ total: int
31
+ eventos: list[AuditoriaResponse]
app/schemas/enums.py CHANGED
@@ -89,3 +89,34 @@ class RolEnum(str, Enum):
89
  MEDICO = "MEDICO"
90
  ADMINISTRATIVO = "ADMINISTRATIVO"
91
  LIMPIEZA = "LIMPIEZA"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  MEDICO = "MEDICO"
90
  ADMINISTRATIVO = "ADMINISTRATIVO"
91
  LIMPIEZA = "LIMPIEZA"
92
+
93
+
94
+ class EntidadAuditoriaEnum(str, Enum):
95
+ CAMA = "CAMA"
96
+ SOLICITUD = "SOLICITUD"
97
+ RESERVA_QUIROFANO = "RESERVA_QUIROFANO"
98
+
99
+
100
+ class OrigenAuditoriaEnum(str, Enum):
101
+ API = "API"
102
+ WEBHOOK = "WEBHOOK"
103
+ SISTEMA = "SISTEMA"
104
+
105
+
106
+ class TipoEventoAuditoriaEnum(str, Enum):
107
+ SOLICITUD_RECIBIDA = "SOLICITUD_RECIBIDA"
108
+ SOLICITUD_APROBADA = "SOLICITUD_APROBADA"
109
+ SOLICITUD_RECHAZADA = "SOLICITUD_RECHAZADA"
110
+ CAMA_CREADA = "CAMA_CREADA"
111
+ CAMA_ASIGNADA = "CAMA_ASIGNADA"
112
+ CAMA_TRASLADO = "CAMA_TRASLADO"
113
+ CAMA_CAMBIO_ESTADO = "CAMA_CAMBIO_ESTADO"
114
+ CAMA_ALTA = "CAMA_ALTA"
115
+ CAMA_CODIGO_ROJO = "CAMA_CODIGO_ROJO"
116
+ CAMA_ALERTA_RESUELTA = "CAMA_ALERTA_RESUELTA"
117
+ CAMA_BAJA = "CAMA_BAJA"
118
+ RESERVA_CREADA = "RESERVA_CREADA"
119
+ RESERVA_CAMBIO_ESTADO = "RESERVA_CAMBIO_ESTADO"
120
+ RESERVA_URGENTE = "RESERVA_URGENTE"
121
+ RESERVA_DESPLAZADA = "RESERVA_DESPLAZADA"
122
+ RESERVA_CANCELADA = "RESERVA_CANCELADA"
app/services/cama_service.py CHANGED
@@ -22,7 +22,9 @@ from app.schemas.reserva import (
22
  from app.schemas.enums import EstadoCamaEnum, EstadoReservaEnum, SectorEnum, TipoCamaEnum
23
  from app.crud import cama as cama_crud
24
  from app.crud import reserva as reserva_crud
 
25
  from app.integrations import hce, monitoreo, facturacion, turnos
 
26
 
27
 
28
  # ─── Constantes de dominio ─────────────────────────────────────────────────
@@ -75,16 +77,31 @@ def get_camas(
75
  return cama_crud.get_all(db, rol, piso, sector, estado, hospital_id)
76
 
77
 
78
- def create_cama(db: Client, data: CamaCreateRequest) -> Cama:
79
- return cama_crud.create(db, data)
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
 
82
  def get_cama(db: Client, cama_id: int) -> Cama:
83
  return _get_cama_or_404(db, cama_id)
84
 
85
 
86
- def update_cama(db: Client, cama_id: int, data: CamaUpdateRequest, rol: str) -> Cama:
 
 
87
  cama = _get_cama_or_404(db, cama_id)
 
88
 
89
  if data.estado is not None:
90
  nuevo_estado = data.estado.value
@@ -132,10 +149,26 @@ def update_cama(db: Client, cama_id: int, data: CamaUpdateRequest, rol: str) ->
132
  cama.contraindicaciones_incompatibles = data.contraindicaciones_incompatibles
133
 
134
  cama.ultima_actualizacion = datetime.now(timezone.utc)
135
- return cama_crud.save(db, cama)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
 
138
- def delete_cama(db: Client, cama_id: int) -> Cama:
139
  cama = _get_cama_or_404(db, cama_id)
140
  if cama.estado in (
141
  EstadoCamaEnum.OCUPADA.value,
@@ -155,12 +188,29 @@ def delete_cama(db: Client, cama_id: int) -> Cama:
155
  status_code=409,
156
  detail={"codigo": "CONFLICTO_ESTADO", "mensaje": "La cama ya estΓ‘ dada de baja"},
157
  )
 
158
  cama.estado = EstadoCamaEnum.BAJA_PERMANENTE.value
159
  cama.ultima_actualizacion = datetime.now(timezone.utc)
160
- return cama_crud.save(db, cama)
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
 
163
- def asignar_cama(db: Client, cama_id: int, tipo: str, paciente_id: int, cama_origen_id: int | None) -> Cama:
 
 
 
164
  cama_destino = _get_cama_or_404(db, cama_id)
165
 
166
  if cama_destino.estado != EstadoCamaEnum.DISPONIBLE.value:
@@ -196,7 +246,31 @@ def asignar_cama(db: Client, cama_id: int, tipo: str, paciente_id: int, cama_ori
196
  cama_destino.estado = EstadoCamaEnum.OCUPADA.value
197
  cama_destino.paciente_id = paciente_id
198
  cama_destino.ultima_actualizacion = datetime.now(timezone.utc)
199
- return cama_crud.save(db, cama_destino)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
201
 
202
  # ─── QuirΓ³fanos (entidad) ──────────────────────────────────────────────────
@@ -226,7 +300,7 @@ def get_quirofanos_list(
226
  )
227
 
228
 
229
- def create_quirofano(db: Client, data: QuirofanoCreateRequest) -> Cama:
230
  cama_req = CamaCreateRequest(
231
  numero=data.numero,
232
  piso=data.piso,
@@ -236,7 +310,19 @@ def create_quirofano(db: Client, data: QuirofanoCreateRequest) -> Cama:
236
  hospital_id=data.hospital_id,
237
  contraindicaciones_incompatibles=data.contraindicaciones_incompatibles,
238
  )
239
- return cama_crud.create(db, cama_req)
 
 
 
 
 
 
 
 
 
 
 
 
240
 
241
 
242
  def get_quirofano(db: Client, quirofano_id: int) -> Cama:
@@ -244,9 +330,10 @@ def get_quirofano(db: Client, quirofano_id: int) -> Cama:
244
 
245
 
246
  def update_quirofano(
247
- db: Client, quirofano_id: int, data: QuirofanoUpdateRequest
248
  ) -> Cama:
249
  cama = _get_quirofano_or_404(db, quirofano_id)
 
250
 
251
  if data.estado is not None:
252
  nuevo_estado = data.estado.value
@@ -273,7 +360,22 @@ def update_quirofano(
273
  cama.contraindicaciones_incompatibles = data.contraindicaciones_incompatibles
274
 
275
  cama.ultima_actualizacion = datetime.now(timezone.utc)
276
- return cama_crud.save(db, cama)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
 
278
 
279
  # ─── Reservas de QuirΓ³fano ─────────────────────────────────────────────────
@@ -296,7 +398,7 @@ def get_reservas(
296
 
297
 
298
  def create_reserva(
299
- db: Client, cama_id: int, data: ReservaQuirofanoCreateRequest
300
  ) -> tuple[ReservaQuirofano, bool]:
301
  """Retorna (reserva, created). created=False si ya existΓ­a (idempotencia)."""
302
  cama = _get_cama_or_404(db, cama_id)
@@ -333,7 +435,21 @@ def create_reserva(
333
  },
334
  )
335
 
336
- return reserva_crud.create_programada(db, cama_id, data), True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
 
338
 
339
  def get_reserva(db: Client, cama_id: int, reserva_id: int) -> ReservaQuirofano:
@@ -345,10 +461,13 @@ def get_reserva(db: Client, cama_id: int, reserva_id: int) -> ReservaQuirofano:
345
 
346
 
347
  def update_reserva_estado(
348
- db: Client, cama_id: int, reserva_id: int, data: ReservaEstadoUpdateRequest
 
349
  ) -> ReservaQuirofano:
350
  reserva = get_reserva(db, cama_id, reserva_id)
351
  cama = _get_cama_or_404(db, cama_id)
 
 
352
 
353
  TRANSICIONES_VALIDAS = {
354
  EstadoReservaEnum.RESERVADA.value: [EstadoReservaEnum.EN_CURSO.value, EstadoReservaEnum.CANCELADA.value],
@@ -378,7 +497,36 @@ def update_reserva_estado(
378
 
379
  cama.ultima_actualizacion = datetime.now(timezone.utc)
380
  cama_crud.save(db, cama)
381
- return reserva_crud.save(db, reserva)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
382
 
383
 
384
  def get_disponibilidad_quirofanos(
@@ -431,6 +579,18 @@ def crear_reserva_urgente(
431
 
432
  if cama_libre:
433
  reserva = reserva_crud.create_urgente(db, cama_libre.id, data)
 
 
 
 
 
 
 
 
 
 
 
 
434
  return reserva, None
435
 
436
  candidata = _find_desplazable(db, quirofanos, data.fecha_hora_inicio, data.fecha_hora_fin_estimada)
@@ -464,6 +624,30 @@ def crear_reserva_urgente(
464
  candidata.desplazada_por_reserva_id = reserva_urgente.id
465
  reserva_crud.save(db, candidata)
466
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
  return reserva_urgente, candidata
468
 
469
 
 
22
  from app.schemas.enums import EstadoCamaEnum, EstadoReservaEnum, SectorEnum, TipoCamaEnum
23
  from app.crud import cama as cama_crud
24
  from app.crud import reserva as reserva_crud
25
+ from app.crud import auditoria as auditoria_crud
26
  from app.integrations import hce, monitoreo, facturacion, turnos
27
+ from app.schemas.enums import EntidadAuditoriaEnum, TipoEventoAuditoriaEnum, OrigenAuditoriaEnum
28
 
29
 
30
  # ─── Constantes de dominio ─────────────────────────────────────────────────
 
77
  return cama_crud.get_all(db, rol, piso, sector, estado, hospital_id)
78
 
79
 
80
+ def create_cama(db: Client, data: CamaCreateRequest, actor: dict | None = None) -> Cama:
81
+ cama = cama_crud.create(db, data)
82
+ auditoria_crud.registrar(
83
+ db,
84
+ entidad=EntidadAuditoriaEnum.CAMA.value,
85
+ entidad_id=cama.id,
86
+ cama_id=cama.id,
87
+ evento=TipoEventoAuditoriaEnum.CAMA_CREADA.value,
88
+ estado_nuevo=cama.estado,
89
+ actor=actor,
90
+ descripcion=f"Cama {cama.numero} creada en {cama.sector}",
91
+ hospital_id=cama.hospital_id,
92
+ )
93
+ return cama
94
 
95
 
96
  def get_cama(db: Client, cama_id: int) -> Cama:
97
  return _get_cama_or_404(db, cama_id)
98
 
99
 
100
+ def update_cama(
101
+ db: Client, cama_id: int, data: CamaUpdateRequest, rol: str, actor: dict | None = None
102
+ ) -> Cama:
103
  cama = _get_cama_or_404(db, cama_id)
104
+ estado_previo = cama.estado
105
 
106
  if data.estado is not None:
107
  nuevo_estado = data.estado.value
 
149
  cama.contraindicaciones_incompatibles = data.contraindicaciones_incompatibles
150
 
151
  cama.ultima_actualizacion = datetime.now(timezone.utc)
152
+ cama = cama_crud.save(db, cama)
153
+
154
+ if data.estado is not None and cama.estado != estado_previo:
155
+ auditoria_crud.registrar(
156
+ db,
157
+ entidad=EntidadAuditoriaEnum.CAMA.value,
158
+ entidad_id=cama.id,
159
+ cama_id=cama.id,
160
+ evento=TipoEventoAuditoriaEnum.CAMA_CAMBIO_ESTADO.value,
161
+ estado_anterior=estado_previo,
162
+ estado_nuevo=cama.estado,
163
+ paciente_id=cama.paciente_id,
164
+ actor=actor,
165
+ descripcion=f"Cama {cama.numero}: {estado_previo} β†’ {cama.estado}",
166
+ hospital_id=cama.hospital_id,
167
+ )
168
+ return cama
169
 
170
 
171
+ def delete_cama(db: Client, cama_id: int, actor: dict | None = None) -> Cama:
172
  cama = _get_cama_or_404(db, cama_id)
173
  if cama.estado in (
174
  EstadoCamaEnum.OCUPADA.value,
 
188
  status_code=409,
189
  detail={"codigo": "CONFLICTO_ESTADO", "mensaje": "La cama ya estΓ‘ dada de baja"},
190
  )
191
+ estado_previo = cama.estado
192
  cama.estado = EstadoCamaEnum.BAJA_PERMANENTE.value
193
  cama.ultima_actualizacion = datetime.now(timezone.utc)
194
+ cama = cama_crud.save(db, cama)
195
+ auditoria_crud.registrar(
196
+ db,
197
+ entidad=EntidadAuditoriaEnum.CAMA.value,
198
+ entidad_id=cama.id,
199
+ cama_id=cama.id,
200
+ evento=TipoEventoAuditoriaEnum.CAMA_BAJA.value,
201
+ estado_anterior=estado_previo,
202
+ estado_nuevo=cama.estado,
203
+ actor=actor,
204
+ descripcion=f"Baja permanente de la cama {cama.numero}",
205
+ hospital_id=cama.hospital_id,
206
+ )
207
+ return cama
208
 
209
 
210
+ def asignar_cama(
211
+ db: Client, cama_id: int, tipo: str, paciente_id: int, cama_origen_id: int | None,
212
+ actor: dict | None = None,
213
+ ) -> Cama:
214
  cama_destino = _get_cama_or_404(db, cama_id)
215
 
216
  if cama_destino.estado != EstadoCamaEnum.DISPONIBLE.value:
 
246
  cama_destino.estado = EstadoCamaEnum.OCUPADA.value
247
  cama_destino.paciente_id = paciente_id
248
  cama_destino.ultima_actualizacion = datetime.now(timezone.utc)
249
+ cama_destino = cama_crud.save(db, cama_destino)
250
+
251
+ es_traslado = tipo == "TRASLADO"
252
+ auditoria_crud.registrar(
253
+ db,
254
+ entidad=EntidadAuditoriaEnum.CAMA.value,
255
+ entidad_id=cama_destino.id,
256
+ cama_id=cama_destino.id,
257
+ evento=(
258
+ TipoEventoAuditoriaEnum.CAMA_TRASLADO.value
259
+ if es_traslado
260
+ else TipoEventoAuditoriaEnum.CAMA_ASIGNADA.value
261
+ ),
262
+ estado_nuevo=cama_destino.estado,
263
+ paciente_id=paciente_id,
264
+ actor=actor,
265
+ descripcion=(
266
+ f"Traslado del paciente {paciente_id} a la cama {cama_destino.numero}"
267
+ if es_traslado
268
+ else f"Ingreso del paciente {paciente_id} a la cama {cama_destino.numero}"
269
+ ),
270
+ detalle={"tipo": tipo, "cama_origen_id": cama_origen_id} if es_traslado else {"tipo": tipo},
271
+ hospital_id=cama_destino.hospital_id,
272
+ )
273
+ return cama_destino
274
 
275
 
276
  # ─── QuirΓ³fanos (entidad) ──────────────────────────────────────────────────
 
300
  )
301
 
302
 
303
+ def create_quirofano(db: Client, data: QuirofanoCreateRequest, actor: dict | None = None) -> Cama:
304
  cama_req = CamaCreateRequest(
305
  numero=data.numero,
306
  piso=data.piso,
 
310
  hospital_id=data.hospital_id,
311
  contraindicaciones_incompatibles=data.contraindicaciones_incompatibles,
312
  )
313
+ cama = cama_crud.create(db, cama_req)
314
+ auditoria_crud.registrar(
315
+ db,
316
+ entidad=EntidadAuditoriaEnum.CAMA.value,
317
+ entidad_id=cama.id,
318
+ cama_id=cama.id,
319
+ evento=TipoEventoAuditoriaEnum.CAMA_CREADA.value,
320
+ estado_nuevo=cama.estado,
321
+ actor=actor,
322
+ descripcion=f"QuirΓ³fano {cama.numero} creado",
323
+ hospital_id=cama.hospital_id,
324
+ )
325
+ return cama
326
 
327
 
328
  def get_quirofano(db: Client, quirofano_id: int) -> Cama:
 
330
 
331
 
332
  def update_quirofano(
333
+ db: Client, quirofano_id: int, data: QuirofanoUpdateRequest, actor: dict | None = None
334
  ) -> Cama:
335
  cama = _get_quirofano_or_404(db, quirofano_id)
336
+ estado_previo = cama.estado
337
 
338
  if data.estado is not None:
339
  nuevo_estado = data.estado.value
 
360
  cama.contraindicaciones_incompatibles = data.contraindicaciones_incompatibles
361
 
362
  cama.ultima_actualizacion = datetime.now(timezone.utc)
363
+ cama = cama_crud.save(db, cama)
364
+
365
+ if data.estado is not None and cama.estado != estado_previo:
366
+ auditoria_crud.registrar(
367
+ db,
368
+ entidad=EntidadAuditoriaEnum.CAMA.value,
369
+ entidad_id=cama.id,
370
+ cama_id=cama.id,
371
+ evento=TipoEventoAuditoriaEnum.CAMA_CAMBIO_ESTADO.value,
372
+ estado_anterior=estado_previo,
373
+ estado_nuevo=cama.estado,
374
+ actor=actor,
375
+ descripcion=f"QuirΓ³fano {cama.numero}: {estado_previo} β†’ {cama.estado}",
376
+ hospital_id=cama.hospital_id,
377
+ )
378
+ return cama
379
 
380
 
381
  # ─── Reservas de QuirΓ³fano ─────────────────────────────────────────────────
 
398
 
399
 
400
  def create_reserva(
401
+ db: Client, cama_id: int, data: ReservaQuirofanoCreateRequest, actor: dict | None = None
402
  ) -> tuple[ReservaQuirofano, bool]:
403
  """Retorna (reserva, created). created=False si ya existΓ­a (idempotencia)."""
404
  cama = _get_cama_or_404(db, cama_id)
 
435
  },
436
  )
437
 
438
+ reserva = reserva_crud.create_programada(db, cama_id, data)
439
+ auditoria_crud.registrar(
440
+ db,
441
+ entidad=EntidadAuditoriaEnum.RESERVA_QUIROFANO.value,
442
+ entidad_id=reserva.id,
443
+ cama_id=cama_id,
444
+ evento=TipoEventoAuditoriaEnum.RESERVA_CREADA.value,
445
+ estado_nuevo=reserva.estado,
446
+ paciente_id=reserva.paciente_id,
447
+ actor=actor,
448
+ descripcion=f"Reserva programada en quirΓ³fano {cama_id}",
449
+ detalle={"turno_id": reserva.turno_id, "prioridad": reserva.prioridad},
450
+ hospital_id=cama.hospital_id,
451
+ )
452
+ return reserva, True
453
 
454
 
455
  def get_reserva(db: Client, cama_id: int, reserva_id: int) -> ReservaQuirofano:
 
461
 
462
 
463
  def update_reserva_estado(
464
+ db: Client, cama_id: int, reserva_id: int, data: ReservaEstadoUpdateRequest,
465
+ actor: dict | None = None,
466
  ) -> ReservaQuirofano:
467
  reserva = get_reserva(db, cama_id, reserva_id)
468
  cama = _get_cama_or_404(db, cama_id)
469
+ reserva_estado_previo = reserva.estado
470
+ cama_estado_previo = cama.estado
471
 
472
  TRANSICIONES_VALIDAS = {
473
  EstadoReservaEnum.RESERVADA.value: [EstadoReservaEnum.EN_CURSO.value, EstadoReservaEnum.CANCELADA.value],
 
497
 
498
  cama.ultima_actualizacion = datetime.now(timezone.utc)
499
  cama_crud.save(db, cama)
500
+ reserva = reserva_crud.save(db, reserva)
501
+
502
+ auditoria_crud.registrar(
503
+ db,
504
+ entidad=EntidadAuditoriaEnum.RESERVA_QUIROFANO.value,
505
+ entidad_id=reserva.id,
506
+ cama_id=cama_id,
507
+ evento=TipoEventoAuditoriaEnum.RESERVA_CAMBIO_ESTADO.value,
508
+ estado_anterior=reserva_estado_previo,
509
+ estado_nuevo=reserva.estado,
510
+ paciente_id=reserva.paciente_id,
511
+ actor=actor,
512
+ descripcion=f"Reserva {reserva.id}: {reserva_estado_previo} β†’ {reserva.estado}",
513
+ hospital_id=cama.hospital_id,
514
+ )
515
+ if cama.estado != cama_estado_previo:
516
+ auditoria_crud.registrar(
517
+ db,
518
+ entidad=EntidadAuditoriaEnum.CAMA.value,
519
+ entidad_id=cama.id,
520
+ cama_id=cama.id,
521
+ evento=TipoEventoAuditoriaEnum.CAMA_CAMBIO_ESTADO.value,
522
+ estado_anterior=cama_estado_previo,
523
+ estado_nuevo=cama.estado,
524
+ paciente_id=cama.paciente_id,
525
+ actor=actor,
526
+ descripcion=f"Cama {cama.numero}: {cama_estado_previo} β†’ {cama.estado} (reserva {reserva.id})",
527
+ hospital_id=cama.hospital_id,
528
+ )
529
+ return reserva
530
 
531
 
532
  def get_disponibilidad_quirofanos(
 
579
 
580
  if cama_libre:
581
  reserva = reserva_crud.create_urgente(db, cama_libre.id, data)
582
+ auditoria_crud.registrar(
583
+ db,
584
+ entidad=EntidadAuditoriaEnum.RESERVA_QUIROFANO.value,
585
+ entidad_id=reserva.id,
586
+ cama_id=cama_libre.id,
587
+ evento=TipoEventoAuditoriaEnum.RESERVA_URGENTE.value,
588
+ estado_nuevo=reserva.estado,
589
+ paciente_id=reserva.paciente_id,
590
+ origen=OrigenAuditoriaEnum.WEBHOOK.value,
591
+ descripcion=f"Reserva urgente creada en quirΓ³fano {cama_libre.id}",
592
+ hospital_id=cama_libre.hospital_id,
593
+ )
594
  return reserva, None
595
 
596
  candidata = _find_desplazable(db, quirofanos, data.fecha_hora_inicio, data.fecha_hora_fin_estimada)
 
624
  candidata.desplazada_por_reserva_id = reserva_urgente.id
625
  reserva_crud.save(db, candidata)
626
 
627
+ auditoria_crud.registrar(
628
+ db,
629
+ entidad=EntidadAuditoriaEnum.RESERVA_QUIROFANO.value,
630
+ entidad_id=reserva_urgente.id,
631
+ cama_id=candidata_cama_id,
632
+ evento=TipoEventoAuditoriaEnum.RESERVA_URGENTE.value,
633
+ estado_nuevo=reserva_urgente.estado,
634
+ paciente_id=reserva_urgente.paciente_id,
635
+ origen=OrigenAuditoriaEnum.WEBHOOK.value,
636
+ descripcion=f"Reserva urgente creada en quirΓ³fano {candidata_cama_id} (desplazΓ³ la reserva {candidata.id})",
637
+ )
638
+ auditoria_crud.registrar(
639
+ db,
640
+ entidad=EntidadAuditoriaEnum.RESERVA_QUIROFANO.value,
641
+ entidad_id=candidata.id,
642
+ cama_id=candidata_cama_id,
643
+ evento=TipoEventoAuditoriaEnum.RESERVA_DESPLAZADA.value,
644
+ estado_nuevo=candidata.estado,
645
+ paciente_id=candidata.paciente_id,
646
+ origen=OrigenAuditoriaEnum.WEBHOOK.value,
647
+ descripcion=f"Reserva {candidata.id} reprogramada por urgencia",
648
+ detalle={"desplazada_por_reserva_id": reserva_urgente.id, "turno_id": candidata.turno_id},
649
+ )
650
+
651
  return reserva_urgente, candidata
652
 
653
 
app/services/solicitud_service.py CHANGED
@@ -14,7 +14,13 @@ from app.schemas.enums import EstadoCamaEnum, EstadoReservaEnum
14
  from app.crud import solicitud as solicitud_crud
15
  from app.crud import cama as cama_crud
16
  from app.crud import reserva as reserva_crud
 
17
  from app.integrations import hce, monitoreo, core, facturacion
 
 
 
 
 
18
 
19
 
20
  _ERR_NOT_FOUND = {"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "Solicitud no encontrada"}
@@ -70,7 +76,21 @@ def recibir_solicitud(db: Client, data: SolicitudHceWebhook) -> Solicitud:
70
  existing = solicitud_crud.get_by_hce_id(db, data.solicitud_hce_id)
71
  if existing:
72
  return existing
73
- return solicitud_crud.create(db, data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
 
76
  # ─── Listar / obtener solicitudes ──────────────────────────────────────────
@@ -95,6 +115,7 @@ def resolver_solicitud(
95
  solicitud_id: str,
96
  data: SolicitudResolucionRequest,
97
  resuelto_por: int,
 
98
  ) -> Solicitud:
99
  sol = _get_solicitud_or_404(db, solicitud_id)
100
 
@@ -111,7 +132,7 @@ def resolver_solicitud(
111
  accion = data.accion.value
112
 
113
  if accion == "RECHAZAR":
114
- _rechazar(sol, data.motivo, resuelto_por)
115
  elif accion in ("APROBAR", "APROBAR_CON_CAMBIO"):
116
  cama_id = data.cama_asignada_id if accion == "APROBAR_CON_CAMBIO" else sol.cama_solicitada_id
117
  if cama_id is None and sol.tipo == "INTERNACION":
@@ -120,26 +141,43 @@ def resolver_solicitud(
120
  detail={"codigo": "ERROR_VALIDACION", "mensaje": "Se requiere cama_asignada_id"},
121
  )
122
  if sol.tipo == "INTERNACION":
123
- _aprobar_internacion(db, sol, cama_id, data.motivo, resuelto_por, accion)
124
  else:
125
- _aprobar_traslado(db, sol, cama_id, data.motivo, resuelto_por, accion)
126
  else:
127
  raise HTTPException(status_code=400, detail={"codigo": "ERROR_VALIDACION", "mensaje": "AcciΓ³n invΓ‘lida"})
128
 
129
  return solicitud_crud.save(db, sol)
130
 
131
 
132
- def _rechazar(sol: Solicitud, motivo: str | None, resuelto_por: int) -> None:
 
 
133
  sol.estado = "RECHAZADA"
134
  sol.accion = "RECHAZAR"
135
  sol.motivo = motivo
136
  sol.resuelto_por = resuelto_por
137
  sol.timestamp_resolucion = datetime.now(timezone.utc)
138
  hce.notify_resultado_solicitud(sol.solicitud_hce_id, "RECHAZADA", motivo)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
 
141
  def _aprobar_internacion(
142
- db: Client, sol: Solicitud, cama_id: int, motivo: str | None, resuelto_por: int, accion: str
 
143
  ) -> None:
144
  paciente = core.validate_patient(sol.paciente_id)
145
  if not paciente:
@@ -173,9 +211,38 @@ def _aprobar_internacion(
173
  hce.notify_resultado_solicitud(sol.solicitud_hce_id, "APROBADA")
174
  monitoreo.notify_alta(sol.paciente_id)
175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
  def _aprobar_traslado(
178
- db: Client, sol: Solicitud, cama_destino_id: int | None, motivo: str | None, resuelto_por: int, accion: str
 
179
  ) -> None:
180
  dest_id = cama_destino_id or sol.cama_destino_solicitada_id
181
  if not dest_id:
@@ -217,6 +284,35 @@ def _aprobar_traslado(
217
  monitoreo.notify_baja(sol.paciente_id)
218
  monitoreo.notify_alta(sol.paciente_id)
219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
 
221
  # ─── Alta mΓ©dica (desde HCE M1) ────────────────────────────────────────────
222
 
@@ -240,10 +336,24 @@ def procesar_alta_medica(db: Client, paciente_id: int) -> Cama:
240
  detail={"codigo": "SERVICIO_EXTERNO_NO_DISPONIBLE", "mensaje": "No se pudo dar de baja el monitoreo (M9)"},
241
  )
242
 
 
243
  cama.estado = EstadoCamaEnum.EN_LIMPIEZA.value
244
  cama.ultimo_movimiento_tipo = "ALTA"
245
  cama.ultima_actualizacion = datetime.now(timezone.utc)
246
  cama_crud.save(db, cama)
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  return cama
248
 
249
 
@@ -256,10 +366,24 @@ def procesar_alerta_emergencia(db: Client, paciente_id: int) -> Cama:
256
  status_code=404,
257
  detail={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "Paciente sin cama asignada"},
258
  )
 
259
  cama.estado = EstadoCamaEnum.CODIGO_ROJO.value
260
  cama.ultima_actualizacion = datetime.now(timezone.utc)
261
  cama_crud.save(db, cama)
262
  hce.notify_evento_episodio(0, "CODIGO_ROJO", f"Alerta de emergencia detectada para paciente {paciente_id}")
 
 
 
 
 
 
 
 
 
 
 
 
 
263
  return cama
264
 
265
 
@@ -270,9 +394,24 @@ def procesar_alerta_resuelta(db: Client, paciente_id: int) -> Cama:
270
  status_code=404,
271
  detail={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "No se encontrΓ³ cama en CODIGO_ROJO para el paciente"},
272
  )
 
273
  cama.estado = EstadoCamaEnum.OCUPADA.value
274
  cama.ultima_actualizacion = datetime.now(timezone.utc)
275
- return cama_crud.save(db, cama)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
 
277
 
278
  # ─── Cancelar reserva por turno (desde M2) ─────────────────────────────────
@@ -298,5 +437,20 @@ def cancelar_reserva_por_turno(db: Client, turno_id: int, motivo: str) -> Reserv
298
  "detalle": f"Estado: {reserva.estado}",
299
  },
300
  )
 
301
  reserva.estado = EstadoReservaEnum.CANCELADA.value
302
- return reserva_crud.save(db, reserva)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  from app.crud import solicitud as solicitud_crud
15
  from app.crud import cama as cama_crud
16
  from app.crud import reserva as reserva_crud
17
+ from app.crud import auditoria as auditoria_crud
18
  from app.integrations import hce, monitoreo, core, facturacion
19
+ from app.schemas.enums import (
20
+ EntidadAuditoriaEnum,
21
+ TipoEventoAuditoriaEnum,
22
+ OrigenAuditoriaEnum,
23
+ )
24
 
25
 
26
  _ERR_NOT_FOUND = {"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "Solicitud no encontrada"}
 
76
  existing = solicitud_crud.get_by_hce_id(db, data.solicitud_hce_id)
77
  if existing:
78
  return existing
79
+ sol = solicitud_crud.create(db, data)
80
+ auditoria_crud.registrar(
81
+ db,
82
+ entidad=EntidadAuditoriaEnum.SOLICITUD.value,
83
+ entidad_id=sol.solicitud_id,
84
+ cama_id=sol.cama_solicitada_id,
85
+ evento=TipoEventoAuditoriaEnum.SOLICITUD_RECIBIDA.value,
86
+ estado_nuevo=sol.estado,
87
+ paciente_id=sol.paciente_id,
88
+ origen=OrigenAuditoriaEnum.WEBHOOK.value,
89
+ descripcion=f"Solicitud {sol.solicitud_id} ({sol.tipo}) recibida desde HCE",
90
+ detalle={"solicitud_hce_id": sol.solicitud_hce_id, "tipo": sol.tipo},
91
+ hospital_id=sol.hospital_id,
92
+ )
93
+ return sol
94
 
95
 
96
  # ─── Listar / obtener solicitudes ──────────────────────────────────────────
 
115
  solicitud_id: str,
116
  data: SolicitudResolucionRequest,
117
  resuelto_por: int,
118
+ actor: dict | None = None,
119
  ) -> Solicitud:
120
  sol = _get_solicitud_or_404(db, solicitud_id)
121
 
 
132
  accion = data.accion.value
133
 
134
  if accion == "RECHAZAR":
135
+ _rechazar(db, sol, data.motivo, resuelto_por, actor)
136
  elif accion in ("APROBAR", "APROBAR_CON_CAMBIO"):
137
  cama_id = data.cama_asignada_id if accion == "APROBAR_CON_CAMBIO" else sol.cama_solicitada_id
138
  if cama_id is None and sol.tipo == "INTERNACION":
 
141
  detail={"codigo": "ERROR_VALIDACION", "mensaje": "Se requiere cama_asignada_id"},
142
  )
143
  if sol.tipo == "INTERNACION":
144
+ _aprobar_internacion(db, sol, cama_id, data.motivo, resuelto_por, accion, actor)
145
  else:
146
+ _aprobar_traslado(db, sol, cama_id, data.motivo, resuelto_por, accion, actor)
147
  else:
148
  raise HTTPException(status_code=400, detail={"codigo": "ERROR_VALIDACION", "mensaje": "AcciΓ³n invΓ‘lida"})
149
 
150
  return solicitud_crud.save(db, sol)
151
 
152
 
153
+ def _rechazar(
154
+ db: Client, sol: Solicitud, motivo: str | None, resuelto_por: int, actor: dict | None = None
155
+ ) -> None:
156
  sol.estado = "RECHAZADA"
157
  sol.accion = "RECHAZAR"
158
  sol.motivo = motivo
159
  sol.resuelto_por = resuelto_por
160
  sol.timestamp_resolucion = datetime.now(timezone.utc)
161
  hce.notify_resultado_solicitud(sol.solicitud_hce_id, "RECHAZADA", motivo)
162
+ auditoria_crud.registrar(
163
+ db,
164
+ entidad=EntidadAuditoriaEnum.SOLICITUD.value,
165
+ entidad_id=sol.solicitud_id,
166
+ cama_id=sol.cama_solicitada_id,
167
+ evento=TipoEventoAuditoriaEnum.SOLICITUD_RECHAZADA.value,
168
+ estado_anterior="PENDIENTE",
169
+ estado_nuevo=sol.estado,
170
+ paciente_id=sol.paciente_id,
171
+ actor=actor,
172
+ descripcion=f"Solicitud {sol.solicitud_id} rechazada",
173
+ detalle={"motivo": motivo},
174
+ hospital_id=sol.hospital_id,
175
+ )
176
 
177
 
178
  def _aprobar_internacion(
179
+ db: Client, sol: Solicitud, cama_id: int, motivo: str | None, resuelto_por: int,
180
+ accion: str, actor: dict | None = None,
181
  ) -> None:
182
  paciente = core.validate_patient(sol.paciente_id)
183
  if not paciente:
 
211
  hce.notify_resultado_solicitud(sol.solicitud_hce_id, "APROBADA")
212
  monitoreo.notify_alta(sol.paciente_id)
213
 
214
+ auditoria_crud.registrar(
215
+ db,
216
+ entidad=EntidadAuditoriaEnum.SOLICITUD.value,
217
+ entidad_id=sol.solicitud_id,
218
+ cama_id=cama_id,
219
+ evento=TipoEventoAuditoriaEnum.SOLICITUD_APROBADA.value,
220
+ estado_anterior="PENDIENTE",
221
+ estado_nuevo=sol.estado,
222
+ paciente_id=sol.paciente_id,
223
+ actor=actor,
224
+ descripcion=f"Solicitud {sol.solicitud_id} aprobada ({accion}) β€” internaciΓ³n",
225
+ detalle={"accion": accion, "cama_asignada_id": cama_id},
226
+ hospital_id=sol.hospital_id,
227
+ )
228
+ auditoria_crud.registrar(
229
+ db,
230
+ entidad=EntidadAuditoriaEnum.CAMA.value,
231
+ entidad_id=cama_id,
232
+ cama_id=cama_id,
233
+ evento=TipoEventoAuditoriaEnum.CAMA_ASIGNADA.value,
234
+ estado_anterior=EstadoCamaEnum.DISPONIBLE.value,
235
+ estado_nuevo=cama.estado,
236
+ paciente_id=sol.paciente_id,
237
+ actor=actor,
238
+ descripcion=f"Paciente {sol.paciente_id} ingresado a la cama {cama_id} (solicitud {sol.solicitud_id})",
239
+ hospital_id=cama.hospital_id,
240
+ )
241
+
242
 
243
  def _aprobar_traslado(
244
+ db: Client, sol: Solicitud, cama_destino_id: int | None, motivo: str | None, resuelto_por: int,
245
+ accion: str, actor: dict | None = None,
246
  ) -> None:
247
  dest_id = cama_destino_id or sol.cama_destino_solicitada_id
248
  if not dest_id:
 
284
  monitoreo.notify_baja(sol.paciente_id)
285
  monitoreo.notify_alta(sol.paciente_id)
286
 
287
+ auditoria_crud.registrar(
288
+ db,
289
+ entidad=EntidadAuditoriaEnum.SOLICITUD.value,
290
+ entidad_id=sol.solicitud_id,
291
+ cama_id=dest_id,
292
+ evento=TipoEventoAuditoriaEnum.SOLICITUD_APROBADA.value,
293
+ estado_anterior="PENDIENTE",
294
+ estado_nuevo=sol.estado,
295
+ paciente_id=sol.paciente_id,
296
+ actor=actor,
297
+ descripcion=f"Solicitud {sol.solicitud_id} aprobada ({accion}) β€” traslado",
298
+ detalle={"accion": accion, "cama_asignada_id": dest_id, "cama_origen_id": sol.cama_origen_id},
299
+ hospital_id=sol.hospital_id,
300
+ )
301
+ auditoria_crud.registrar(
302
+ db,
303
+ entidad=EntidadAuditoriaEnum.CAMA.value,
304
+ entidad_id=dest_id,
305
+ cama_id=dest_id,
306
+ evento=TipoEventoAuditoriaEnum.CAMA_TRASLADO.value,
307
+ estado_anterior=EstadoCamaEnum.DISPONIBLE.value,
308
+ estado_nuevo=cama_destino.estado,
309
+ paciente_id=sol.paciente_id,
310
+ actor=actor,
311
+ descripcion=f"Paciente {sol.paciente_id} trasladado a la cama {dest_id} (solicitud {sol.solicitud_id})",
312
+ detalle={"cama_origen_id": sol.cama_origen_id},
313
+ hospital_id=cama_destino.hospital_id,
314
+ )
315
+
316
 
317
  # ─── Alta mΓ©dica (desde HCE M1) ────────────────────────────────────────────
318
 
 
336
  detail={"codigo": "SERVICIO_EXTERNO_NO_DISPONIBLE", "mensaje": "No se pudo dar de baja el monitoreo (M9)"},
337
  )
338
 
339
+ estado_previo = cama.estado
340
  cama.estado = EstadoCamaEnum.EN_LIMPIEZA.value
341
  cama.ultimo_movimiento_tipo = "ALTA"
342
  cama.ultima_actualizacion = datetime.now(timezone.utc)
343
  cama_crud.save(db, cama)
344
+ auditoria_crud.registrar(
345
+ db,
346
+ entidad=EntidadAuditoriaEnum.CAMA.value,
347
+ entidad_id=cama.id,
348
+ cama_id=cama.id,
349
+ evento=TipoEventoAuditoriaEnum.CAMA_ALTA.value,
350
+ estado_anterior=estado_previo,
351
+ estado_nuevo=cama.estado,
352
+ paciente_id=paciente_id,
353
+ origen=OrigenAuditoriaEnum.WEBHOOK.value,
354
+ descripcion=f"Alta mΓ©dica del paciente {paciente_id}; cama {cama.numero} en limpieza",
355
+ hospital_id=cama.hospital_id,
356
+ )
357
  return cama
358
 
359
 
 
366
  status_code=404,
367
  detail={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "Paciente sin cama asignada"},
368
  )
369
+ estado_previo = cama.estado
370
  cama.estado = EstadoCamaEnum.CODIGO_ROJO.value
371
  cama.ultima_actualizacion = datetime.now(timezone.utc)
372
  cama_crud.save(db, cama)
373
  hce.notify_evento_episodio(0, "CODIGO_ROJO", f"Alerta de emergencia detectada para paciente {paciente_id}")
374
+ auditoria_crud.registrar(
375
+ db,
376
+ entidad=EntidadAuditoriaEnum.CAMA.value,
377
+ entidad_id=cama.id,
378
+ cama_id=cama.id,
379
+ evento=TipoEventoAuditoriaEnum.CAMA_CODIGO_ROJO.value,
380
+ estado_anterior=estado_previo,
381
+ estado_nuevo=cama.estado,
382
+ paciente_id=paciente_id,
383
+ origen=OrigenAuditoriaEnum.WEBHOOK.value,
384
+ descripcion=f"Alerta de emergencia: cama {cama.numero} en CODIGO_ROJO",
385
+ hospital_id=cama.hospital_id,
386
+ )
387
  return cama
388
 
389
 
 
394
  status_code=404,
395
  detail={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "No se encontrΓ³ cama en CODIGO_ROJO para el paciente"},
396
  )
397
+ estado_previo = cama.estado
398
  cama.estado = EstadoCamaEnum.OCUPADA.value
399
  cama.ultima_actualizacion = datetime.now(timezone.utc)
400
+ cama = cama_crud.save(db, cama)
401
+ auditoria_crud.registrar(
402
+ db,
403
+ entidad=EntidadAuditoriaEnum.CAMA.value,
404
+ entidad_id=cama.id,
405
+ cama_id=cama.id,
406
+ evento=TipoEventoAuditoriaEnum.CAMA_ALERTA_RESUELTA.value,
407
+ estado_anterior=estado_previo,
408
+ estado_nuevo=cama.estado,
409
+ paciente_id=paciente_id,
410
+ origen=OrigenAuditoriaEnum.WEBHOOK.value,
411
+ descripcion=f"Alerta resuelta: cama {cama.numero} vuelve a OCUPADA",
412
+ hospital_id=cama.hospital_id,
413
+ )
414
+ return cama
415
 
416
 
417
  # ─── Cancelar reserva por turno (desde M2) ─────────────────────────────────
 
437
  "detalle": f"Estado: {reserva.estado}",
438
  },
439
  )
440
+ estado_previo = reserva.estado
441
  reserva.estado = EstadoReservaEnum.CANCELADA.value
442
+ reserva = reserva_crud.save(db, reserva)
443
+ auditoria_crud.registrar(
444
+ db,
445
+ entidad=EntidadAuditoriaEnum.RESERVA_QUIROFANO.value,
446
+ entidad_id=reserva.id,
447
+ cama_id=reserva.cama_id,
448
+ evento=TipoEventoAuditoriaEnum.RESERVA_CANCELADA.value,
449
+ estado_anterior=estado_previo,
450
+ estado_nuevo=reserva.estado,
451
+ paciente_id=reserva.paciente_id,
452
+ origen=OrigenAuditoriaEnum.WEBHOOK.value,
453
+ descripcion=f"Reserva {reserva.id} cancelada por turno {turno_id}",
454
+ detalle={"turno_id": turno_id, "motivo": motivo},
455
+ )
456
+ return reserva
docs/superpowers/specs/2026-06-26-auditoria-cama-design.md CHANGED
@@ -123,9 +123,11 @@ Siguiendo las capas existentes (`routers β†’ services β†’ crud β†’ models`):
123
  - **`app/crud/auditoria.py`**:
124
  - `registrar(db, *, entidad, entidad_id, evento, cama_id=None, estado_anterior=None, estado_nuevo=None, paciente_id=None, actor=None, origen="API", descripcion=None, detalle=None, hospital_id=None) -> None` β€” inserta una fila. **Best-effort**: envuelto en `try/except`, ante error solo loguea `warning` y nunca propaga (la auditorΓ­a jamΓ‘s rompe la operaciΓ³n de negocio).
125
  - `get_all(db, *, cama_id, entidad, entidad_id, paciente_id, evento, rol, usuario_id, hospital_id, fecha_desde, fecha_hasta, limit, offset) -> tuple[list[Auditoria], int]` β€” query con filtros, orden `creado_en` desc, paginaciΓ³n. Devuelve filas + total.
126
- - **`app/routers/auditoria.py`** β€” `GET /auditoria`.
 
127
  - **`app/schemas/enums.py`** β€” enums nuevos (arriba).
128
- - **`app/main.py`** β€” registrar el router.
 
129
 
130
  ### Actor
131
 
@@ -162,13 +164,46 @@ Tipo liviano para transportar el actor desde el router hasta el crud. Un `dict`
162
 
163
  Para registrar el actor donde hoy no llega, se agrega un parΓ‘metro `actor` a las funciones de servicio invocadas desde routers autenticados (`update_cama`, `delete_cama`, `asignar_cama`, `update_quirofano`, `update_reserva_estado`, `create_reserva`, `resolver_solicitud`). Los routers lo construyen desde el JWT. Las funciones disparadas por webhooks no reciben actor y registran `SISTEMA`/`WEBHOOK`.
164
 
165
- ## Endpoint
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
  ```
168
  GET /api/v1/auditoria
169
  ```
170
 
171
- AutorizaciΓ³n: roles `ADMINISTRATIVO`, `MEDICO`.
 
172
 
173
  Query params (todos opcionales):
174
 
 
123
  - **`app/crud/auditoria.py`**:
124
  - `registrar(db, *, entidad, entidad_id, evento, cama_id=None, estado_anterior=None, estado_nuevo=None, paciente_id=None, actor=None, origen="API", descripcion=None, detalle=None, hospital_id=None) -> None` β€” inserta una fila. **Best-effort**: envuelto en `try/except`, ante error solo loguea `warning` y nunca propaga (la auditorΓ­a jamΓ‘s rompe la operaciΓ³n de negocio).
125
  - `get_all(db, *, cama_id, entidad, entidad_id, paciente_id, evento, rol, usuario_id, hospital_id, fecha_desde, fecha_hasta, limit, offset) -> tuple[list[Auditoria], int]` β€” query con filtros, orden `creado_en` desc, paginaciΓ³n. Devuelve filas + total.
126
+ - **`app/routers/auditoria.py`** β€” `GET /auditoria` + `WS /auditoria/ws`.
127
+ - **`app/realtime.py`** β€” `AuditoriaHub` (broadcast in-process a los WebSocket).
128
  - **`app/schemas/enums.py`** β€” enums nuevos (arriba).
129
+ - **`app/main.py`** β€” registrar el router y bindear el event loop al hub en el `lifespan`.
130
+ - **`scripts/create_auditoria_table.py`** β€” bootstrap DDL idempotente vΓ­a psycopg2.
131
 
132
  ### Actor
133
 
 
164
 
165
  Para registrar el actor donde hoy no llega, se agrega un parΓ‘metro `actor` a las funciones de servicio invocadas desde routers autenticados (`update_cama`, `delete_cama`, `asignar_cama`, `update_quirofano`, `update_reserva_estado`, `create_reserva`, `resolver_solicitud`). Los routers lo construyen desde el JWT. Las funciones disparadas por webhooks no reciben actor y registran `SISTEMA`/`WEBHOOK`.
166
 
167
+ ## CreaciΓ³n de la tabla
168
+
169
+ Como `supabase-py` (PostgREST) no ejecuta DDL, la tabla se crea con
170
+ `scripts/create_auditoria_table.py`: se conecta por `psycopg2` usando
171
+ `DATABASE_URL` (lee `.env` si la variable no estΓ‘ en el entorno) y ejecuta el
172
+ DDL idempotente de arriba. Se corre una sola vez con
173
+ `python scripts/create_auditoria_table.py`. El SQL tambiΓ©n queda documentado en
174
+ el README para pegarlo manualmente en el Supabase SQL Editor.
175
+
176
+ ## Entrega en tiempo real (WebSocket)
177
+
178
+ AdemΓ‘s del GET REST, se expone `WS /api/v1/auditoria/ws` para que el frontend se
179
+ actualice en vivo. Mecanismo:
180
+
181
+ - **Hub in-process** (`app/realtime.py`): mantiene en memoria las conexiones
182
+ WebSocket activas con sus filtros. VΓ‘lido para un solo proceso uvicorn (el
183
+ Dockerfile no usa `--workers`). Si se escala a varios workers/procesos, hay que
184
+ migrar a Supabase Realtime o Redis pub/sub, porque cada proceso solo ve sus
185
+ conexiones.
186
+ - **Puente sync→async**: `crud.auditoria.registrar` es síncrono (corre en el
187
+ threadpool de FastAPI). Tras insertar, llama a `hub.publish(evento)`, que usa
188
+ `asyncio.run_coroutine_threadsafe` contra el event loop capturado en el
189
+ `lifespan` (`hub.bind_loop`). Best-effort: si no hay loop o clientes, no hace
190
+ nada; nunca lanza.
191
+ - **Al conectar**, el endpoint autentica el JWT (query param `token`, porque el
192
+ navegador no puede setear el header `Authorization` en WS), envΓ­a un
193
+ `{"tipo": "snapshot", ...}` con el historial filtrado (mismo `get_all` que el
194
+ GET) y luego cada nuevo evento llega como `{"tipo": "evento", "evento": {...}}`.
195
+ - **Filtrado por conexiΓ³n**: cada cliente puede suscribirse con filtros
196
+ (`cama_id`, `entidad`, `paciente_id`, etc.); el hub solo le envΓ­a los eventos
197
+ que matchean.
198
+
199
+ ## Endpoint REST
200
 
201
  ```
202
  GET /api/v1/auditoria
203
  ```
204
 
205
+ AutorizaciΓ³n: roles `ADMINISTRATIVO`, `MEDICO`. Se conserva como fallback para
206
+ fronts que no usen WebSocket.
207
 
208
  Query params (todos opcionales):
209
 
scripts/create_auditoria_table.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Crea la tabla de auditorΓ­a (y sus Γ­ndices) en la base PostgreSQL/Supabase.
3
+
4
+ Idempotente: usa CREATE TABLE / CREATE INDEX IF NOT EXISTS, asΓ­ que puede
5
+ correrse varias veces sin efectos secundarios.
6
+
7
+ Uso:
8
+ # Requiere DATABASE_URL en el entorno o en .env
9
+ # postgresql://USUARIO:CONTRASEΓ‘A@HOST/NOMBRE_BD?sslmode=require
10
+ python scripts/create_auditoria_table.py
11
+
12
+ No usa el cliente supabase-py porque PostgREST no ejecuta DDL; se conecta vΓ­a
13
+ psycopg2 directamente al Postgres (psycopg2-binary ya estΓ‘ en requirements.txt).
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ import psycopg2
22
+
23
+ DDL = """
24
+ CREATE TABLE IF NOT EXISTS auditoria (
25
+ id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
26
+ entidad TEXT NOT NULL,
27
+ entidad_id TEXT NOT NULL,
28
+ cama_id BIGINT,
29
+ evento TEXT NOT NULL,
30
+ estado_anterior TEXT,
31
+ estado_nuevo TEXT,
32
+ paciente_id BIGINT,
33
+ usuario_id TEXT,
34
+ rol TEXT,
35
+ origen TEXT NOT NULL DEFAULT 'API',
36
+ descripcion TEXT,
37
+ detalle JSONB,
38
+ hospital_id TEXT,
39
+ creado_en TIMESTAMPTZ NOT NULL DEFAULT now()
40
+ );
41
+
42
+ CREATE INDEX IF NOT EXISTS idx_auditoria_cama_id ON auditoria (cama_id);
43
+ CREATE INDEX IF NOT EXISTS idx_auditoria_entidad ON auditoria (entidad, entidad_id);
44
+ CREATE INDEX IF NOT EXISTS idx_auditoria_paciente_id ON auditoria (paciente_id);
45
+ CREATE INDEX IF NOT EXISTS idx_auditoria_creado_en ON auditoria (creado_en DESC);
46
+ CREATE INDEX IF NOT EXISTS idx_auditoria_hospital_id ON auditoria (hospital_id);
47
+ """
48
+
49
+
50
+ def _load_env_file() -> None:
51
+ """Carga DATABASE_URL desde .env si no estΓ‘ ya en el entorno (sin dependencias)."""
52
+ if os.getenv("DATABASE_URL"):
53
+ return
54
+ env_path = Path(__file__).resolve().parent.parent / ".env"
55
+ if not env_path.exists():
56
+ return
57
+ for line in env_path.read_text(encoding="utf-8").splitlines():
58
+ line = line.strip()
59
+ if not line or line.startswith("#") or "=" not in line:
60
+ continue
61
+ key, _, value = line.partition("=")
62
+ if key.strip() == "DATABASE_URL":
63
+ os.environ.setdefault("DATABASE_URL", value.strip().strip('"').strip("'"))
64
+ break
65
+
66
+
67
+ def main() -> int:
68
+ _load_env_file()
69
+ dsn = os.getenv("DATABASE_URL")
70
+ if not dsn:
71
+ print(
72
+ "ERROR: falta DATABASE_URL. Definila en el entorno o en .env:\n"
73
+ " postgresql://USUARIO:CONTRASEΓ‘A@HOST/NOMBRE_BD?sslmode=require",
74
+ file=sys.stderr,
75
+ )
76
+ return 1
77
+
78
+ print("Conectando a la base…")
79
+ with psycopg2.connect(dsn) as conn:
80
+ with conn.cursor() as cur:
81
+ cur.execute(DDL)
82
+ conn.commit()
83
+ print("OK: tabla 'auditoria' e Γ­ndices creados (o ya existΓ­an).")
84
+ return 0
85
+
86
+
87
+ if __name__ == "__main__":
88
+ raise SystemExit(main())
tests/factories.py CHANGED
@@ -76,6 +76,7 @@ def make_solicitud(**overrides) -> SimpleNamespace:
76
  "cama_asignada_id": None,
77
  "origen": "GUARDIA",
78
  "turno_id": None,
 
79
  "diagnostico_ingreso": None,
80
  "obra_social_id": None,
81
  "numero_afiliado": None,
 
76
  "cama_asignada_id": None,
77
  "origen": "GUARDIA",
78
  "turno_id": None,
79
+ "hospital_id": "HOSP-001",
80
  "diagnostico_ingreso": None,
81
  "obra_social_id": None,
82
  "numero_afiliado": None,
tests/test_auditoria.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests de auditorΓ­a: endpoint GET REST, WebSocket (snapshot), instrumentaciΓ³n de
3
+ los servicios y garantΓ­a de que el registro es best-effort (nunca rompe la
4
+ operaciΓ³n de negocio).
5
+ """
6
+ from datetime import datetime, timezone
7
+ from types import SimpleNamespace
8
+ from unittest.mock import MagicMock
9
+
10
+ import pytest
11
+ from fastapi.testclient import TestClient
12
+ from starlette.websockets import WebSocketDisconnect
13
+
14
+ from app.dependencies import create_access_token
15
+ from app.crud import auditoria as auditoria_crud
16
+ from tests.factories import make_cama
17
+
18
+ PREFIX = "/api/v1/auditoria"
19
+ _NOW = datetime(2026, 6, 26, 12, 0, tzinfo=timezone.utc)
20
+
21
+
22
+ def make_evento(**overrides) -> SimpleNamespace:
23
+ data = {
24
+ "id": 1,
25
+ "entidad": "CAMA",
26
+ "entidad_id": "101",
27
+ "cama_id": 101,
28
+ "evento": "CAMA_CAMBIO_ESTADO",
29
+ "estado_anterior": "OCUPADA",
30
+ "estado_nuevo": "EN_LIMPIEZA",
31
+ "paciente_id": 7,
32
+ "usuario_id": "1",
33
+ "rol": "ADMINISTRATIVO",
34
+ "origen": "API",
35
+ "descripcion": "Cama 101: OCUPADA β†’ EN_LIMPIEZA",
36
+ "detalle": {"motivo": "alta"},
37
+ "hospital_id": "HOSP-001",
38
+ "creado_en": _NOW,
39
+ }
40
+ data.update(overrides)
41
+ return SimpleNamespace(**data)
42
+
43
+
44
+ # ─── Auth / roles ──────────────────────────────────────────────────────────
45
+
46
+ def test_get_auditoria_sin_token_401(client: TestClient):
47
+ assert client.get(PREFIX).status_code == 401
48
+
49
+
50
+ def test_get_auditoria_rol_limpieza_403(client: TestClient, limpieza_headers):
51
+ assert client.get(PREFIX, headers=limpieza_headers).status_code == 403
52
+
53
+
54
+ # ─── Listado REST ────────────────────────────────────────────────────────────
55
+
56
+ def test_get_auditoria_ok(client: TestClient, medico_headers, monkeypatch):
57
+ monkeypatch.setattr(
58
+ "app.crud.auditoria.get_all",
59
+ lambda *a, **k: ([make_evento(), make_evento(id=2, evento="CAMA_BAJA")], 2),
60
+ )
61
+ resp = client.get(f"{PREFIX}?cama_id=101", headers=medico_headers)
62
+ assert resp.status_code == 200
63
+ data = resp.json()
64
+ assert data["total"] == 2
65
+ assert data["eventos"][0]["evento"] == "CAMA_CAMBIO_ESTADO"
66
+ assert data["eventos"][0]["cama_id"] == 101
67
+
68
+
69
+ def test_get_auditoria_pasa_filtros_al_crud(client: TestClient, admin_headers, monkeypatch):
70
+ capturado = {}
71
+
72
+ def fake_get_all(db, **kwargs):
73
+ capturado.update(kwargs)
74
+ return [], 0
75
+
76
+ monkeypatch.setattr("app.crud.auditoria.get_all", fake_get_all)
77
+ resp = client.get(
78
+ f"{PREFIX}?cama_id=5&evento=CAMA_BAJA&paciente_id=9&limit=10&offset=20",
79
+ headers=admin_headers,
80
+ )
81
+ assert resp.status_code == 200
82
+ assert capturado["cama_id"] == 5
83
+ assert capturado["evento"] == "CAMA_BAJA"
84
+ assert capturado["paciente_id"] == 9
85
+ assert capturado["limit"] == 10
86
+ assert capturado["offset"] == 20
87
+
88
+
89
+ def test_get_auditoria_limit_invalido_422(client: TestClient, admin_headers):
90
+ assert client.get(f"{PREFIX}?limit=9999", headers=admin_headers).status_code == 422
91
+
92
+
93
+ # ─── InstrumentaciΓ³n de servicios ────────────────────────────────────────────
94
+
95
+ def test_crear_cama_registra_evento(client: TestClient, admin_headers, monkeypatch):
96
+ eventos = []
97
+ monkeypatch.setattr("app.crud.cama.create", lambda db, data: make_cama(numero=data.numero))
98
+ monkeypatch.setattr(
99
+ "app.crud.auditoria.registrar",
100
+ lambda db, **kw: eventos.append(kw),
101
+ )
102
+ payload = {
103
+ "numero": 101, "piso": 1, "sector": "SALA_COMUN",
104
+ "tipo": "ESTANDAR", "hospital_id": "HOSP-001",
105
+ }
106
+ resp = client.post("/api/v1/camas", json=payload, headers=admin_headers)
107
+ assert resp.status_code == 201
108
+ assert len(eventos) == 1
109
+ assert eventos[0]["evento"] == "CAMA_CREADA"
110
+ assert eventos[0]["actor"] == {"usuario_id": "1", "rol": "ADMINISTRATIVO"}
111
+
112
+
113
+ def test_baja_cama_registra_evento(client: TestClient, admin_headers, monkeypatch):
114
+ eventos = []
115
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_cama(estado="DISPONIBLE"))
116
+ monkeypatch.setattr("app.crud.cama.save", lambda db, cama: cama)
117
+ monkeypatch.setattr("app.crud.auditoria.registrar", lambda db, **kw: eventos.append(kw))
118
+ resp = client.delete("/api/v1/camas/101", headers=admin_headers)
119
+ assert resp.status_code == 200
120
+ assert any(e["evento"] == "CAMA_BAJA" and e["estado_nuevo"] == "BAJA_PERMANENTE" for e in eventos)
121
+
122
+
123
+ # ─── Best-effort: la auditorΓ­a nunca rompe la operaciΓ³n ──────────────────────
124
+
125
+ def test_registrar_no_propaga_si_falla(monkeypatch):
126
+ db = MagicMock()
127
+ db.table.side_effect = RuntimeError("base caΓ­da")
128
+ # No debe lanzar ninguna excepciΓ³n.
129
+ assert auditoria_crud.registrar(db, entidad="CAMA", entidad_id=1, evento="CAMA_CREADA") is None
130
+
131
+
132
+ def test_crear_cama_ok_aunque_falle_auditoria(client: TestClient, admin_headers, monkeypatch):
133
+ monkeypatch.setattr("app.crud.cama.create", lambda db, data: make_cama(numero=data.numero))
134
+ # registrar real captura su propia excepciΓ³n internamente; aquΓ­ verificamos
135
+ # que el flujo del endpoint no se ve afectado.
136
+ monkeypatch.setattr("app.crud.auditoria.registrar", lambda db, **kw: None)
137
+ payload = {
138
+ "numero": 102, "piso": 1, "sector": "SALA_COMUN",
139
+ "tipo": "ESTANDAR", "hospital_id": "HOSP-001",
140
+ }
141
+ resp = client.post("/api/v1/camas", json=payload, headers=admin_headers)
142
+ assert resp.status_code == 201
143
+
144
+
145
+ # ─── WebSocket ───────────────────────────────────────────────────────────────
146
+
147
+ def _token(rol: str = "MEDICO") -> str:
148
+ return create_access_token(sub="1", rol=rol)
149
+
150
+
151
+ def test_ws_sin_token_se_rechaza(client: TestClient):
152
+ with pytest.raises(WebSocketDisconnect):
153
+ with client.websocket_connect(f"{PREFIX}/ws") as ws:
154
+ ws.receive_json()
155
+
156
+
157
+ def test_ws_envia_snapshot_al_conectar(client: TestClient, monkeypatch):
158
+ monkeypatch.setattr(
159
+ "app.crud.auditoria.get_all",
160
+ lambda *a, **k: ([make_evento()], 1),
161
+ )
162
+ with client.websocket_connect(f"{PREFIX}/ws?token={_token()}&cama_id=101") as ws:
163
+ msg = ws.receive_json()
164
+ assert msg["tipo"] == "snapshot"
165
+ assert msg["total"] == 1
166
+ assert msg["eventos"][0]["evento"] == "CAMA_CAMBIO_ESTADO"
167
+
168
+
169
+ # ─── Hub: filtrado por conexiΓ³n ──────────────────────────────────────────────
170
+
171
+ def test_hub_match_respeta_filtros():
172
+ from app.realtime import _match
173
+
174
+ evento = {"cama_id": 101, "entidad": "CAMA", "paciente_id": 7}
175
+ assert _match(evento, {}) is True
176
+ assert _match(evento, {"cama_id": 101}) is True
177
+ assert _match(evento, {"cama_id": 999}) is False
178
+ assert _match(evento, {"entidad": "CAMA", "paciente_id": 7}) is True
179
+ assert _match(evento, {"paciente_id": 8}) is False