juampisor commited on
Commit
f564ed8
·
1 Parent(s): f6c0922

Tabla de auditoria. Fixes a restricciones de roles.

Browse files
.DS_Store CHANGED
Binary files a/.DS_Store and b/.DS_Store differ
 
app/crud/auditoria.py CHANGED
@@ -3,7 +3,7 @@ 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
@@ -13,7 +13,6 @@ from typing import Any
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
 
@@ -61,14 +60,7 @@ def registrar(
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
 
 
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
+ El push en tiempo real lo maneja Supabase Realtime directamente sobre la tabla.
7
  """
8
  from __future__ import annotations
9
  import logging
 
13
  from supabase import Client
14
 
15
  from app.models.auditoria import Auditoria
 
16
 
17
  logger = logging.getLogger(__name__)
18
 
 
60
  "creado_en": datetime.now(timezone.utc).isoformat(),
61
  }
62
 
63
+ db.table(_TABLE).insert(row).execute()
 
 
 
 
 
 
 
64
  except Exception as e:
65
  logger.warning("No se pudo registrar evento de auditoría (%s/%s): %s", entidad, evento, e)
66
 
app/crud/cama.py CHANGED
@@ -17,7 +17,6 @@ def get_by_id(db: Client, cama_id: int) -> Cama | None:
17
 
18
  def get_all(
19
  db: Client,
20
- rol: str,
21
  piso: int | None = None,
22
  sector: str | None = None,
23
  estado: str | None = None,
@@ -25,11 +24,8 @@ def get_all(
25
  ) -> list[Cama]:
26
  q = db.table(_TABLE).select("*").neq("estado", "BAJA_PERMANENTE")
27
 
28
- if rol == "LIMPIEZA":
29
- q = q.eq("estado", "EN_LIMPIEZA")
30
- elif estado:
31
  q = q.eq("estado", estado)
32
-
33
  if piso is not None:
34
  q = q.eq("piso", piso)
35
  if sector:
 
17
 
18
  def get_all(
19
  db: Client,
 
20
  piso: int | None = None,
21
  sector: str | None = None,
22
  estado: str | None = None,
 
24
  ) -> list[Cama]:
25
  q = db.table(_TABLE).select("*").neq("estado", "BAJA_PERMANENTE")
26
 
27
+ if estado:
 
 
28
  q = q.eq("estado", estado)
 
29
  if piso is not None:
30
  q = q.eq("piso", piso)
31
  if sector:
app/main.py CHANGED
@@ -3,7 +3,6 @@ Health Grid - Módulo 6: Internación y Gestión de Camas
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,7 +11,6 @@ from fastapi.responses import JSONResponse
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
@@ -30,9 +28,6 @@ logging.basicConfig(
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
 
 
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
 
12
  from app.config import settings
13
  from app.dependencies import create_access_token
 
14
 
15
  from app.routers import camas, quirofanos, solicitudes, webhooks, auditoria
16
  from app.routers.webhooks import router_turnos
 
28
 
29
  @asynccontextmanager
30
  async def lifespan(app: FastAPI):
 
 
 
31
  logger.info("Conectado a Supabase — listo para operar")
32
  yield
33
 
app/realtime.py DELETED
@@ -1,75 +0,0 @@
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 CHANGED
@@ -1,30 +1,25 @@
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,
@@ -66,72 +61,3 @@ def get_auditoria(
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
 
1
  """
2
  Auditoría de camas: historial de eventos.
3
 
4
+ GET /auditoria — snapshot REST con filtros y paginación.
5
+ El tiempo real lo maneja Supabase Realtime directamente en el front.
6
  """
7
  from datetime import datetime
8
  from typing import Optional
9
 
10
+ from fastapi import APIRouter, Depends, Query
11
  from supabase import Client
12
 
13
+ from app.dependencies import get_db, require_roles
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
 
18
  router = APIRouter(prefix="/auditoria", tags=["Auditoría"])
19
 
20
  _ROLES_PERMITIDOS = ("ADMINISTRATIVO", "MEDICO")
21
 
22
 
 
 
 
 
23
  @router.get(
24
  "",
25
  response_model=AuditoriaListResponse,
 
61
  total=total,
62
  eventos=[AuditoriaResponse.model_validate(f) for f in filas],
63
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/routers/camas.py CHANGED
@@ -33,7 +33,7 @@ def get_camas(
33
  db: Client = Depends(get_db),
34
  user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO", "LIMPIEZA")),
35
  ):
36
- camas = cama_service.get_camas(db, user["rol"], piso, sector, estado.value if estado else None, hospital_id)
37
  camas_resp = [CamaResponse.model_validate(c) for c in camas]
38
  estados = [c.estado for c in camas]
39
  return CamaMapaResponse(
@@ -72,7 +72,7 @@ def crear_cama(
72
  def get_cama(
73
  cama_id: int,
74
  db: Client = Depends(get_db),
75
- user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
76
  ):
77
  cama = cama_service.get_cama(db, cama_id)
78
  return CamaResponse.model_validate(cama)
 
33
  db: Client = Depends(get_db),
34
  user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO", "LIMPIEZA")),
35
  ):
36
+ camas = cama_service.get_camas(db, piso, sector, estado.value if estado else None, hospital_id)
37
  camas_resp = [CamaResponse.model_validate(c) for c in camas]
38
  estados = [c.estado for c in camas]
39
  return CamaMapaResponse(
 
72
  def get_cama(
73
  cama_id: int,
74
  db: Client = Depends(get_db),
75
+ user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO", "LIMPIEZA")),
76
  ):
77
  cama = cama_service.get_cama(db, cama_id)
78
  return CamaResponse.model_validate(cama)
app/services/cama_service.py CHANGED
@@ -68,13 +68,12 @@ def _verificar_contraindicaciones(paciente_id: int, cama: Cama) -> None:
68
 
69
  def get_camas(
70
  db: Client,
71
- rol: str,
72
  piso: int | None = None,
73
  sector: str | None = None,
74
  estado: str | None = None,
75
  hospital_id: str | None = None,
76
  ) -> list[Cama]:
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:
@@ -103,6 +102,15 @@ def update_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
108
 
 
68
 
69
  def get_camas(
70
  db: Client,
 
71
  piso: int | None = None,
72
  sector: str | None = None,
73
  estado: str | None = None,
74
  hospital_id: str | None = None,
75
  ) -> list[Cama]:
76
+ return cama_crud.get_all(db, piso, sector, estado, hospital_id)
77
 
78
 
79
  def create_cama(db: Client, data: CamaCreateRequest, actor: dict | None = None) -> Cama:
 
102
  cama = _get_cama_or_404(db, cama_id)
103
  estado_previo = cama.estado
104
 
105
+ if rol == "LIMPIEZA" and data.contraindicaciones_incompatibles is not None:
106
+ raise HTTPException(
107
+ status_code=403,
108
+ detail={
109
+ "codigo": "NO_AUTORIZADO",
110
+ "mensaje": "El rol LIMPIEZA no puede modificar contraindicaciones",
111
+ },
112
+ )
113
+
114
  if data.estado is not None:
115
  nuevo_estado = data.estado.value
116