Cambios a payload M9
Browse files- app/integrations/monitoreo.py +14 -6
- app/services/cama_service.py +3 -3
- app/services/solicitud_service.py +4 -4
- documentation/M6_DISEÑO.md +19 -19
- documentation/M6_EVENTOS_RABBITMQ.md +20 -21
- documentation/M6_EVENTOS_REFERENCIA.md +115 -0
- tests/test_core_events.py +44 -2
- tests/test_solicitudes.py +28 -0
app/integrations/monitoreo.py
CHANGED
|
@@ -7,18 +7,20 @@ from app.integrations import core_events
|
|
| 7 |
from app.integrations._base import _post
|
| 8 |
|
| 9 |
|
| 10 |
-
def notify_alta(paciente_id: int) -> bool:
|
| 11 |
"""
|
| 12 |
Además del webhook REST directo (sin cambios), publica el mismo evento al bus del
|
| 13 |
-
Core (ALTA_MONITOREO) vía `core_events.publish_event`.
|
| 14 |
-
|
| 15 |
-
`
|
|
|
|
| 16 |
"""
|
| 17 |
if settings.mock_external_services:
|
| 18 |
return True
|
| 19 |
payload = {
|
| 20 |
"evento": "ALTA_MONITOREO",
|
| 21 |
"paciente_id": paciente_id,
|
|
|
|
| 22 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 23 |
}
|
| 24 |
# Canal primario: evento via M10 Core. Backup HTTP si falla o no está configurado.
|
|
@@ -32,14 +34,20 @@ def notify_alta(paciente_id: int) -> bool:
|
|
| 32 |
) is not None
|
| 33 |
|
| 34 |
|
| 35 |
-
def notify_baja(paciente_id: int) -> bool:
|
| 36 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
if settings.mock_external_services:
|
| 38 |
print(f"[SIMULACION] Request a M9 Monitoreo → baja de paciente {paciente_id}")
|
| 39 |
return True
|
| 40 |
payload = {
|
| 41 |
"evento": "BAJA_MONITOREO",
|
| 42 |
"paciente_id": paciente_id,
|
|
|
|
| 43 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 44 |
}
|
| 45 |
# Canal primario: evento via M10 Core. Backup HTTP si falla o no está configurado.
|
|
|
|
| 7 |
from app.integrations._base import _post
|
| 8 |
|
| 9 |
|
| 10 |
+
def notify_alta(paciente_id: int, cama_id: int | None = None) -> bool:
|
| 11 |
"""
|
| 12 |
Además del webhook REST directo (sin cambios), publica el mismo evento al bus del
|
| 13 |
+
Core (ALTA_MONITOREO, event_type_id=26) vía `core_events.publish_event`.
|
| 14 |
+
|
| 15 |
+
`cama_id`: la cama a la que se asocia el ingreso a monitoreo — la cama destino en un
|
| 16 |
+
ingreso o traslado (ver call sites en `solicitud_service.py`/`cama_service.py`).
|
| 17 |
"""
|
| 18 |
if settings.mock_external_services:
|
| 19 |
return True
|
| 20 |
payload = {
|
| 21 |
"evento": "ALTA_MONITOREO",
|
| 22 |
"paciente_id": paciente_id,
|
| 23 |
+
"cama_id": cama_id,
|
| 24 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 25 |
}
|
| 26 |
# Canal primario: evento via M10 Core. Backup HTTP si falla o no está configurado.
|
|
|
|
| 34 |
) is not None
|
| 35 |
|
| 36 |
|
| 37 |
+
def notify_baja(paciente_id: int, cama_id: int | None = None) -> bool:
|
| 38 |
+
"""
|
| 39 |
+
Mismo esquema que `notify_alta`, para BAJA_MONITOREO (event_type_id=27).
|
| 40 |
+
|
| 41 |
+
`cama_id`: la cama que el paciente deja — la cama origen en un traslado, o la cama que
|
| 42 |
+
se libera en un alta médica (ver call sites en `solicitud_service.py`/`cama_service.py`).
|
| 43 |
+
"""
|
| 44 |
if settings.mock_external_services:
|
| 45 |
print(f"[SIMULACION] Request a M9 Monitoreo → baja de paciente {paciente_id}")
|
| 46 |
return True
|
| 47 |
payload = {
|
| 48 |
"evento": "BAJA_MONITOREO",
|
| 49 |
"paciente_id": paciente_id,
|
| 50 |
+
"cama_id": cama_id,
|
| 51 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 52 |
}
|
| 53 |
# Canal primario: evento via M10 Core. Backup HTTP si falla o no está configurado.
|
app/services/cama_service.py
CHANGED
|
@@ -273,11 +273,11 @@ def asignar_cama(
|
|
| 273 |
cama_origen.ultima_actualizacion = datetime.now(timezone.utc)
|
| 274 |
cama_crud.save(db, cama_origen)
|
| 275 |
hce.notify_movimiento("TRASLADO", paciente_id, cama_id, cama_origen_id)
|
| 276 |
-
monitoreo.notify_baja(paciente_id)
|
| 277 |
-
monitoreo.notify_alta(paciente_id)
|
| 278 |
else:
|
| 279 |
hce.notify_movimiento("INGRESO", paciente_id, cama_id)
|
| 280 |
-
monitoreo.notify_alta(paciente_id)
|
| 281 |
|
| 282 |
cama_destino.estado = EstadoCamaEnum.OCUPADA.value
|
| 283 |
cama_destino.paciente_id = paciente_id
|
|
|
|
| 273 |
cama_origen.ultima_actualizacion = datetime.now(timezone.utc)
|
| 274 |
cama_crud.save(db, cama_origen)
|
| 275 |
hce.notify_movimiento("TRASLADO", paciente_id, cama_id, cama_origen_id)
|
| 276 |
+
monitoreo.notify_baja(paciente_id, cama_origen_id)
|
| 277 |
+
monitoreo.notify_alta(paciente_id, cama_id)
|
| 278 |
else:
|
| 279 |
hce.notify_movimiento("INGRESO", paciente_id, cama_id)
|
| 280 |
+
monitoreo.notify_alta(paciente_id, cama_id)
|
| 281 |
|
| 282 |
cama_destino.estado = EstadoCamaEnum.OCUPADA.value
|
| 283 |
cama_destino.paciente_id = paciente_id
|
app/services/solicitud_service.py
CHANGED
|
@@ -246,7 +246,7 @@ def _aprobar_internacion(
|
|
| 246 |
|
| 247 |
hce.notify_movimiento("INGRESO", sol.paciente_id, cama_id)
|
| 248 |
hce.notify_resultado_solicitud(sol.solicitud_hce_id, "APROBADA")
|
| 249 |
-
monitoreo.notify_alta(sol.paciente_id)
|
| 250 |
|
| 251 |
auditoria_crud.registrar(
|
| 252 |
db,
|
|
@@ -336,8 +336,8 @@ def _aprobar_traslado(
|
|
| 336 |
|
| 337 |
hce.notify_movimiento("TRASLADO", sol.paciente_id, dest_id, sol.cama_origen_id)
|
| 338 |
hce.notify_resultado_solicitud(sol.solicitud_hce_id, "APROBADA")
|
| 339 |
-
monitoreo.notify_baja(sol.paciente_id)
|
| 340 |
-
monitoreo.notify_alta(sol.paciente_id)
|
| 341 |
|
| 342 |
auditoria_crud.registrar(
|
| 343 |
db,
|
|
@@ -383,7 +383,7 @@ def procesar_alta_medica(db: Client, data: AltaMedicaWebhook) -> Cama:
|
|
| 383 |
# el paciente sale de monitoreo, pero que M9 esté caído no debe revertir el alta.
|
| 384 |
# La notificación real a M7 (CAMA_LISTA) ocurre más adelante, al completar la
|
| 385 |
# limpieza (cama_service.py), también fire-and-forget.
|
| 386 |
-
monitoreo.notify_baja(paciente_id)
|
| 387 |
|
| 388 |
estado_previo = cama.estado
|
| 389 |
cama.estado = EstadoCamaEnum.EN_LIMPIEZA.value
|
|
|
|
| 246 |
|
| 247 |
hce.notify_movimiento("INGRESO", sol.paciente_id, cama_id)
|
| 248 |
hce.notify_resultado_solicitud(sol.solicitud_hce_id, "APROBADA")
|
| 249 |
+
monitoreo.notify_alta(sol.paciente_id, cama_id)
|
| 250 |
|
| 251 |
auditoria_crud.registrar(
|
| 252 |
db,
|
|
|
|
| 336 |
|
| 337 |
hce.notify_movimiento("TRASLADO", sol.paciente_id, dest_id, sol.cama_origen_id)
|
| 338 |
hce.notify_resultado_solicitud(sol.solicitud_hce_id, "APROBADA")
|
| 339 |
+
monitoreo.notify_baja(sol.paciente_id, sol.cama_origen_id)
|
| 340 |
+
monitoreo.notify_alta(sol.paciente_id, dest_id)
|
| 341 |
|
| 342 |
auditoria_crud.registrar(
|
| 343 |
db,
|
|
|
|
| 383 |
# el paciente sale de monitoreo, pero que M9 esté caído no debe revertir el alta.
|
| 384 |
# La notificación real a M7 (CAMA_LISTA) ocurre más adelante, al completar la
|
| 385 |
# limpieza (cama_service.py), también fire-and-forget.
|
| 386 |
+
monitoreo.notify_baja(paciente_id, cama.id)
|
| 387 |
|
| 388 |
estado_previo = cama.estado
|
| 389 |
cama.estado = EstadoCamaEnum.EN_LIMPIEZA.value
|
documentation/M6_DISEÑO.md
CHANGED
|
@@ -245,9 +245,9 @@ Margen de precisión aceptable: con un cron cada 1–5 minutos, una cirugía pue
|
|
| 245 |
|
| 246 |
| Evento | Receptor | Endpoint receptor / evento del bus | Cuándo |
|
| 247 |
|--------|----------|-------------------|--------|
|
| 248 |
-
| `SOLICITUD_RESUELTA` | M1 HCE | `POST /hce/solicitudes/{solicitudHceId}/resultado` (REST); evento
|
| 249 |
-
| `ALTA_MONITOREO` | M9 Monitoreo | `POST /webhooks/internacion/alta-monitoreo` (REST); evento
|
| 250 |
-
| `BAJA_MONITOREO` | M9 Monitoreo | `POST /webhooks/internacion/baja-monitoreo` (REST); evento
|
| 251 |
| `CAMA_LISTA` / `CIERRE_INTERNACION` | M7 Facturación | `POST /webhooks/internacion/cama-lista` (REST, fallback/testing); evento `facturacion.internacion.cama-lista.requested` (`event_type_id=19`, activo) | Al completar limpieza post-alta (`EN_LIMPIEZA → DISPONIBLE`) |
|
| 252 |
|
| 253 |
**M7 confirmó su integración por escrito** (`documentation/integrations/M7_integration.md`):
|
|
@@ -348,22 +348,22 @@ devuelve sincrónicamente qué quirófano/reserva se asignó y qué reservas se
|
|
| 348 |
no hay hoy un canal async equivalente. Migrarla requiere antes acordar con M1 un evento de
|
| 349 |
respuesta (`correlation_id` + `response_event_id`). Sigue siendo solo REST.
|
| 350 |
|
| 351 |
-
**Lado saliente —
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
`
|
| 359 |
-
|
| 360 |
-
`
|
| 361 |
-
`
|
| 362 |
-
`notify_*` (`hce.notify_resultado_solicitud`,
|
| 363 |
-
`facturacion.notify_cama_lista`) hacen **dual-write**:
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
|
| 368 |
---
|
| 369 |
|
|
|
|
| 245 |
|
| 246 |
| Evento | Receptor | Endpoint receptor / evento del bus | Cuándo |
|
| 247 |
|--------|----------|-------------------|--------|
|
| 248 |
+
| `SOLICITUD_RESUELTA` | M1 HCE | `POST /hce/solicitudes/{solicitudHceId}/resultado` (REST); evento `event_type_id=25`, activo — confirmado por M1 | Al aprobar o rechazar una solicitud |
|
| 249 |
+
| `ALTA_MONITOREO` | M9 Monitoreo | `POST /webhooks/internacion/alta-monitoreo` (REST); evento `event_type_id=26`, activo — confirmado por M9. Payload incluye `cama_id` (destino) | Al asignar cama (ingreso o destino de traslado) |
|
| 250 |
+
| `BAJA_MONITOREO` | M9 Monitoreo | `POST /webhooks/internacion/baja-monitoreo` (REST); evento `event_type_id=27`, activo — confirmado por M9. Payload incluye `cama_id` (origen) | Al dar el alta o al trasladar (cama origen) |
|
| 251 |
| `CAMA_LISTA` / `CIERRE_INTERNACION` | M7 Facturación | `POST /webhooks/internacion/cama-lista` (REST, fallback/testing); evento `facturacion.internacion.cama-lista.requested` (`event_type_id=19`, activo) | Al completar limpieza post-alta (`EN_LIMPIEZA → DISPONIBLE`) |
|
| 252 |
|
| 253 |
**M7 confirmó su integración por escrito** (`documentation/integrations/M7_integration.md`):
|
|
|
|
| 348 |
no hay hoy un canal async equivalente. Migrarla requiere antes acordar con M1 un evento de
|
| 349 |
respuesta (`correlation_id` + `response_event_id`). Sigue siendo solo REST.
|
| 350 |
|
| 351 |
+
**Lado saliente — los 4 `event_type_id` reales ya están activos.** Las 4 notificaciones de
|
| 352 |
+
§7.2 (`SOLICITUD_RESUELTA=25`, `ALTA_MONITOREO=26`, `BAJA_MONITOREO=27`, `CAMA_LISTA=19`)
|
| 353 |
+
siguen el mismo bus; el evento y la cola los crea y posee **el receptor** (M1/M9/M7), no M6
|
| 354 |
+
— por la misma regla del tutorial que aplica al revés en §7.1. Los 4 equipos ya
|
| 355 |
+
compartieron su id.
|
| 356 |
+
|
| 357 |
+
`app/integrations/core_events.py::publish_event(event_type_id, payload)` sigue siendo un
|
| 358 |
+
no-op explícito si algún `event_type_id is None` (mismo mecanismo, por si algún deploy no
|
| 359 |
+
tiene la variable cargada), pero en `.env` las 4 settings
|
| 360 |
+
(`hce_solicitud_resuelta_event_type_id`, `monitoreo_alta_event_type_id`,
|
| 361 |
+
`monitoreo_baja_event_type_id`, `facturacion_cama_lista_event_type_id`) ya tienen su valor
|
| 362 |
+
real. Las 4 funciones `notify_*` (`hce.notify_resultado_solicitud`,
|
| 363 |
+
`monitoreo.notify_alta`/`notify_baja`, `facturacion.notify_cama_lista`) hacen **dual-write**:
|
| 364 |
+
siguen llamando al webhook REST directo y además llaman a `publish_event`, que ahora sí
|
| 365 |
+
publica al bus real. `monitoreo.notify_alta`/`notify_baja` además llevan `cama_id` en el
|
| 366 |
+
payload desde esta corrección (2026-07) — destino en el alta, origen en la baja.
|
| 367 |
|
| 368 |
---
|
| 369 |
|
documentation/M6_EVENTOS_RABBITMQ.md
CHANGED
|
@@ -158,22 +158,23 @@ Los 4 puntos de notificación saliente de M6 (`M6_DISEÑO.md` §7.2) hacen **dua
|
|
| 158 |
|
| 159 |
| Función | Notificación | Receptor | Config del `event_type_id` | Estado |
|
| 160 |
|---|---|---|---|---|
|
| 161 |
-
| `hce.notify_resultado_solicitud` | `SOLICITUD_RESUELTA` | M1 HCE | `hce_solicitud_resuelta_event_type_id` |
|
| 162 |
-
| `monitoreo.notify_alta` | `ALTA_MONITOREO` | M9 Monitoreo | `monitoreo_alta_event_type_id` |
|
| 163 |
-
| `monitoreo.notify_baja` | `BAJA_MONITOREO` | M9 Monitoreo | `monitoreo_baja_event_type_id` |
|
| 164 |
| `facturacion.notify_cama_lista` | `CIERRE_INTERNACION` (`facturacion.internacion.cama-lista.requested`) | M7 Facturación | `facturacion_cama_lista_event_type_id` | **Activo — `event_type_id=19`, confirmado por escrito** |
|
| 165 |
|
| 166 |
El evento/cola de cada notificación lo crea y comparte el módulo receptor, no M6 (misma
|
| 167 |
-
regla que aplica al revés en §2.2).
|
| 168 |
-
—
|
| 169 |
-
el
|
| 170 |
-
|
| 171 |
-
`
|
| 172 |
-
`
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
|
|
|
| 177 |
|
| 178 |
**Corrección 2026-07 (auditoría contra el contrato real de M7):** una prueba end-to-end
|
| 179 |
contra el broker real mostró que el evento a M7 nunca salía (`facturacion_cama_lista_event_type_id`
|
|
@@ -228,12 +229,10 @@ RABBITMQ_PORT=5672
|
|
| 228 |
RABBITMQ_VHOST=/
|
| 229 |
INTERNACION_REQUESTS_QUEUE=internacion.requests
|
| 230 |
|
| 231 |
-
# Publisher saliente —
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
# MONITOREO_ALTA_EVENT_TYPE_ID=
|
| 236 |
-
# MONITOREO_BAJA_EVENT_TYPE_ID=
|
| 237 |
FACTURACION_CAMA_LISTA_EVENT_TYPE_ID=19
|
| 238 |
```
|
| 239 |
|
|
@@ -244,8 +243,8 @@ Las credenciales del broker (`login`/`password` en `aio_pika.connect_robust`) so
|
|
| 244 |
## 9. Pendientes
|
| 245 |
|
| 246 |
- **Host/puerto/vhost reales del broker RabbitMQ compartido** — sin esto, `RABBITMQ_CONSUMER_ENABLED=true` no puede conectar. Único bloqueante para que el consumer corra contra el broker de verdad.
|
| 247 |
-
-
|
| 248 |
-
-
|
| 249 |
- ~~`event_type_id` de M7 (`CAMA_LISTA`)~~ — **resuelto**: M7 confirmó `event_type_id=19`, ya activo.
|
| 250 |
- **`episodio_id` de M1** — pendiente que M1 agregue este campo a `internacion.solicitud.creada` (requerido para `tipo=INTERNACION`, ya no a `alta-medica` — ver corrección 2026-07 en §7 de este doc). Ver `M6_DISEÑO.md` §14 punto 50 y `documentation/M6_INTEGRACION_M1_HCE.md` §4.3.
|
| 251 |
- **Coordinar con M1/M9/M2 la migración de sus emisores** hacia los 5 eventos entrantes de §2.2, y una fecha de retiro de los webhooks REST equivalentes una vez confirmada.
|
|
|
|
| 158 |
|
| 159 |
| Función | Notificación | Receptor | Config del `event_type_id` | Estado |
|
| 160 |
|---|---|---|---|---|
|
| 161 |
+
| `hce.notify_resultado_solicitud` | `SOLICITUD_RESUELTA` | M1 HCE | `hce_solicitud_resuelta_event_type_id` | **Activo — `event_type_id=25`, confirmado por M1** |
|
| 162 |
+
| `monitoreo.notify_alta` | `ALTA_MONITOREO` | M9 Monitoreo | `monitoreo_alta_event_type_id` | **Activo — `event_type_id=26`, confirmado por M9** |
|
| 163 |
+
| `monitoreo.notify_baja` | `BAJA_MONITOREO` | M9 Monitoreo | `monitoreo_baja_event_type_id` | **Activo — `event_type_id=27`, confirmado por M9** |
|
| 164 |
| `facturacion.notify_cama_lista` | `CIERRE_INTERNACION` (`facturacion.internacion.cama-lista.requested`) | M7 Facturación | `facturacion_cama_lista_event_type_id` | **Activo — `event_type_id=19`, confirmado por escrito** |
|
| 165 |
|
| 166 |
El evento/cola de cada notificación lo crea y comparte el módulo receptor, no M6 (misma
|
| 167 |
+
regla que aplica al revés en §2.2). Los 4 ya están activos. Su payload es distinto entre sí
|
| 168 |
+
— ver `app/integrations/facturacion.py::notify_cama_lista` y `M6_DISEÑO.md` §7.2/§14.9 para
|
| 169 |
+
el detalle completo del de M7, incluido el bloqueante de `idEpisodioExterno`.
|
| 170 |
+
|
| 171 |
+
**Corrección 2026-07 (`cama_id` en los eventos de M9):** `ALTA_MONITOREO`/`BAJA_MONITOREO`
|
| 172 |
+
ahora llevan también `cama_id` en el payload — M9 lo necesita para saber a qué cama
|
| 173 |
+
corresponde el alta/baja de monitoreo. Regla de qué cama va en cada notificación: en un
|
| 174 |
+
ingreso, `notify_alta` lleva la cama destino; en un traslado, `notify_baja` lleva la cama
|
| 175 |
+
**origen** (la que el paciente deja) y `notify_alta` lleva la cama **destino** (la nueva);
|
| 176 |
+
en un alta médica, `notify_baja` lleva la cama que se libera. Ver
|
| 177 |
+
`app/integrations/monitoreo.py`.
|
| 178 |
|
| 179 |
**Corrección 2026-07 (auditoría contra el contrato real de M7):** una prueba end-to-end
|
| 180 |
contra el broker real mostró que el evento a M7 nunca salía (`facturacion_cama_lista_event_type_id`
|
|
|
|
| 229 |
RABBITMQ_VHOST=/
|
| 230 |
INTERNACION_REQUESTS_QUEUE=internacion.requests
|
| 231 |
|
| 232 |
+
# Publisher saliente — los 4 confirmados y activos:
|
| 233 |
+
HCE_SOLICITUD_RESUELTA_EVENT_TYPE_ID=25
|
| 234 |
+
MONITOREO_ALTA_EVENT_TYPE_ID=26
|
| 235 |
+
MONITOREO_BAJA_EVENT_TYPE_ID=27
|
|
|
|
|
|
|
| 236 |
FACTURACION_CAMA_LISTA_EVENT_TYPE_ID=19
|
| 237 |
```
|
| 238 |
|
|
|
|
| 243 |
## 9. Pendientes
|
| 244 |
|
| 245 |
- **Host/puerto/vhost reales del broker RabbitMQ compartido** — sin esto, `RABBITMQ_CONSUMER_ENABLED=true` no puede conectar. Único bloqueante para que el consumer corra contra el broker de verdad.
|
| 246 |
+
- ~~`event_type_id` de M1 (`SOLICITUD_RESUELTA`)~~ — **resuelto**: M1 confirmó `event_type_id=25`, ya activo.
|
| 247 |
+
- ~~`event_type_id` de M9 (`ALTA_MONITOREO`, `BAJA_MONITOREO`)~~ — **resuelto**: M9 confirmó `event_type_id=26`/`27`, ya activos.
|
| 248 |
- ~~`event_type_id` de M7 (`CAMA_LISTA`)~~ — **resuelto**: M7 confirmó `event_type_id=19`, ya activo.
|
| 249 |
- **`episodio_id` de M1** — pendiente que M1 agregue este campo a `internacion.solicitud.creada` (requerido para `tipo=INTERNACION`, ya no a `alta-medica` — ver corrección 2026-07 en §7 de este doc). Ver `M6_DISEÑO.md` §14 punto 50 y `documentation/M6_INTEGRACION_M1_HCE.md` §4.3.
|
| 250 |
- **Coordinar con M1/M9/M2 la migración de sus emisores** hacia los 5 eventos entrantes de §2.2, y una fecha de retiro de los webhooks REST equivalentes una vez confirmada.
|
documentation/M6_EVENTOS_REFERENCIA.md
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Eventos de M6 — referencia rápida
|
| 2 |
+
|
| 3 |
+
> Índice de un vistazo de todos los eventos del bus (Core/RabbitMQ) que entran y salen de
|
| 4 |
+
> M6. Para el detalle completo (infraestructura, envelope, consumer/publisher) ver
|
| 5 |
+
> [`M6_EVENTOS_RABBITMQ.md`](M6_EVENTOS_RABBITMQ.md).
|
| 6 |
+
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
## 📥 Entrantes (otros módulos → M6)
|
| 10 |
+
|
| 11 |
+
Todos llegan a la cola `internacion.requests` del Core. Fire-and-forget (no esperan respuesta).
|
| 12 |
+
|
| 13 |
+
| id | evento | emisor | qué es |
|
| 14 |
+
|----|--------|--------|--------|
|
| 15 |
+
| **14** | `internacion.solicitud.creada` | M1 HCE | Nueva solicitud de internación o traslado |
|
| 16 |
+
| **15** | `internacion.alta-medica.registrada` | M1 HCE | El médico dio el alta → liberar cama |
|
| 17 |
+
| **16** | `internacion.alerta-emergencia.detectada` | M9 Monitoreo | Emergencia del paciente → cama a CÓDIGO_ROJO |
|
| 18 |
+
| **17** | `internacion.alerta-resuelta.notificada` | M9 Monitoreo | Emergencia resuelta → cama vuelve a OCUPADA |
|
| 19 |
+
| **18** | `internacion.turno.cancelado` | M2 Turnos | Se canceló un turno de quirófano → liberar reserva |
|
| 20 |
+
|
| 21 |
+
**14 — solicitud.creada** (`SolicitudHceWebhook`)
|
| 22 |
+
```json
|
| 23 |
+
// INTERNACION
|
| 24 |
+
{
|
| 25 |
+
"tipo": "INTERNACION", "solicitud_hce_id": "HCE-123", "paciente_id": 22,
|
| 26 |
+
"medico_solicitante_id": 20, "episodio_id": 17, // requerido para INTERNACION
|
| 27 |
+
"cama_solicitada_id": 5, "origen": "GUARDIA", "turno_id": null,
|
| 28 |
+
"diagnostico_ingreso": "...", "obra_social_id": "OS-1", "numero_afiliado": "...",
|
| 29 |
+
"prioridad": "ALTA", "observaciones": null, "hospital_id": "1",
|
| 30 |
+
"timestamp": "2026-07-17T15:00:00Z"
|
| 31 |
+
}
|
| 32 |
+
// TRASLADO (no manda episodio_id: se hereda de la cama origen)
|
| 33 |
+
{
|
| 34 |
+
"tipo": "TRASLADO", "solicitud_hce_id": "HCE-124", "paciente_id": 22,
|
| 35 |
+
"medico_solicitante_id": 20, "cama_origen_id": 5,
|
| 36 |
+
"cama_destino_solicitada_id": 9, "motivo_traslado": "...",
|
| 37 |
+
"timestamp": "2026-07-17T15:00:00Z"
|
| 38 |
+
}
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
**15 — alta-medica.registrada** (`AltaMedicaWebhook`)
|
| 42 |
+
```json
|
| 43 |
+
{ "paciente_id": 22, "medico_firmante_id": 1, "tipo_alta": "ALTA_MEDICA",
|
| 44 |
+
"timestamp": "2026-07-17T15:00:00Z" }
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
**16 — alerta-emergencia.detectada** (`AlertaEmergenciaRequest`)
|
| 48 |
+
```json
|
| 49 |
+
{ "paciente_id": 22, "observaciones": "...", "timestamp": "2026-07-17T15:00:00Z" }
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
**17 — alerta-resuelta.notificada** (`AlertaResueltaRequest`)
|
| 53 |
+
```json
|
| 54 |
+
{ "paciente_id": 22, "motivo_resolucion": "...", "timestamp": "2026-07-17T15:00:00Z" }
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
**18 — turno.cancelado** (`CancelacionQuirofanoRequest` + `turno_id`)
|
| 58 |
+
```json
|
| 59 |
+
{ "turno_id": 88, "motivo": "...", "tipo_cancelacion": "...",
|
| 60 |
+
"timestamp": "2026-07-17T15:00:00Z" }
|
| 61 |
+
```
|
| 62 |
+
> En REST el `turno_id` va en el path; por el bus **debe** ir dentro del payload.
|
| 63 |
+
|
| 64 |
+
---
|
| 65 |
+
|
| 66 |
+
## 📤 Salientes (M6 → otros módulos)
|
| 67 |
+
|
| 68 |
+
| id | evento | receptor | qué es |
|
| 69 |
+
|----|--------|----------|--------|
|
| 70 |
+
| **25** | `SOLICITUD_RESUELTA` | M1 HCE | Resultado (APROBADA/RECHAZADA) de una solicitud |
|
| 71 |
+
| **26** | `ALTA_MONITOREO` | M9 Monitoreo | Paciente entra a monitoreo en una cama |
|
| 72 |
+
| **27** | `BAJA_MONITOREO` | M9 Monitoreo | Paciente sale de monitoreo de una cama |
|
| 73 |
+
| **19** | `CIERRE_INTERNACION` | M7 Facturación | Cama liberada tras alta → cerrar y facturar |
|
| 74 |
+
|
| 75 |
+
Los 4 están activos (dual-write: REST directo + evento del bus).
|
| 76 |
+
|
| 77 |
+
**25 — SOLICITUD_RESUELTA → M1** (`hce.notify_resultado_solicitud`)
|
| 78 |
+
```json
|
| 79 |
+
{ "solicitud_hce_id": "HCE-123", "resultado": "APROBADA",
|
| 80 |
+
"motivo": null, "timestamp": "2026-07-17T15:00:00Z" }
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
**26/27 — ALTA_MONITOREO / BAJA_MONITOREO → M9** (`monitoreo.notify_alta` / `notify_baja`)
|
| 84 |
+
```json
|
| 85 |
+
{ "evento": "ALTA_MONITOREO", "paciente_id": 22, "cama_id": 9, "timestamp": "..." }
|
| 86 |
+
{ "evento": "BAJA_MONITOREO", "paciente_id": 22, "cama_id": 5, "timestamp": "..." }
|
| 87 |
+
```
|
| 88 |
+
> Regla de `cama_id`: ingreso → cama destino (alta) · traslado → baja(cama origen) +
|
| 89 |
+
> alta(cama destino) · alta médica → cama liberada (baja).
|
| 90 |
+
|
| 91 |
+
**19 — CIERRE_INTERNACION → M7** (`facturacion.notify_cama_lista`)
|
| 92 |
+
```json
|
| 93 |
+
{
|
| 94 |
+
"evento": "CIERRE_INTERNACION",
|
| 95 |
+
"idEventoExterno": "M6-CIERRE-INT-9-22-2026-07-17", // clave de idempotencia
|
| 96 |
+
"idInternacionExterna": "HCE-123", "idEpisodioExterno": 17,
|
| 97 |
+
"idPacienteExterno": 22, "fechaIngreso": "...Z", "fechaAlta": "...Z",
|
| 98 |
+
"tipoAlta": "ALTA_MEDICA", "timestampEvento": "...Z"
|
| 99 |
+
}
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
> **No van al bus** (REST puro a M1): `hce.notify_movimiento` (`/hce/movimientos`) y
|
| 103 |
+
> `hce.notify_evento_episodio` (`/hce/episodios/{id}/eventos`). Cirugía urgente también es
|
| 104 |
+
> solo REST.
|
| 105 |
+
|
| 106 |
+
---
|
| 107 |
+
|
| 108 |
+
## Ids — resumen
|
| 109 |
+
|
| 110 |
+
| Dirección | evento | id |
|
| 111 |
+
|-----------|--------|----|
|
| 112 |
+
| Entrante | solicitud.creada / alta-medica / alerta-emergencia / alerta-resuelta / turno-cancelado | **14 / 15 / 16 / 17 / 18** |
|
| 113 |
+
| Saliente | SOLICITUD_RESUELTA (M1) | **25** |
|
| 114 |
+
| Saliente | ALTA_MONITOREO / BAJA_MONITOREO (M9) | **26 / 27** |
|
| 115 |
+
| Saliente | CIERRE_INTERNACION (M7) | **19** |
|
tests/test_core_events.py
CHANGED
|
@@ -96,10 +96,11 @@ def test_notify_alta_sin_event_type_id_usa_rest_como_backup(monkeypatch):
|
|
| 96 |
lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True,
|
| 97 |
)
|
| 98 |
|
| 99 |
-
ok = monitoreo.notify_alta(7)
|
| 100 |
|
| 101 |
assert ok is True
|
| 102 |
assert len(rest_calls) == 1
|
|
|
|
| 103 |
assert len(publish_calls) == 0 # no se llama publish_event cuando event_type_id es None
|
| 104 |
|
| 105 |
|
|
@@ -118,13 +119,54 @@ def test_notify_baja_sin_event_type_id_usa_rest_como_backup(monkeypatch):
|
|
| 118 |
lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True,
|
| 119 |
)
|
| 120 |
|
| 121 |
-
ok = monitoreo.notify_baja(7)
|
| 122 |
|
| 123 |
assert ok is True
|
| 124 |
assert len(rest_calls) == 1
|
|
|
|
| 125 |
assert len(publish_calls) == 0 # no se llama publish_event cuando event_type_id es None
|
| 126 |
|
| 127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
def test_notify_cama_lista_sigue_llamando_rest_con_payload_minimo(monkeypatch):
|
| 129 |
"""El REST directo es fallback/testing manual según M7 — payload mínimo, sin cambios."""
|
| 130 |
monkeypatch.setattr(settings, "mock_external_services", False)
|
|
|
|
| 96 |
lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True,
|
| 97 |
)
|
| 98 |
|
| 99 |
+
ok = monitoreo.notify_alta(7, cama_id=9)
|
| 100 |
|
| 101 |
assert ok is True
|
| 102 |
assert len(rest_calls) == 1
|
| 103 |
+
assert rest_calls[0][1]["cama_id"] == 9
|
| 104 |
assert len(publish_calls) == 0 # no se llama publish_event cuando event_type_id es None
|
| 105 |
|
| 106 |
|
|
|
|
| 119 |
lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True,
|
| 120 |
)
|
| 121 |
|
| 122 |
+
ok = monitoreo.notify_baja(7, cama_id=9)
|
| 123 |
|
| 124 |
assert ok is True
|
| 125 |
assert len(rest_calls) == 1
|
| 126 |
+
assert rest_calls[0][1]["cama_id"] == 9
|
| 127 |
assert len(publish_calls) == 0 # no se llama publish_event cuando event_type_id es None
|
| 128 |
|
| 129 |
|
| 130 |
+
def test_notify_alta_con_event_type_id_publica_al_bus_con_cama_id(monkeypatch):
|
| 131 |
+
"""Con monitoreo_alta_event_type_id=26 configurado (id real de M9), publica al bus con
|
| 132 |
+
cama_id incluido en el payload."""
|
| 133 |
+
monkeypatch.setattr(settings, "mock_external_services", False)
|
| 134 |
+
monkeypatch.setattr(settings, "monitoreo_alta_event_type_id", 26)
|
| 135 |
+
publish_calls = []
|
| 136 |
+
monkeypatch.setattr(
|
| 137 |
+
"app.integrations.core_events.publish_event",
|
| 138 |
+
lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True,
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
ok = monitoreo.notify_alta(7, cama_id=9)
|
| 142 |
+
|
| 143 |
+
assert ok is True
|
| 144 |
+
assert len(publish_calls) == 1
|
| 145 |
+
event_type_id, payload = publish_calls[0]
|
| 146 |
+
assert event_type_id == 26
|
| 147 |
+
assert payload["cama_id"] == 9
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def test_notify_baja_con_event_type_id_publica_al_bus_con_cama_id(monkeypatch):
|
| 151 |
+
"""Con monitoreo_baja_event_type_id=27 configurado (id real de M9), publica al bus con
|
| 152 |
+
cama_id incluido en el payload."""
|
| 153 |
+
monkeypatch.setattr(settings, "mock_external_services", False)
|
| 154 |
+
monkeypatch.setattr(settings, "monitoreo_baja_event_type_id", 27)
|
| 155 |
+
publish_calls = []
|
| 156 |
+
monkeypatch.setattr(
|
| 157 |
+
"app.integrations.core_events.publish_event",
|
| 158 |
+
lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
ok = monitoreo.notify_baja(7, cama_id=9)
|
| 162 |
+
|
| 163 |
+
assert ok is True
|
| 164 |
+
assert len(publish_calls) == 1
|
| 165 |
+
event_type_id, payload = publish_calls[0]
|
| 166 |
+
assert event_type_id == 27
|
| 167 |
+
assert payload["cama_id"] == 9
|
| 168 |
+
|
| 169 |
+
|
| 170 |
def test_notify_cama_lista_sigue_llamando_rest_con_payload_minimo(monkeypatch):
|
| 171 |
"""El REST directo es fallback/testing manual según M7 — payload mínimo, sin cambios."""
|
| 172 |
monkeypatch.setattr(settings, "mock_external_services", False)
|
tests/test_solicitudes.py
CHANGED
|
@@ -188,6 +188,34 @@ def test_aprobar_traslado_hereda_episodio_de_la_cama_origen(monkeypatch):
|
|
| 188 |
assert cama_destino.episodio_id == 500
|
| 189 |
|
| 190 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
def test_aprobar_traslado_paciente_invalido_en_core_502(monkeypatch):
|
| 192 |
"""Health check M6 §A2: el traslado también valida el paciente contra el Core,
|
| 193 |
igual que la internación — antes de esta corrección no se validaba."""
|
|
|
|
| 188 |
assert cama_destino.episodio_id == 500
|
| 189 |
|
| 190 |
|
| 191 |
+
def test_aprobar_traslado_notifica_monitoreo_con_cama_origen_y_destino(monkeypatch):
|
| 192 |
+
"""La baja de monitoreo lleva la cama que el paciente DEJA (origen); el alta lleva la
|
| 193 |
+
cama nueva (destino) — así M9 sabe exactamente qué cama libera y cuál ocupa."""
|
| 194 |
+
cama_origen = make_cama(id=101, estado="OCUPADA")
|
| 195 |
+
cama_destino = make_cama(id=202, estado="DISPONIBLE")
|
| 196 |
+
sol = make_solicitud(
|
| 197 |
+
tipo="TRASLADO", solicitud_hce_id="HCE-SOL-TRASLADO", cama_origen_id=101, cama_destino_solicitada_id=202,
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
def _get_cama(db, cid):
|
| 201 |
+
return cama_origen if cid == 101 else cama_destino
|
| 202 |
+
|
| 203 |
+
monkeypatch.setattr("app.crud.cama.get_by_id", _get_cama)
|
| 204 |
+
monkeypatch.setattr("app.crud.cama.save", lambda db, c: c)
|
| 205 |
+
monkeypatch.setattr("app.integrations.hce.get_contraindicaciones", lambda pid: [])
|
| 206 |
+
monkeypatch.setattr("app.integrations.hce.notify_movimiento", lambda *a, **k: None)
|
| 207 |
+
monkeypatch.setattr("app.integrations.hce.notify_resultado_solicitud", lambda *a, **k: None)
|
| 208 |
+
baja_calls = []
|
| 209 |
+
alta_calls = []
|
| 210 |
+
monkeypatch.setattr("app.integrations.monitoreo.notify_baja", lambda pid, cama_id=None: baja_calls.append(cama_id))
|
| 211 |
+
monkeypatch.setattr("app.integrations.monitoreo.notify_alta", lambda pid, cama_id=None: alta_calls.append(cama_id))
|
| 212 |
+
|
| 213 |
+
solicitud_service._aprobar_traslado(MagicMock(), sol, None, None, resuelto_por=1, accion="APROBAR")
|
| 214 |
+
|
| 215 |
+
assert baja_calls == [101]
|
| 216 |
+
assert alta_calls == [202]
|
| 217 |
+
|
| 218 |
+
|
| 219 |
def test_aprobar_traslado_paciente_invalido_en_core_502(monkeypatch):
|
| 220 |
"""Health check M6 §A2: el traslado también valida el paciente contra el Core,
|
| 221 |
igual que la internación — antes de esta corrección no se validaba."""
|