Merge branch 'main' into jps/integracion-M10
Browse files- .env.example +29 -0
- .github/workflows/reservas-tick.yml +15 -0
- app/config.py +65 -0
- app/crud/cama.py +6 -0
- app/crud/reserva.py +27 -0
- app/integrations/core_events.py +38 -0
- app/integrations/facturacion.py +127 -36
- app/integrations/hce.py +17 -2
- app/integrations/monitoreo.py +14 -2
- app/integrations/rabbit_consumer.py +134 -0
- app/main.py +16 -1
- app/models/cama.py +16 -0
- app/routers/internal.py +43 -0
- app/routers/webhooks.py +1 -1
- app/services/cama_service.py +42 -2
- app/services/solicitud_service.py +28 -14
- documentation/M6_DISEÑO.md +122 -10
- documentation/M6_demo_payloads.md +0 -291
- documentation/integracion_m7_estado.md +287 -0
- documentation/{M10_SSO_INTEGRATION_GUIDE.md → integrations/M10_SSO_INTEGRATION_GUIDE.md} +0 -0
- documentation/{M10_integration.md → integrations/M10_integration.md} +0 -0
- documentation/integrations/M7_integration.md +101 -0
- documentation/{M10_openapi.yaml → integrations/openapi_docs/M10_openapi.yaml} +0 -0
- documentation/{M1_docs.html → integrations/openapi_docs/M1_docs.html} +0 -0
- documentation/{M2_openapi.json → integrations/openapi_docs/M2_openapi.json} +0 -0
- requirements.txt +1 -0
- tests/factories.py +4 -0
- tests/test_config.py +42 -0
- tests/test_core_events.py +194 -0
- tests/test_internal.py +41 -0
- tests/test_rabbit_consumer.py +180 -0
- tests/test_reserva_scheduler.py +108 -0
- tests/test_solicitudes.py +61 -0
- tests/test_webhooks.py +45 -0
.env.example
CHANGED
|
@@ -43,3 +43,32 @@ M2_TURNOS_URL=http://modulo2:8002
|
|
| 43 |
M7_FACTURACION_URL=http://modulo7:8007
|
| 44 |
M9_MONITOREO_URL=http://modulo9:8009
|
| 45 |
M10_CORE_URL=http://modulo10:8010
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
M7_FACTURACION_URL=http://modulo7:8007
|
| 44 |
M9_MONITOREO_URL=http://modulo9:8009
|
| 45 |
M10_CORE_URL=http://modulo10:8010
|
| 46 |
+
|
| 47 |
+
# ─── Bus de eventos del Core (M10) ─────────────────────────────────────────
|
| 48 |
+
# RABBITMQ_CONSUMER_ENABLED=true levanta el consumer de internacion.requests
|
| 49 |
+
# (cola + 5 event types ya dados de alta en el Core, ver M6_DISEÑO.md §7).
|
| 50 |
+
# Las credenciales del broker son CORE_SERVICE_EMAIL/CORE_SERVICE_PASSWORD.
|
| 51 |
+
RABBITMQ_CONSUMER_ENABLED=false
|
| 52 |
+
RABBITMQ_HOST=localhost
|
| 53 |
+
RABBITMQ_PORT=5672
|
| 54 |
+
RABBITMQ_VHOST=/
|
| 55 |
+
INTERNACION_REQUESTS_QUEUE=internacion.requests
|
| 56 |
+
|
| 57 |
+
# event_type_id de las notificaciones salientes de M6. Cada uno lo crea y
|
| 58 |
+
# comparte el módulo receptor (M1/M9/M7). Dejar comentado hasta tener el ID
|
| 59 |
+
# real: pydantic-settings no trata "KEY=" vacío como None, tira ValidationError.
|
| 60 |
+
# M7 ya confirmó el suyo por escrito (documentation/integrations/M7_integration.md,
|
| 61 |
+
# event_type_id=19) — se activa descomentando y completando, igual que se hará acá
|
| 62 |
+
# cuando M1/M9 confirmen los suyos.
|
| 63 |
+
# HCE_SOLICITUD_RESUELTA_EVENT_TYPE_ID=
|
| 64 |
+
# MONITOREO_ALTA_EVENT_TYPE_ID=
|
| 65 |
+
# MONITOREO_BAJA_EVENT_TYPE_ID=
|
| 66 |
+
# FACTURACION_CAMA_LISTA_EVENT_TYPE_ID=
|
| 67 |
+
|
| 68 |
+
# ─── Endpoint interno: auto-transición de reservas de quirófano ────────────
|
| 69 |
+
# POST /api/v1/internal/reservas/tick avanza RESERVADA→EN_CURSO→COMPLETADA
|
| 70 |
+
# según el horario de cada reserva. Lo llama un cron externo (GitHub
|
| 71 |
+
# Actions/cron-job.org), no un scheduler interno — ver M6_DISEÑO.md §5.4.
|
| 72 |
+
# Generar con: python -c "import secrets; print(secrets.token_hex(32))"
|
| 73 |
+
# Vacío por default: el endpoint rechaza todo (falla cerrado).
|
| 74 |
+
INTERNAL_TICK_SECRET=
|
.github/workflows/reservas-tick.yml
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Reservas Tick
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
schedule:
|
| 5 |
+
- cron: "*/5 * * * *" # cada 5 min — mínimo práctico de GitHub Actions
|
| 6 |
+
workflow_dispatch: {} # permite disparar el tick a mano desde la pestaña Actions
|
| 7 |
+
|
| 8 |
+
jobs:
|
| 9 |
+
tick:
|
| 10 |
+
runs-on: ubuntu-latest
|
| 11 |
+
steps:
|
| 12 |
+
- name: POST /internal/reservas/tick
|
| 13 |
+
run: |
|
| 14 |
+
curl -sf -X POST "${{ vars.M6_URL }}/api/v1/internal/reservas/tick" \
|
| 15 |
+
-H "X-Internal-Token: ${{ secrets.M6_INTERNAL_TICK_SECRET }}"
|
app/config.py
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from pydantic_settings import BaseSettings, SettingsConfigDict
|
| 2 |
|
| 3 |
|
|
@@ -8,6 +11,30 @@ class Settings(BaseSettings):
|
|
| 8 |
extra="ignore",
|
| 9 |
)
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
# Base de datos (Supabase)
|
| 12 |
supabase_url: str
|
| 13 |
supabase_key: str
|
|
@@ -52,5 +79,43 @@ class Settings(BaseSettings):
|
|
| 52 |
# Si True, no llama a módulos externos (útil para desarrollo local sin stack completo)
|
| 53 |
mock_external_services: bool = True
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
settings = Settings()
|
|
|
|
| 1 |
+
from typing import get_args
|
| 2 |
+
|
| 3 |
+
from pydantic import model_validator
|
| 4 |
from pydantic_settings import BaseSettings, SettingsConfigDict
|
| 5 |
|
| 6 |
|
|
|
|
| 11 |
extra="ignore",
|
| 12 |
)
|
| 13 |
|
| 14 |
+
@model_validator(mode="before")
|
| 15 |
+
@classmethod
|
| 16 |
+
def _blank_non_str_env_vars_fall_back_to_default(cls, data):
|
| 17 |
+
"""
|
| 18 |
+
Una variable de entorno declarada pero vacía ("") llega a pydantic-settings
|
| 19 |
+
como si el usuario hubiese provisto ese valor, no como "no seteada" — para
|
| 20 |
+
un campo no-string (int, bool, int | None) eso rompe el arranque entero
|
| 21 |
+
(`ValidationError` en `Settings()`, que tira abajo `main.py` antes de
|
| 22 |
+
levantar cualquier endpoint). Ya pasó dos veces en producción: con los
|
| 23 |
+
`*_event_type_id` y con `RABBITMQ_PORT`/`RABBITMQ_CONSUMER_ENABLED`.
|
| 24 |
+
|
| 25 |
+
Para un campo no-string, "" nunca es un valor válido de todos modos —
|
| 26 |
+
tratarlo como ausente y caer al default declarado es siempre seguro. Los
|
| 27 |
+
campos `str` (`core_service_email`, `internal_tick_secret`, etc.) no se
|
| 28 |
+
tocan: para esos, `""` ya es su semántica normal de "no configurado".
|
| 29 |
+
"""
|
| 30 |
+
if not isinstance(data, dict):
|
| 31 |
+
return data
|
| 32 |
+
cleaned = dict(data)
|
| 33 |
+
for name, field in cls.model_fields.items():
|
| 34 |
+
if cleaned.get(name) == "" and str not in (field.annotation, *get_args(field.annotation)):
|
| 35 |
+
cleaned.pop(name)
|
| 36 |
+
return cleaned
|
| 37 |
+
|
| 38 |
# Base de datos (Supabase)
|
| 39 |
supabase_url: str
|
| 40 |
supabase_key: str
|
|
|
|
| 79 |
# Si True, no llama a módulos externos (útil para desarrollo local sin stack completo)
|
| 80 |
mock_external_services: bool = True
|
| 81 |
|
| 82 |
+
# ─── Bus de eventos del Core (M10): entrante ────────────────────────────
|
| 83 |
+
# M6 consume su propia cola de requests (`app/integrations/rabbit_consumer.py`),
|
| 84 |
+
# creada una vez en el Core (`POST /rabbit/queues`) — ver `M6_DISEÑO.md` §7.
|
| 85 |
+
# Las credenciales son las mismas que la cuenta de servicio ya usa contra el
|
| 86 |
+
# Core (`core_service_email`/`core_service_password`): ese email ya está
|
| 87 |
+
# provisionado como usuario de RabbitMQ. Host/puerto/vhost del broker
|
| 88 |
+
# compartido quedan pendientes de conseguir con el equipo de Core.
|
| 89 |
+
rabbitmq_host: str = "localhost"
|
| 90 |
+
rabbitmq_port: int = 5672
|
| 91 |
+
rabbitmq_vhost: str = "/"
|
| 92 |
+
internacion_requests_queue: str = "internacion.requests"
|
| 93 |
+
|
| 94 |
+
# Apaga el consumer por default: sin esto, dev/tests intentarían conectar contra
|
| 95 |
+
# `rabbitmq_host` (default "localhost") en cada arranque de la app, sin necesidad.
|
| 96 |
+
# Activar cuando se tenga el host/puerto/vhost real del broker compartido.
|
| 97 |
+
rabbitmq_consumer_enabled: bool = False
|
| 98 |
+
|
| 99 |
+
# ─── Bus de eventos del Core (M10): saliente ────────────────────────────
|
| 100 |
+
# `event_type_id` de las notificaciones que M6 publica hacia M1/M9/M7
|
| 101 |
+
# (`app/integrations/core_events.py::publish_event`). Cada uno lo crea y
|
| 102 |
+
# posee el módulo receptor, no M6 — quedan en `None` hasta que compartan el
|
| 103 |
+
# ID real. Mientras sea `None`, `publish_event` no dispara ningún request;
|
| 104 |
+
# la notificación sigue saliendo solo por el webhook REST directo actual.
|
| 105 |
+
hce_solicitud_resuelta_event_type_id: int | None = None
|
| 106 |
+
monitoreo_alta_event_type_id: int | None = None
|
| 107 |
+
monitoreo_baja_event_type_id: int | None = None
|
| 108 |
+
facturacion_cama_lista_event_type_id: int | None = None
|
| 109 |
+
|
| 110 |
+
# ─── Endpoints internos (sistema, no usuario) ──────────────────────────
|
| 111 |
+
# POST /api/v1/internal/reservas/tick (app/routers/internal.py) avanza
|
| 112 |
+
# automáticamente RESERVADA→EN_CURSO→COMPLETADA según el horario de cada
|
| 113 |
+
# reserva de quirófano. No hay un usuario humano detrás de esa llamada (la
|
| 114 |
+
# dispara un cron externo, ver M6_DISEÑO.md §5.4) — se protege con este
|
| 115 |
+
# secreto compartido en vez de un JWT de sesión. Vacío por default: el
|
| 116 |
+
# endpoint rechaza todo (falla cerrado). Generar con
|
| 117 |
+
# `python -c "import secrets; print(secrets.token_hex(32))"`.
|
| 118 |
+
internal_tick_secret: str = ""
|
| 119 |
+
|
| 120 |
|
| 121 |
settings = Settings()
|
app/crud/cama.py
CHANGED
|
@@ -61,6 +61,12 @@ def save(db: Client, cama: Cama) -> Cama:
|
|
| 61 |
"contraindicaciones_incompatibles": cama.contraindicaciones_incompatibles,
|
| 62 |
"ultima_actualizacion": cama.ultima_actualizacion.isoformat() if cama.ultima_actualizacion else None,
|
| 63 |
"ultimo_movimiento_tipo": cama.ultimo_movimiento_tipo,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
}
|
| 65 |
db.table(_TABLE).update(updates).eq("id", cama.id).execute()
|
| 66 |
return cama
|
|
|
|
| 61 |
"contraindicaciones_incompatibles": cama.contraindicaciones_incompatibles,
|
| 62 |
"ultima_actualizacion": cama.ultima_actualizacion.isoformat() if cama.ultima_actualizacion else None,
|
| 63 |
"ultimo_movimiento_tipo": cama.ultimo_movimiento_tipo,
|
| 64 |
+
# Datos del episodio en curso (ver app/models/cama.py) — necesarios para el
|
| 65 |
+
# payload rico que pide M7 en notify_cama_lista.
|
| 66 |
+
"solicitud_hce_id": cama.solicitud_hce_id,
|
| 67 |
+
"fecha_ingreso": cama.fecha_ingreso.isoformat() if cama.fecha_ingreso else None,
|
| 68 |
+
"alta_tipo": cama.alta_tipo,
|
| 69 |
+
"alta_timestamp": cama.alta_timestamp.isoformat() if cama.alta_timestamp else None,
|
| 70 |
}
|
| 71 |
db.table(_TABLE).update(updates).eq("id", cama.id).execute()
|
| 72 |
return cama
|
app/crud/reserva.py
CHANGED
|
@@ -107,6 +107,33 @@ def get_futuras(db: Client, cama_id: int, desde: datetime) -> list[ReservaQuirof
|
|
| 107 |
return [ReservaQuirofano.from_dict(row) for row in resp.data]
|
| 108 |
|
| 109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
def get_activa_por_turno(db: Client, turno_id: int) -> ReservaQuirofano | None:
|
| 111 |
resp = (
|
| 112 |
db.table(_TABLE)
|
|
|
|
| 107 |
return [ReservaQuirofano.from_dict(row) for row in resp.data]
|
| 108 |
|
| 109 |
|
| 110 |
+
def get_pendientes_de_inicio(db: Client, ahora: datetime) -> list[ReservaQuirofano]:
|
| 111 |
+
"""Reservas `RESERVADA` cuyo horario de inicio ya llegó — candidatas a pasar a
|
| 112 |
+
`EN_CURSO` automáticamente. Una reserva `CANCELADA` nunca aparece acá: el filtro por
|
| 113 |
+
estado ya resuelve "si no se canceló, arranca sola" sin lógica adicional."""
|
| 114 |
+
resp = (
|
| 115 |
+
db.table(_TABLE)
|
| 116 |
+
.select("*")
|
| 117 |
+
.eq("estado", "RESERVADA")
|
| 118 |
+
.lte("fecha_hora_inicio", ahora.isoformat())
|
| 119 |
+
.execute()
|
| 120 |
+
)
|
| 121 |
+
return [ReservaQuirofano.from_dict(row) for row in resp.data]
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def get_pendientes_de_fin(db: Client, ahora: datetime) -> list[ReservaQuirofano]:
|
| 125 |
+
"""Reservas `EN_CURSO` cuyo horario de fin estimado ya llegó — candidatas a pasar a
|
| 126 |
+
`COMPLETADA` automáticamente."""
|
| 127 |
+
resp = (
|
| 128 |
+
db.table(_TABLE)
|
| 129 |
+
.select("*")
|
| 130 |
+
.eq("estado", "EN_CURSO")
|
| 131 |
+
.lte("fecha_hora_fin_estimada", ahora.isoformat())
|
| 132 |
+
.execute()
|
| 133 |
+
)
|
| 134 |
+
return [ReservaQuirofano.from_dict(row) for row in resp.data]
|
| 135 |
+
|
| 136 |
+
|
| 137 |
def get_activa_por_turno(db: Client, turno_id: int) -> ReservaQuirofano | None:
|
| 138 |
resp = (
|
| 139 |
db.table(_TABLE)
|
app/integrations/core_events.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Publicación de eventos salientes al bus del Core (M10): `POST /events/log`.
|
| 3 |
+
|
| 4 |
+
Cada notificación saliente de M6 (SOLICITUD_RESUELTA a M1, ALTA_MONITOREO/
|
| 5 |
+
BAJA_MONITOREO a M9, CAMA_LISTA a M7) apunta a un `event_type_id` que crea y
|
| 6 |
+
posee el módulo receptor, no M6 (ver `M6_DISEÑO.md` §7). Hasta que cada equipo
|
| 7 |
+
comparta su ID real, la settings correspondiente queda en `None` y
|
| 8 |
+
`publish_event` es un no-op explícito — no bloquea el flujo de negocio ni
|
| 9 |
+
genera tráfico contra el Core. El día que llegue el ID real, alcanza con
|
| 10 |
+
cargarlo en config: el código no cambia.
|
| 11 |
+
"""
|
| 12 |
+
import json
|
| 13 |
+
import logging
|
| 14 |
+
|
| 15 |
+
from app.config import settings
|
| 16 |
+
from app.integrations._base import _post
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def publish_event(event_type_id: int | None, payload: dict, publisher_module: str = "internacion") -> bool:
|
| 22 |
+
"""
|
| 23 |
+
`publisher_module` default `"internacion"` para los eventos que M1/M9 todavía no
|
| 24 |
+
documentaron con un valor propio. M7 sí lo confirmó por escrito: espera
|
| 25 |
+
`"modulo_6"` (ver `app/integrations/facturacion.py::notify_cama_lista`).
|
| 26 |
+
"""
|
| 27 |
+
if event_type_id is None:
|
| 28 |
+
logger.info(
|
| 29 |
+
"Evento no publicado (event_type_id todavía no configurado): %s", payload
|
| 30 |
+
)
|
| 31 |
+
return True
|
| 32 |
+
|
| 33 |
+
body = {
|
| 34 |
+
"event_type_id": event_type_id,
|
| 35 |
+
"publisher_module": publisher_module,
|
| 36 |
+
"payload": json.dumps(payload),
|
| 37 |
+
}
|
| 38 |
+
return _post(f"{settings.m10_core_url}/events/log", body) is not None
|
app/integrations/facturacion.py
CHANGED
|
@@ -1,60 +1,151 @@
|
|
| 1 |
"""
|
| 2 |
-
M7 Facturación — notificación de
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
M7
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
"""
|
| 8 |
from datetime import date, datetime, timezone
|
| 9 |
|
|
|
|
|
|
|
| 10 |
from app.config import settings
|
|
|
|
| 11 |
from app.integrations._base import _post
|
|
|
|
|
|
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
|
|
|
|
| 15 |
"""
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
(cama + paciente + fecha del alta) para que un reintento del mismo evento no genere un
|
| 20 |
alta duplicada en facturación.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
"""
|
| 22 |
if settings.mock_external_services:
|
| 23 |
return True
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
| 26 |
"evento": "CAMA_LISTA",
|
| 27 |
"idEventoExterno": id_evento_externo,
|
| 28 |
-
"
|
| 29 |
-
"
|
| 30 |
-
"
|
| 31 |
}
|
| 32 |
-
|
| 33 |
-
f"{settings.m7_facturacion_url}/api/v1/webhooks/internacion/cama-lista",
|
| 34 |
) is not None
|
| 35 |
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
Avisa a M7 que debe cerrar la facturación de la cama tras un alta médica.
|
| 40 |
-
|
| 41 |
-
Se invoca ANTES del cambio de estado de la cama: el alta depende de que M7 confirme
|
| 42 |
-
el cierre. `idEventoExterno` es la clave de idempotencia (cama + paciente + fecha).
|
| 43 |
-
"""
|
| 44 |
-
if settings.mock_external_services:
|
| 45 |
-
print(
|
| 46 |
-
f"[SIMULACION] Request a M7 Facturación → cierre de cama "
|
| 47 |
-
f"{cama_id} (paciente {paciente_id})"
|
| 48 |
-
)
|
| 49 |
-
return True
|
| 50 |
-
id_evento_externo = f"M6-CIERRE-CAMA-{cama_id}-{paciente_id}-{date.today().isoformat()}"
|
| 51 |
-
payload = {
|
| 52 |
-
"evento": "CIERRE_CAMA",
|
| 53 |
"idEventoExterno": id_evento_externo,
|
| 54 |
-
"
|
| 55 |
-
"
|
| 56 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
}
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
)
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
M7 Facturación — notificación de cierre de internación para facturar.
|
| 3 |
|
| 4 |
+
Dos canales, con payloads DISTINTOS (ver `notify_cama_lista`):
|
| 5 |
+
- REST directo (`POST /api/v1/webhooks/internacion/cama-lista`): fallback/testing manual
|
| 6 |
+
según M7 (`documentation/integrations/M7_integration.md`) — payload mínimo.
|
| 7 |
+
- Evento del Core (`facturacion.internacion.cama-lista.requested`, `event_type_id=19`):
|
| 8 |
+
la integración final confirmada por M7 — payload rico (`CIERRE_INTERNACION`), con datos
|
| 9 |
+
del episodio que M6 empezó a persistir en la propia fila de `Cama` (ver
|
| 10 |
+
`app/models/cama.py`) precisamente para poder armar este evento.
|
| 11 |
"""
|
| 12 |
from datetime import date, datetime, timezone
|
| 13 |
|
| 14 |
+
from supabase import Client
|
| 15 |
+
|
| 16 |
from app.config import settings
|
| 17 |
+
from app.integrations import core_events
|
| 18 |
from app.integrations._base import _post
|
| 19 |
+
from app.models.cama import Cama
|
| 20 |
+
|
| 21 |
|
| 22 |
+
def _tramo_desde_cama(cama: Cama) -> list[dict]:
|
| 23 |
+
"""Fallback: un único tramo con los datos de la cama final del episodio."""
|
| 24 |
+
return [{
|
| 25 |
+
"camaId": str(cama.id),
|
| 26 |
+
"sector": cama.sector,
|
| 27 |
+
"tipoCama": cama.tipo,
|
| 28 |
+
"desde": cama.fecha_ingreso.isoformat() if cama.fecha_ingreso else None,
|
| 29 |
+
"hasta": cama.alta_timestamp.isoformat() if cama.alta_timestamp else None,
|
| 30 |
+
}]
|
| 31 |
|
| 32 |
+
|
| 33 |
+
def _reconstruir_tramos(db: Client, paciente_id: int, cama: Cama) -> list[dict]:
|
| 34 |
"""
|
| 35 |
+
Reconstruye los tramos de uso de cama del episodio desde la tabla de auditoría.
|
| 36 |
+
|
| 37 |
+
Estrategia: cada evento CAMA_ASIGNADA abre un tramo; el siguiente CAMA_ASIGNADA lo
|
| 38 |
+
cierra. El último tramo cierra en CAMA_ALTA (o alta_timestamp de la cama como
|
| 39 |
+
fallback). Solo se consideran eventos a partir de fecha_ingreso del episodio para
|
| 40 |
+
no mezclar con hospitalizaciones previas del mismo paciente.
|
| 41 |
+
|
| 42 |
+
Ante cualquier fallo de DB o datos insuficientes cae a _tramo_desde_cama (un único
|
| 43 |
+
tramo con la cama actual).
|
| 44 |
+
"""
|
| 45 |
+
from app.crud import cama as cama_crud # import local para evitar ciclo
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
fecha_desde = cama.fecha_ingreso.isoformat() if cama.fecha_ingreso else None
|
| 49 |
+
q = (
|
| 50 |
+
db.table("auditoria")
|
| 51 |
+
.select("cama_id,evento,creado_en")
|
| 52 |
+
.eq("paciente_id", paciente_id)
|
| 53 |
+
.in_("evento", ["CAMA_ASIGNADA", "CAMA_ALTA"])
|
| 54 |
+
.order("creado_en")
|
| 55 |
+
)
|
| 56 |
+
if fecha_desde:
|
| 57 |
+
q = q.gte("creado_en", fecha_desde)
|
| 58 |
+
resp = q.execute()
|
| 59 |
+
eventos = resp.data or []
|
| 60 |
+
except Exception:
|
| 61 |
+
return _tramo_desde_cama(cama)
|
| 62 |
+
|
| 63 |
+
asignaciones = [e for e in eventos if e["evento"] == "CAMA_ASIGNADA"]
|
| 64 |
+
altas = [e for e in eventos if e["evento"] == "CAMA_ALTA"]
|
| 65 |
+
|
| 66 |
+
if not asignaciones:
|
| 67 |
+
return _tramo_desde_cama(cama)
|
| 68 |
+
|
| 69 |
+
fin_ultimo = (
|
| 70 |
+
altas[-1]["creado_en"] if altas
|
| 71 |
+
else (cama.alta_timestamp.isoformat() if cama.alta_timestamp else None)
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
tramos_raw = []
|
| 75 |
+
for i, asig in enumerate(asignaciones):
|
| 76 |
+
hasta = asignaciones[i + 1]["creado_en"] if i + 1 < len(asignaciones) else fin_ultimo
|
| 77 |
+
tramos_raw.append({"cama_id": asig["cama_id"], "desde": asig["creado_en"], "hasta": hasta})
|
| 78 |
+
|
| 79 |
+
result = []
|
| 80 |
+
for t in tramos_raw:
|
| 81 |
+
cid = t["cama_id"]
|
| 82 |
+
if cid == cama.id:
|
| 83 |
+
sector, tipo = cama.sector, cama.tipo
|
| 84 |
+
else:
|
| 85 |
+
try:
|
| 86 |
+
hist = cama_crud.get_by_id(db, cid)
|
| 87 |
+
sector = hist.sector if hist else cama.sector
|
| 88 |
+
tipo = hist.tipo if hist else cama.tipo
|
| 89 |
+
except Exception:
|
| 90 |
+
sector, tipo = cama.sector, cama.tipo
|
| 91 |
+
result.append({
|
| 92 |
+
"camaId": str(cid),
|
| 93 |
+
"sector": sector,
|
| 94 |
+
"tipoCama": tipo,
|
| 95 |
+
"desde": t["desde"],
|
| 96 |
+
"hasta": t["hasta"],
|
| 97 |
+
})
|
| 98 |
+
|
| 99 |
+
return result or _tramo_desde_cama(cama)
|
| 100 |
|
| 101 |
+
|
| 102 |
+
def notify_cama_lista(cama: Cama, db: Client) -> bool:
|
| 103 |
+
"""
|
| 104 |
+
Avisa a M7 que una cama quedó lista tras un alta — cierra la internación del lado de
|
| 105 |
+
facturación.
|
| 106 |
+
|
| 107 |
+
`idEventoExterno` es la clave de idempotencia que usa M7: se deriva de forma estable
|
| 108 |
(cama + paciente + fecha del alta) para que un reintento del mismo evento no genere un
|
| 109 |
alta duplicada en facturación.
|
| 110 |
+
|
| 111 |
+
El payload del evento del Core incluye `idEpisodioExterno: None` a propósito: M1
|
| 112 |
+
todavía no lo provee en `AltaMedicaWebhook` (pendiente de coordinar — ver
|
| 113 |
+
`M6_DISEÑO.md` §14 y `documentation/M6_INTEGRACION_M1_HCE.md`). M7 confirmó que sin
|
| 114 |
+
ese dato el evento queda pendiente de completar del lado de ellos, no se rechaza.
|
| 115 |
"""
|
| 116 |
if settings.mock_external_services:
|
| 117 |
return True
|
| 118 |
+
|
| 119 |
+
paciente_id = cama.paciente_id or 0
|
| 120 |
+
id_evento_externo = f"M6-CIERRE-INT-{cama.id}-{paciente_id}-{date.today().isoformat()}"
|
| 121 |
+
|
| 122 |
+
payload_rest = {
|
| 123 |
"evento": "CAMA_LISTA",
|
| 124 |
"idEventoExterno": id_evento_externo,
|
| 125 |
+
"camaId": str(cama.id),
|
| 126 |
+
"idPacienteExterno": paciente_id,
|
| 127 |
+
"timestampEvento": datetime.now(timezone.utc).isoformat(),
|
| 128 |
}
|
| 129 |
+
ok_rest = _post(
|
| 130 |
+
f"{settings.m7_facturacion_url}/api/v1/webhooks/internacion/cama-lista", payload_rest
|
| 131 |
) is not None
|
| 132 |
|
| 133 |
+
camas_utilizadas = _reconstruir_tramos(db, paciente_id, cama)
|
| 134 |
|
| 135 |
+
payload_evento = {
|
| 136 |
+
"evento": "CIERRE_INTERNACION",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
"idEventoExterno": id_evento_externo,
|
| 138 |
+
"camaId": str(cama.id),
|
| 139 |
+
"idInternacionExterna": cama.solicitud_hce_id,
|
| 140 |
+
"idEpisodioExterno": None, # bloqueante externo — ver docstring
|
| 141 |
+
"idPacienteExterno": paciente_id,
|
| 142 |
+
"fechaIngreso": cama.fecha_ingreso.isoformat() if cama.fecha_ingreso else None,
|
| 143 |
+
"fechaAlta": cama.alta_timestamp.isoformat() if cama.alta_timestamp else None,
|
| 144 |
+
"tipoAlta": cama.alta_tipo,
|
| 145 |
+
"timestampEvento": datetime.now(timezone.utc).isoformat(),
|
| 146 |
+
"camasUtilizadas": camas_utilizadas,
|
| 147 |
}
|
| 148 |
+
core_events.publish_event(
|
| 149 |
+
settings.facturacion_cama_lista_event_type_id, payload_evento, publisher_module="modulo_6"
|
| 150 |
+
)
|
| 151 |
+
return ok_rest
|
app/integrations/hce.py
CHANGED
|
@@ -3,6 +3,7 @@ M1 HCE — contraindicaciones y movimientos de pacientes.
|
|
| 3 |
"""
|
| 4 |
from datetime import datetime, timezone
|
| 5 |
from app.config import settings
|
|
|
|
| 6 |
from app.integrations._base import _get, _post
|
| 7 |
|
| 8 |
|
|
@@ -42,7 +43,14 @@ def notify_resultado_solicitud(
|
|
| 42 |
resultado: str,
|
| 43 |
motivo: str | None = None,
|
| 44 |
) -> bool:
|
| 45 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
if settings.mock_external_services:
|
| 47 |
return True
|
| 48 |
payload = {
|
|
@@ -50,9 +58,16 @@ def notify_resultado_solicitud(
|
|
| 50 |
"motivo": motivo,
|
| 51 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 52 |
}
|
| 53 |
-
|
| 54 |
f"{settings.m1_hce_url}/api/v1/hce/solicitudes/{solicitud_hce_id}/resultado", payload
|
| 55 |
) is not None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
|
| 58 |
def notify_movimiento(
|
|
|
|
| 3 |
"""
|
| 4 |
from datetime import datetime, timezone
|
| 5 |
from app.config import settings
|
| 6 |
+
from app.integrations import core_events
|
| 7 |
from app.integrations._base import _get, _post
|
| 8 |
|
| 9 |
|
|
|
|
| 43 |
resultado: str,
|
| 44 |
motivo: str | None = None,
|
| 45 |
) -> bool:
|
| 46 |
+
"""
|
| 47 |
+
Notifica a M1 el resultado (APROBADA / RECHAZADA) de una solicitud. Retorna True si OK.
|
| 48 |
+
|
| 49 |
+
Además del webhook REST directo (sin cambios), publica el mismo evento al bus del Core
|
| 50 |
+
(SOLICITUD_RESUELTA) vía `core_events.publish_event`. Es un no-op mientras
|
| 51 |
+
`hce_solicitud_resuelta_event_type_id` no esté configurado — M1 todavía no compartió
|
| 52 |
+
su `event_type_id` real (ver `M6_DISEÑO.md` §7).
|
| 53 |
+
"""
|
| 54 |
if settings.mock_external_services:
|
| 55 |
return True
|
| 56 |
payload = {
|
|
|
|
| 58 |
"motivo": motivo,
|
| 59 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 60 |
}
|
| 61 |
+
ok_rest = _post(
|
| 62 |
f"{settings.m1_hce_url}/api/v1/hce/solicitudes/{solicitud_hce_id}/resultado", payload
|
| 63 |
) is not None
|
| 64 |
+
# El body REST no lleva solicitud_hce_id (va en el path); el evento del bus sí lo
|
| 65 |
+
# necesita, porque no hay URL que lo transporte implícitamente.
|
| 66 |
+
core_events.publish_event(
|
| 67 |
+
settings.hce_solicitud_resuelta_event_type_id,
|
| 68 |
+
{**payload, "solicitud_hce_id": solicitud_hce_id},
|
| 69 |
+
)
|
| 70 |
+
return ok_rest
|
| 71 |
|
| 72 |
|
| 73 |
def notify_movimiento(
|
app/integrations/monitoreo.py
CHANGED
|
@@ -3,10 +3,17 @@ M9 Monitoreo — altas y bajas de pacientes en monitoreo.
|
|
| 3 |
"""
|
| 4 |
from datetime import datetime, timezone
|
| 5 |
from app.config import settings
|
|
|
|
| 6 |
from app.integrations._base import _post
|
| 7 |
|
| 8 |
|
| 9 |
def notify_alta(paciente_id: int) -> bool:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
if settings.mock_external_services:
|
| 11 |
return True
|
| 12 |
payload = {
|
|
@@ -14,12 +21,15 @@ def notify_alta(paciente_id: int) -> bool:
|
|
| 14 |
"paciente_id": paciente_id,
|
| 15 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 16 |
}
|
| 17 |
-
|
| 18 |
f"{settings.m9_monitoreo_url}/api/v1/webhooks/internacion/alta-monitoreo", payload
|
| 19 |
) is not None
|
|
|
|
|
|
|
| 20 |
|
| 21 |
|
| 22 |
def notify_baja(paciente_id: int) -> bool:
|
|
|
|
| 23 |
if settings.mock_external_services:
|
| 24 |
print(f"[SIMULACION] Request a M9 Monitoreo → baja de paciente {paciente_id}")
|
| 25 |
return True
|
|
@@ -28,6 +38,8 @@ def notify_baja(paciente_id: int) -> bool:
|
|
| 28 |
"paciente_id": paciente_id,
|
| 29 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 30 |
}
|
| 31 |
-
|
| 32 |
f"{settings.m9_monitoreo_url}/api/v1/webhooks/internacion/baja-monitoreo", payload
|
| 33 |
) is not None
|
|
|
|
|
|
|
|
|
| 3 |
"""
|
| 4 |
from datetime import datetime, timezone
|
| 5 |
from app.config import settings
|
| 6 |
+
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`. Es un no-op mientras
|
| 14 |
+
`monitoreo_alta_event_type_id` no esté configurado — M9 todavía no compartió su
|
| 15 |
+
`event_type_id` real (ver `M6_DISEÑO.md` §7).
|
| 16 |
+
"""
|
| 17 |
if settings.mock_external_services:
|
| 18 |
return True
|
| 19 |
payload = {
|
|
|
|
| 21 |
"paciente_id": paciente_id,
|
| 22 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 23 |
}
|
| 24 |
+
ok_rest = _post(
|
| 25 |
f"{settings.m9_monitoreo_url}/api/v1/webhooks/internacion/alta-monitoreo", payload
|
| 26 |
) is not None
|
| 27 |
+
core_events.publish_event(settings.monitoreo_alta_event_type_id, payload)
|
| 28 |
+
return ok_rest
|
| 29 |
|
| 30 |
|
| 31 |
def notify_baja(paciente_id: int) -> bool:
|
| 32 |
+
"""Mismo esquema que `notify_alta`, para BAJA_MONITOREO."""
|
| 33 |
if settings.mock_external_services:
|
| 34 |
print(f"[SIMULACION] Request a M9 Monitoreo → baja de paciente {paciente_id}")
|
| 35 |
return True
|
|
|
|
| 38 |
"paciente_id": paciente_id,
|
| 39 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 40 |
}
|
| 41 |
+
ok_rest = _post(
|
| 42 |
f"{settings.m9_monitoreo_url}/api/v1/webhooks/internacion/baja-monitoreo", payload
|
| 43 |
) is not None
|
| 44 |
+
core_events.publish_event(settings.monitoreo_baja_event_type_id, payload)
|
| 45 |
+
return ok_rest
|
app/integrations/rabbit_consumer.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Consumer de `internacion.requests`: recibe por el bus del Core (M10) los mismos eventos
|
| 3 |
+
que hoy llegan como webhooks REST directos de M1/M9/M2 (`app/routers/webhooks.py`).
|
| 4 |
+
|
| 5 |
+
La cola y los 5 event types (`internacion.solicitud.creada`,
|
| 6 |
+
`internacion.alta-medica.registrada`, `internacion.alerta-emergencia.detectada`,
|
| 7 |
+
`internacion.alerta-resuelta.notificada`, `internacion.turno.cancelado`) ya están dados de
|
| 8 |
+
alta y bindeados en el Core — ver `M6_DISEÑO.md` §7. Este módulo solo consume: cada
|
| 9 |
+
mensaje se despacha a la misma función de servicio que usa el router REST equivalente, sin
|
| 10 |
+
lógica de negocio nueva. Cirugía urgente queda fuera (excluida de esta migración, ver
|
| 11 |
+
`M6_DISEÑO.md` §7): sigue siendo solo REST.
|
| 12 |
+
|
| 13 |
+
Los endpoints REST entrantes siguen activos sin cambios durante la transición — cada
|
| 14 |
+
equipo (M1/M9/M2) migra su emisor a su propio ritmo.
|
| 15 |
+
"""
|
| 16 |
+
import asyncio
|
| 17 |
+
import json
|
| 18 |
+
import logging
|
| 19 |
+
|
| 20 |
+
import aio_pika
|
| 21 |
+
from supabase import Client
|
| 22 |
+
|
| 23 |
+
from app.config import settings
|
| 24 |
+
from app.dependencies import get_db
|
| 25 |
+
from app.schemas.reserva import CancelacionQuirofanoRequest
|
| 26 |
+
from app.schemas.solicitud import (
|
| 27 |
+
AlertaEmergenciaRequest,
|
| 28 |
+
AlertaResueltaRequest,
|
| 29 |
+
AltaMedicaWebhook,
|
| 30 |
+
SolicitudHceWebhook,
|
| 31 |
+
)
|
| 32 |
+
from app.services import solicitud_service
|
| 33 |
+
|
| 34 |
+
logger = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _handle_solicitud(db: Client, payload: dict) -> None:
|
| 38 |
+
data = SolicitudHceWebhook.model_validate(payload)
|
| 39 |
+
solicitud_service.recibir_solicitud(db, data)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _handle_alta_medica(db: Client, payload: dict) -> None:
|
| 43 |
+
data = AltaMedicaWebhook.model_validate(payload)
|
| 44 |
+
solicitud_service.procesar_alta_medica(db, data)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _handle_alerta_emergencia(db: Client, payload: dict) -> None:
|
| 48 |
+
data = AlertaEmergenciaRequest.model_validate(payload)
|
| 49 |
+
solicitud_service.procesar_alerta_emergencia(db, data.paciente_id)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _handle_alerta_resuelta(db: Client, payload: dict) -> None:
|
| 53 |
+
data = AlertaResueltaRequest.model_validate(payload)
|
| 54 |
+
solicitud_service.procesar_alerta_resuelta(db, data.paciente_id)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _handle_turno_cancelado(db: Client, payload: dict) -> None:
|
| 58 |
+
# turno_id viaja en el payload del evento (en el webhook REST equivalente viene en el
|
| 59 |
+
# path: POST /turnos/{turno_id}/cancelacion). CancelacionQuirofanoRequest ignora los
|
| 60 |
+
# campos extra, así que se puede validar el resto del payload tal cual.
|
| 61 |
+
turno_id = payload["turno_id"]
|
| 62 |
+
data = CancelacionQuirofanoRequest.model_validate(payload)
|
| 63 |
+
solicitud_service.cancelar_reserva_por_turno(db, turno_id, data.motivo)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
_HANDLERS = {
|
| 67 |
+
"internacion.solicitud.creada": _handle_solicitud,
|
| 68 |
+
"internacion.alta-medica.registrada": _handle_alta_medica,
|
| 69 |
+
"internacion.alerta-emergencia.detectada": _handle_alerta_emergencia,
|
| 70 |
+
"internacion.alerta-resuelta.notificada": _handle_alerta_resuelta,
|
| 71 |
+
"internacion.turno.cancelado": _handle_turno_cancelado,
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def dispatch(event_type_name: str, payload: dict) -> None:
|
| 76 |
+
"""
|
| 77 |
+
Despacha un mensaje ya parseado a la función de servicio correspondiente.
|
| 78 |
+
Lanza `KeyError` si `event_type_name` no está mapeado, o lo que levante el servicio de
|
| 79 |
+
negocio (`ValueError`, `HTTPException`, etc.) — `_on_message` decide ack/reject según
|
| 80 |
+
el resultado.
|
| 81 |
+
"""
|
| 82 |
+
handler = _HANDLERS.get(event_type_name)
|
| 83 |
+
if handler is None:
|
| 84 |
+
raise KeyError(f"event_type_name no reconocido: {event_type_name!r}")
|
| 85 |
+
db = get_db()
|
| 86 |
+
handler(db, payload)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
async def _on_message(message: aio_pika.abc.AbstractIncomingMessage) -> None:
|
| 90 |
+
try:
|
| 91 |
+
envelope = json.loads(message.body)
|
| 92 |
+
event_type_name = envelope["event_type_name"]
|
| 93 |
+
payload = json.loads(envelope["payload"])
|
| 94 |
+
except (json.JSONDecodeError, KeyError, TypeError) as e:
|
| 95 |
+
logger.error(
|
| 96 |
+
"Mensaje malformado en %s, se descarta: %s", settings.internacion_requests_queue, e
|
| 97 |
+
)
|
| 98 |
+
await message.reject(requeue=False)
|
| 99 |
+
return
|
| 100 |
+
|
| 101 |
+
try:
|
| 102 |
+
dispatch(event_type_name, payload)
|
| 103 |
+
except Exception:
|
| 104 |
+
logger.exception(
|
| 105 |
+
"Error procesando %s (log_id=%s) de %s",
|
| 106 |
+
event_type_name, envelope.get("log_id"), settings.internacion_requests_queue,
|
| 107 |
+
)
|
| 108 |
+
await message.reject(requeue=False)
|
| 109 |
+
return
|
| 110 |
+
|
| 111 |
+
await message.ack()
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
async def run_consumer() -> None:
|
| 115 |
+
"""
|
| 116 |
+
Conecta a RabbitMQ y consume `internacion.requests` indefinidamente. Pensado para
|
| 117 |
+
correr como task de asyncio en el lifespan de FastAPI (`app/main.py`), gateado por
|
| 118 |
+
`settings.rabbitmq_consumer_enabled`.
|
| 119 |
+
"""
|
| 120 |
+
connection = await aio_pika.connect_robust(
|
| 121 |
+
host=settings.rabbitmq_host,
|
| 122 |
+
port=settings.rabbitmq_port,
|
| 123 |
+
login=settings.core_service_email,
|
| 124 |
+
password=settings.core_service_password,
|
| 125 |
+
virtualhost=settings.rabbitmq_vhost,
|
| 126 |
+
)
|
| 127 |
+
async with connection:
|
| 128 |
+
channel = await connection.channel()
|
| 129 |
+
await channel.set_qos(prefetch_count=10)
|
| 130 |
+
# passive=True: la cola ya existe (creada vía POST /rabbit/queues del Core, con
|
| 131 |
+
# su propia DLQ) — no la redeclaramos con propiedades propias.
|
| 132 |
+
queue = await channel.declare_queue(settings.internacion_requests_queue, passive=True)
|
| 133 |
+
await queue.consume(_on_message)
|
| 134 |
+
await asyncio.Future()
|
app/main.py
CHANGED
|
@@ -3,6 +3,8 @@ 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 Depends, FastAPI, Request, status
|
|
@@ -11,8 +13,9 @@ from fastapi.responses import JSONResponse
|
|
| 11 |
|
| 12 |
from app.config import settings
|
| 13 |
from app.dependencies import create_access_token, require_roles
|
|
|
|
| 14 |
|
| 15 |
-
from app.routers import auth, camas, quirofanos, solicitudes, webhooks, auditoria
|
| 16 |
from app.routers.webhooks import router_turnos
|
| 17 |
|
| 18 |
logger = logging.getLogger(__name__)
|
|
@@ -29,8 +32,19 @@ logging.basicConfig(
|
|
| 29 |
@asynccontextmanager
|
| 30 |
async def lifespan(app: FastAPI):
|
| 31 |
logger.info("Conectado a Supabase — listo para operar")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
yield
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
# ─── App ───────────────────────────────────────────────────────────────────
|
| 36 |
|
|
@@ -58,6 +72,7 @@ PREFIX = "/api/v1"
|
|
| 58 |
|
| 59 |
app.include_router(auth.router, prefix=PREFIX)
|
| 60 |
app.include_router(camas.router, prefix=PREFIX)
|
|
|
|
| 61 |
app.include_router(quirofanos.router, prefix=PREFIX)
|
| 62 |
app.include_router(solicitudes.router, prefix=PREFIX)
|
| 63 |
app.include_router(webhooks.router, prefix=PREFIX)
|
|
|
|
| 3 |
API REST: http://localhost:8006/api/v1
|
| 4 |
"""
|
| 5 |
|
| 6 |
+
import asyncio
|
| 7 |
+
import contextlib
|
| 8 |
import logging
|
| 9 |
from contextlib import asynccontextmanager
|
| 10 |
from fastapi import Depends, FastAPI, Request, status
|
|
|
|
| 13 |
|
| 14 |
from app.config import settings
|
| 15 |
from app.dependencies import create_access_token, require_roles
|
| 16 |
+
from app.integrations import rabbit_consumer
|
| 17 |
|
| 18 |
+
from app.routers import auth, camas, internal, quirofanos, solicitudes, webhooks, auditoria
|
| 19 |
from app.routers.webhooks import router_turnos
|
| 20 |
|
| 21 |
logger = logging.getLogger(__name__)
|
|
|
|
| 32 |
@asynccontextmanager
|
| 33 |
async def lifespan(app: FastAPI):
|
| 34 |
logger.info("Conectado a Supabase — listo para operar")
|
| 35 |
+
|
| 36 |
+
consumer_task = None
|
| 37 |
+
if settings.rabbitmq_consumer_enabled:
|
| 38 |
+
logger.info("Iniciando consumer de %s", settings.internacion_requests_queue)
|
| 39 |
+
consumer_task = asyncio.create_task(rabbit_consumer.run_consumer())
|
| 40 |
+
|
| 41 |
yield
|
| 42 |
|
| 43 |
+
if consumer_task is not None:
|
| 44 |
+
consumer_task.cancel()
|
| 45 |
+
with contextlib.suppress(asyncio.CancelledError):
|
| 46 |
+
await consumer_task
|
| 47 |
+
|
| 48 |
|
| 49 |
# ─── App ───────────────────────────────────────────────────────────────────
|
| 50 |
|
|
|
|
| 72 |
|
| 73 |
app.include_router(auth.router, prefix=PREFIX)
|
| 74 |
app.include_router(camas.router, prefix=PREFIX)
|
| 75 |
+
app.include_router(internal.router, prefix=PREFIX)
|
| 76 |
app.include_router(quirofanos.router, prefix=PREFIX)
|
| 77 |
app.include_router(solicitudes.router, prefix=PREFIX)
|
| 78 |
app.include_router(webhooks.router, prefix=PREFIX)
|
app/models/cama.py
CHANGED
|
@@ -26,6 +26,10 @@ class Cama:
|
|
| 26 |
contraindicaciones_incompatibles: Optional[list] = None,
|
| 27 |
ultima_actualizacion: Optional[datetime] = None,
|
| 28 |
ultimo_movimiento_tipo: Optional[str] = None,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
):
|
| 30 |
self.id = id
|
| 31 |
self.numero = numero
|
|
@@ -39,6 +43,14 @@ class Cama:
|
|
| 39 |
self.contraindicaciones_incompatibles = contraindicaciones_incompatibles or []
|
| 40 |
self.ultima_actualizacion = _parse_dt(ultima_actualizacion)
|
| 41 |
self.ultimo_movimiento_tipo = ultimo_movimiento_tipo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
@classmethod
|
| 44 |
def from_dict(cls, d: dict) -> "Cama":
|
|
@@ -55,4 +67,8 @@ class Cama:
|
|
| 55 |
contraindicaciones_incompatibles=d.get("contraindicaciones_incompatibles") or [],
|
| 56 |
ultima_actualizacion=d.get("ultima_actualizacion"),
|
| 57 |
ultimo_movimiento_tipo=d.get("ultimo_movimiento_tipo"),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
)
|
|
|
|
| 26 |
contraindicaciones_incompatibles: Optional[list] = None,
|
| 27 |
ultima_actualizacion: Optional[datetime] = None,
|
| 28 |
ultimo_movimiento_tipo: Optional[str] = None,
|
| 29 |
+
solicitud_hce_id: Optional[str] = None,
|
| 30 |
+
fecha_ingreso: Optional[datetime] = None,
|
| 31 |
+
alta_tipo: Optional[str] = None,
|
| 32 |
+
alta_timestamp: Optional[datetime] = None,
|
| 33 |
):
|
| 34 |
self.id = id
|
| 35 |
self.numero = numero
|
|
|
|
| 43 |
self.contraindicaciones_incompatibles = contraindicaciones_incompatibles or []
|
| 44 |
self.ultima_actualizacion = _parse_dt(ultima_actualizacion)
|
| 45 |
self.ultimo_movimiento_tipo = ultimo_movimiento_tipo
|
| 46 |
+
# Datos del episodio en curso — no hay tabla `episodios` separada; viajan en la
|
| 47 |
+
# propia fila de la cama entre el momento en que ocurren (asignación, alta médica)
|
| 48 |
+
# y el momento en que se necesitan (notify_cama_lista, al completar la limpieza).
|
| 49 |
+
# Ver M6_DISEÑO.md §7.2/§14 (integración real con M7).
|
| 50 |
+
self.solicitud_hce_id = solicitud_hce_id
|
| 51 |
+
self.fecha_ingreso = _parse_dt(fecha_ingreso)
|
| 52 |
+
self.alta_tipo = alta_tipo
|
| 53 |
+
self.alta_timestamp = _parse_dt(alta_timestamp)
|
| 54 |
|
| 55 |
@classmethod
|
| 56 |
def from_dict(cls, d: dict) -> "Cama":
|
|
|
|
| 67 |
contraindicaciones_incompatibles=d.get("contraindicaciones_incompatibles") or [],
|
| 68 |
ultima_actualizacion=d.get("ultima_actualizacion"),
|
| 69 |
ultimo_movimiento_tipo=d.get("ultimo_movimiento_tipo"),
|
| 70 |
+
solicitud_hce_id=d.get("solicitud_hce_id"),
|
| 71 |
+
fecha_ingreso=d.get("fecha_ingreso"),
|
| 72 |
+
alta_tipo=d.get("alta_tipo"),
|
| 73 |
+
alta_timestamp=d.get("alta_timestamp"),
|
| 74 |
)
|
app/routers/internal.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Endpoints internos: no hay un usuario humano detrás de estas llamadas, así que no usan
|
| 3 |
+
`get_current_user`/JWT de sesión — se protegen con un secreto compartido simple
|
| 4 |
+
(`settings.internal_tick_secret`).
|
| 5 |
+
|
| 6 |
+
`POST /internal/reservas/tick` avanza automáticamente el estado de las reservas de
|
| 7 |
+
quirófano según su horario (`RESERVADA → EN_CURSO → COMPLETADA`). Está pensado para que
|
| 8 |
+
lo dispare un cron externo (GitHub Actions, cron-job.org, etc.), no un scheduler en
|
| 9 |
+
memoria: el deploy de M6 (HF Spaces, tier gratuito) duerme el contenedor tras
|
| 10 |
+
inactividad, y un loop interno se congelaría con él. La propia request del cron despierta
|
| 11 |
+
el Space si estaba dormido. Ver `M6_DISEÑO.md` §5.4.
|
| 12 |
+
"""
|
| 13 |
+
import secrets
|
| 14 |
+
|
| 15 |
+
from fastapi import APIRouter, Depends, Header, HTTPException, status
|
| 16 |
+
from supabase import Client
|
| 17 |
+
|
| 18 |
+
from app.config import settings
|
| 19 |
+
from app.dependencies import get_db
|
| 20 |
+
from app.services import cama_service
|
| 21 |
+
|
| 22 |
+
router = APIRouter(prefix="/internal", tags=["Internal"])
|
| 23 |
+
|
| 24 |
+
_ERROR_401 = {"codigo": "NO_AUTENTICADO", "mensaje": "Token interno ausente o inválido"}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _verificar_token_interno(x_internal_token: str = Header(...)) -> None:
|
| 28 |
+
if not settings.internal_tick_secret or not secrets.compare_digest(
|
| 29 |
+
x_internal_token, settings.internal_tick_secret
|
| 30 |
+
):
|
| 31 |
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@router.post(
|
| 35 |
+
"/reservas/tick",
|
| 36 |
+
summary="Avanzar automáticamente el estado de reservas de quirófano según su horario",
|
| 37 |
+
responses={401: {"description": "Token interno ausente o inválido"}},
|
| 38 |
+
)
|
| 39 |
+
def tick_reservas(
|
| 40 |
+
db: Client = Depends(get_db),
|
| 41 |
+
_: None = Depends(_verificar_token_interno),
|
| 42 |
+
):
|
| 43 |
+
return cama_service.procesar_transiciones_automaticas(db)
|
app/routers/webhooks.py
CHANGED
|
@@ -58,7 +58,7 @@ def recibir_alta_medica(
|
|
| 58 |
db: Client = Depends(get_db),
|
| 59 |
user: dict = Depends(get_current_user),
|
| 60 |
):
|
| 61 |
-
cama = solicitud_service.procesar_alta_medica(db, data
|
| 62 |
return {
|
| 63 |
"mensaje": "Alta médica procesada. Cama en limpieza.",
|
| 64 |
"cama_id": cama.id,
|
|
|
|
| 58 |
db: Client = Depends(get_db),
|
| 59 |
user: dict = Depends(get_current_user),
|
| 60 |
):
|
| 61 |
+
cama = solicitud_service.procesar_alta_medica(db, data)
|
| 62 |
return {
|
| 63 |
"mensaje": "Alta médica procesada. Cama en limpieza.",
|
| 64 |
"cama_id": cama.id,
|
app/services/cama_service.py
CHANGED
|
@@ -23,7 +23,7 @@ from app.schemas.enums import EstadoCamaEnum, EstadoReservaEnum, SectorEnum, Tip
|
|
| 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,
|
| 27 |
from app.schemas.enums import EntidadAuditoriaEnum, TipoEventoAuditoriaEnum, OrigenAuditoriaEnum
|
| 28 |
|
| 29 |
|
|
@@ -142,9 +142,14 @@ def update_cama(
|
|
| 142 |
and nuevo_estado == EstadoCamaEnum.DISPONIBLE.value
|
| 143 |
and cama.ultimo_movimiento_tipo == "ALTA"
|
| 144 |
):
|
| 145 |
-
facturacion.notify_cama_lista(cama_id=cama.id, paciente_id=cama.paciente_id or 0)
|
| 146 |
cama.paciente_id = None
|
| 147 |
cama.ultimo_movimiento_tipo = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
elif nuevo_estado == EstadoCamaEnum.DISPONIBLE.value and cama.paciente_id:
|
| 149 |
cama.paciente_id = None
|
| 150 |
cama.ultimo_movimiento_tipo = None
|
|
@@ -533,6 +538,41 @@ def update_reserva_estado(
|
|
| 533 |
return reserva
|
| 534 |
|
| 535 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 536 |
def get_disponibilidad_quirofanos(
|
| 537 |
db: Client,
|
| 538 |
desde: datetime,
|
|
|
|
| 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, turnos
|
| 27 |
from app.schemas.enums import EntidadAuditoriaEnum, TipoEventoAuditoriaEnum, OrigenAuditoriaEnum
|
| 28 |
|
| 29 |
|
|
|
|
| 142 |
and nuevo_estado == EstadoCamaEnum.DISPONIBLE.value
|
| 143 |
and cama.ultimo_movimiento_tipo == "ALTA"
|
| 144 |
):
|
|
|
|
| 145 |
cama.paciente_id = None
|
| 146 |
cama.ultimo_movimiento_tipo = None
|
| 147 |
+
# Cierra el episodio: estos datos no deben arrastrarse al próximo paciente
|
| 148 |
+
# que ocupe esta cama.
|
| 149 |
+
cama.solicitud_hce_id = None
|
| 150 |
+
cama.fecha_ingreso = None
|
| 151 |
+
cama.alta_tipo = None
|
| 152 |
+
cama.alta_timestamp = None
|
| 153 |
elif nuevo_estado == EstadoCamaEnum.DISPONIBLE.value and cama.paciente_id:
|
| 154 |
cama.paciente_id = None
|
| 155 |
cama.ultimo_movimiento_tipo = None
|
|
|
|
| 538 |
return reserva
|
| 539 |
|
| 540 |
|
| 541 |
+
def procesar_transiciones_automaticas(db: Client) -> dict:
|
| 542 |
+
"""
|
| 543 |
+
Avanza automáticamente el estado de las reservas de quirófano según su horario:
|
| 544 |
+
`RESERVADA → EN_CURSO` al llegar `fecha_hora_inicio`, `EN_CURSO → COMPLETADA` al
|
| 545 |
+
llegar `fecha_hora_fin_estimada`. Pensado para dispararse desde un tick externo
|
| 546 |
+
(`app/routers/internal.py`), no desde un scheduler en memoria — ver `M6_DISEÑO.md`
|
| 547 |
+
§5.4 para el porqué.
|
| 548 |
+
|
| 549 |
+
Reusa `update_reserva_estado` tal cual: mismos side-effects que la transición manual
|
| 550 |
+
(cama a OCUPADA/EN_LIMPIEZA, auditoría). `actor=None` cae en el default ya existente
|
| 551 |
+
de `auditoria_crud.registrar` (rol SISTEMA, sin usuario humano detrás).
|
| 552 |
+
|
| 553 |
+
Que el filtro de origen (`reserva_crud.get_pendientes_de_inicio`) sea `estado=
|
| 554 |
+
RESERVADA` ya resuelve "si no se canceló, arranca sola": una reserva `CANCELADA`
|
| 555 |
+
nunca es candidata. Y como una reserva ya transicionada deja de matchear el filtro,
|
| 556 |
+
reintentar este tick (por ejemplo si el cron externo se solapa) es idempotente.
|
| 557 |
+
"""
|
| 558 |
+
ahora = datetime.now(timezone.utc)
|
| 559 |
+
|
| 560 |
+
iniciadas = [
|
| 561 |
+
update_reserva_estado(
|
| 562 |
+
db, r.cama_id, r.id, ReservaEstadoUpdateRequest(estado=EstadoReservaEnum.EN_CURSO), actor=None,
|
| 563 |
+
)
|
| 564 |
+
for r in reserva_crud.get_pendientes_de_inicio(db, ahora)
|
| 565 |
+
]
|
| 566 |
+
completadas = [
|
| 567 |
+
update_reserva_estado(
|
| 568 |
+
db, r.cama_id, r.id, ReservaEstadoUpdateRequest(estado=EstadoReservaEnum.COMPLETADA), actor=None,
|
| 569 |
+
)
|
| 570 |
+
for r in reserva_crud.get_pendientes_de_fin(db, ahora)
|
| 571 |
+
]
|
| 572 |
+
|
| 573 |
+
return {"iniciadas": len(iniciadas), "completadas": len(completadas)}
|
| 574 |
+
|
| 575 |
+
|
| 576 |
def get_disponibilidad_quirofanos(
|
| 577 |
db: Client,
|
| 578 |
desde: datetime,
|
app/services/solicitud_service.py
CHANGED
|
@@ -9,7 +9,7 @@ from supabase import Client
|
|
| 9 |
from app.models.solicitud import Solicitud
|
| 10 |
from app.models.cama import Cama
|
| 11 |
from app.models.reserva import ReservaQuirofano
|
| 12 |
-
from app.schemas.solicitud import SolicitudHceWebhook, SolicitudResolucionRequest
|
| 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
|
|
@@ -197,6 +197,10 @@ def _aprobar_internacion(
|
|
| 197 |
|
| 198 |
cama.estado = EstadoCamaEnum.OCUPADA.value
|
| 199 |
cama.paciente_id = sol.paciente_id
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
cama.ultima_actualizacion = datetime.now(timezone.utc)
|
| 201 |
cama_crud.save(db, cama)
|
| 202 |
|
|
@@ -262,10 +266,20 @@ def _aprobar_traslado(
|
|
| 262 |
|
| 263 |
if sol.cama_origen_id:
|
| 264 |
cama_origen = _get_cama_or_404(db, sol.cama_origen_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
cama_origen.estado = EstadoCamaEnum.EN_LIMPIEZA.value
|
| 266 |
cama_origen.ultimo_movimiento_tipo = "TRASLADO"
|
| 267 |
cama_origen.ultima_actualizacion = datetime.now(timezone.utc)
|
| 268 |
cama_crud.save(db, cama_origen)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
|
| 270 |
cama_destino.estado = EstadoCamaEnum.OCUPADA.value
|
| 271 |
cama_destino.paciente_id = sol.paciente_id
|
|
@@ -316,31 +330,31 @@ def _aprobar_traslado(
|
|
| 316 |
|
| 317 |
# ─── Alta médica (desde HCE M1) ────────────────────────────────────────────
|
| 318 |
|
| 319 |
-
def procesar_alta_medica(db: Client,
|
|
|
|
| 320 |
cama = cama_crud.get_by_paciente(db, paciente_id, ["OCUPADA", "CODIGO_ROJO"])
|
| 321 |
if not cama:
|
| 322 |
raise HTTPException(
|
| 323 |
status_code=404,
|
| 324 |
detail={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "No se encontró cama asignada al paciente"},
|
| 325 |
)
|
| 326 |
-
#
|
| 327 |
-
# el
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
detail={"codigo": "SERVICIO_EXTERNO_NO_DISPONIBLE", "mensaje": "No se pudo cerrar la cama en Facturación (M7)"},
|
| 332 |
-
)
|
| 333 |
-
if not monitoreo.notify_baja(paciente_id):
|
| 334 |
-
raise HTTPException(
|
| 335 |
-
status_code=502,
|
| 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,
|
|
|
|
| 9 |
from app.models.solicitud import Solicitud
|
| 10 |
from app.models.cama import Cama
|
| 11 |
from app.models.reserva import ReservaQuirofano
|
| 12 |
+
from app.schemas.solicitud import SolicitudHceWebhook, SolicitudResolucionRequest, AltaMedicaWebhook
|
| 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
|
|
|
|
| 197 |
|
| 198 |
cama.estado = EstadoCamaEnum.OCUPADA.value
|
| 199 |
cama.paciente_id = sol.paciente_id
|
| 200 |
+
# Datos del episodio en curso (ver app/models/cama.py) — necesarios más adelante
|
| 201 |
+
# para el payload rico que pide M7 al cerrarse la internación (notify_cama_lista).
|
| 202 |
+
cama.solicitud_hce_id = sol.solicitud_hce_id
|
| 203 |
+
cama.fecha_ingreso = datetime.now(timezone.utc)
|
| 204 |
cama.ultima_actualizacion = datetime.now(timezone.utc)
|
| 205 |
cama_crud.save(db, cama)
|
| 206 |
|
|
|
|
| 266 |
|
| 267 |
if sol.cama_origen_id:
|
| 268 |
cama_origen = _get_cama_or_404(db, sol.cama_origen_id)
|
| 269 |
+
# El episodio (fecha de ingreso, id de la internación original) es continuo a
|
| 270 |
+
# través de un traslado — se hereda de la cama origen, no de esta solicitud de
|
| 271 |
+
# traslado, para no perder el dato real de cuándo empezó la internación.
|
| 272 |
+
cama_destino.solicitud_hce_id = cama_origen.solicitud_hce_id
|
| 273 |
+
cama_destino.fecha_ingreso = cama_origen.fecha_ingreso
|
| 274 |
cama_origen.estado = EstadoCamaEnum.EN_LIMPIEZA.value
|
| 275 |
cama_origen.ultimo_movimiento_tipo = "TRASLADO"
|
| 276 |
cama_origen.ultima_actualizacion = datetime.now(timezone.utc)
|
| 277 |
cama_crud.save(db, cama_origen)
|
| 278 |
+
else:
|
| 279 |
+
# Traslado sin cama origen registrada (caso atípico) — se trata como un ingreso
|
| 280 |
+
# nuevo a los fines del episodio.
|
| 281 |
+
cama_destino.solicitud_hce_id = sol.solicitud_hce_id
|
| 282 |
+
cama_destino.fecha_ingreso = datetime.now(timezone.utc)
|
| 283 |
|
| 284 |
cama_destino.estado = EstadoCamaEnum.OCUPADA.value
|
| 285 |
cama_destino.paciente_id = sol.paciente_id
|
|
|
|
| 330 |
|
| 331 |
# ─── Alta médica (desde HCE M1) ────────────────────────────────────────────
|
| 332 |
|
| 333 |
+
def procesar_alta_medica(db: Client, data: AltaMedicaWebhook) -> Cama:
|
| 334 |
+
paciente_id = data.paciente_id
|
| 335 |
cama = cama_crud.get_by_paciente(db, paciente_id, ["OCUPADA", "CODIGO_ROJO"])
|
| 336 |
if not cama:
|
| 337 |
raise HTTPException(
|
| 338 |
status_code=404,
|
| 339 |
detail={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "No se encontró cama asignada al paciente"},
|
| 340 |
)
|
| 341 |
+
# Notificación asincrónica (fire-and-forget, M6_DISEÑO.md §2): M6 informa a M9 que
|
| 342 |
+
# el paciente sale de monitoreo, pero que M9 esté caído no debe revertir el alta.
|
| 343 |
+
# La notificación real a M7 (CAMA_LISTA) ocurre más adelante, al completar la
|
| 344 |
+
# limpieza (cama_service.py), también fire-and-forget.
|
| 345 |
+
monitoreo.notify_baja(paciente_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
|
| 347 |
estado_previo = cama.estado
|
| 348 |
cama.estado = EstadoCamaEnum.EN_LIMPIEZA.value
|
| 349 |
cama.ultimo_movimiento_tipo = "ALTA"
|
| 350 |
+
cama.alta_tipo = data.tipo_alta.value
|
| 351 |
+
cama.alta_timestamp = data.timestamp
|
| 352 |
cama.ultima_actualizacion = datetime.now(timezone.utc)
|
| 353 |
cama_crud.save(db, cama)
|
| 354 |
+
# Fire-and-forget: notificación a M7 para cerrar la internación del lado de
|
| 355 |
+
# facturación. Se dispara aquí (alta médica) porque el cierre de facturación
|
| 356 |
+
# ocurre con el alta del paciente, no con la limpieza de la cama.
|
| 357 |
+
facturacion.notify_cama_lista(cama, db)
|
| 358 |
auditoria_crud.registrar(
|
| 359 |
db,
|
| 360 |
entidad=EntidadAuditoriaEnum.CAMA.value,
|
documentation/M6_DISEÑO.md
CHANGED
|
@@ -188,7 +188,13 @@ Si `origen = CIRUGIA_PROGRAMADA`, antes de aprobar se valida el turno quirúrgic
|
|
| 188 |
|
| 189 |
### 5.4 Cirugía programada
|
| 190 |
|
| 191 |
-
`POST /quirofanos/{quirofanoId}/reservas` crea una reserva `PROGRAMADA` en estado `RESERVADA`. Disponibilidad consultable con `GET /quirofanos/disponibilidad?desde&hasta&specialty_id`. El estado se avanza con `PATCH /quirofanos/{quirofanoId}/reservas/{reservaId}` (`EN_CURSO`, `COMPLETADA`, `CANCELADA`).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
### 5.5 Cirugía urgente con priorización ASAP
|
| 194 |
|
|
@@ -237,18 +243,39 @@ Si `origen = CIRUGIA_PROGRAMADA`, antes de aprobar se valida el turno quirúrgic
|
|
| 237 |
|
| 238 |
### 7.2 Webhooks salientes (M6 → otros módulos)
|
| 239 |
|
| 240 |
-
| Evento | Receptor | Endpoint receptor | Cuándo |
|
| 241 |
|--------|----------|-------------------|--------|
|
| 242 |
-
| `SOLICITUD_RESUELTA` | M1 HCE | `POST /hce/solicitudes/{solicitudHceId}/resultado` | Al aprobar o rechazar una solicitud |
|
| 243 |
-
| `ALTA_MONITOREO` | M9 Monitoreo | `POST /webhooks/internacion/alta-monitoreo` | Al asignar cama (ingreso o destino de traslado) |
|
| 244 |
-
| `BAJA_MONITOREO` | M9 Monitoreo | `POST /webhooks/internacion/baja-monitoreo` | Al dar el alta o al trasladar (cama origen) |
|
| 245 |
-
| `CAMA_LISTA` | M7 Facturación | `POST /webhooks/internacion/cama-lista` | Al completar limpieza post-alta (`EN_LIMPIEZA → DISPONIBLE`) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
|
| 247 |
### 7.3 APIs externas consumidas (REST sincrónico)
|
| 248 |
|
| 249 |
| Módulo | Endpoint | Cuándo |
|
| 250 |
|--------|----------|--------|
|
| 251 |
-
| M10 Core | `POST /auth/validate-token` | En cada request (middleware JWT) |
|
| 252 |
| M10 Core | `GET /usuarios/{pacienteId}` | Al aprobar una internación (datos del paciente) |
|
| 253 |
| M1 HCE | `GET /hce/pacientes/{pacienteId}/contraindicaciones` | Al aprobar una internación |
|
| 254 |
| M1 HCE | `GET /hce/pacientes/{pacienteId}` | Al mostrar el detalle del paciente internado en una cama |
|
|
@@ -261,6 +288,64 @@ Si `origen = CIRUGIA_PROGRAMADA`, antes de aprobar se valida el turno quirúrgic
|
|
| 261 |
|
| 262 |
Todos los endpoints `[EXT]` (los que expone otro módulo) se mockean localmente para la 2da entrega. El mock vive en la capa de clientes HTTP: la misma interfaz que en producción, pero devolviendo respuestas canned. Esto permite que la 3ra entrega solo cambie la URL base del cliente, sin tocar la lógica de servicios.
|
| 263 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
---
|
| 265 |
|
| 266 |
## 8. Contrato de API (recursos propios)
|
|
@@ -319,10 +404,9 @@ Ambas tablas necesitan una policy RLS de `SELECT` abierta (`USING (true)`) para
|
|
| 319 |
|
| 320 |
## 10. Persistencia
|
| 321 |
|
| 322 |
-
Tablas principales en PostgreSQL (Supabase): `camas` (incluye quirófanos), `reservas_quirofano`, `solicitudes`, `
|
| 323 |
|
| 324 |
-
- **`camas`** guarda también los quirófanos (`sector=QUIROFANO`, `tipo=CIRUGIA`). Es la decisión de modelo que explica que `QuirofanoResponse.estado` use `EstadoCamaEnum` y que `ReservaQuirofanoResponse` referencie la cama. Alternativa rechazada: tabla `quirofanos` separada, que duplicaría la máquina de estados de disponibilidad.
|
| 325 |
-
- **`episodios`** referencia al paciente y mantiene la lista de camas atravesadas para el reporte a Facturación.
|
| 326 |
- **`auditoria`** es el log append-only de auditoría de `CAMA`/`SOLICITUD`/`RESERVA_QUIROFANO`, instrumentado explícitamente en la capa de servicios (no triggers, no middleware) para capturar el actor del JWT y el contexto de negocio completo. Registrar un evento es *best-effort*: nunca propaga una excepción que rompa la operación de negocio. Habilitada para Supabase Realtime (§9). Modelo completo, enums y puntos de instrumentación en `docs/superpowers/specs/2026-06-26-auditoria-cama-design.md`.
|
| 327 |
- La asignación de cama (validar `DISPONIBLE` → set `OCUPADA` + `paciente_id`) se hace en una transacción con bloqueo de fila para evitar doble ocupación.
|
| 328 |
|
|
@@ -434,3 +518,31 @@ No hay lookup aparte (`GET /roles`, `GET /users/{id}`) ni verificación de JWT d
|
|
| 434 |
26. **Nuevo endpoint `POST /auth/sso-exchange`.** Canjea un ticket SSO de un solo uso del Core (`app/routers/auth.py`, activo con `SSO_ENABLED=true`) por una sesión propia de M6: JWT HS256 con el rol ya resuelto. Request `{ticket}`; response `{token, user, rol}`; errores `401` (ticket inválido/usado/expirado), `403` (roles del usuario sin mapeo a M6), `404` (SSO deshabilitado), `502` (Core inalcanzable). Actualizar `M6_openapi.json` con este endpoint.
|
| 435 |
27. **Eliminado el lookup `GET /roles` y la verificación de JWT del Core por-request.** El rol ya no se resuelve con una llamada aparte cacheada: viene directo en `user.roles[]` de la respuesta del canje SSO (`models.AuthResponse` → `models.User` → `models.Role`). Se retiraron `core_auth.resolve_user_roles`, `_fetch_roles_index`, `verify_core_token`, `get_signing_key` y sus caches (`_roles_index_cache`, `_jwks_cache`); con ellos, las settings `jwks_cache_ttl_seconds`/`core_roles_cache_ttl_seconds`. Se conserva `map_core_roles_to_internal` (§11), que ahora traduce `user.roles[].name` en vez de un índice cacheado.
|
| 436 |
28. **`app/config.py::auth_mode` reemplazado por `sso_enabled`.** Ya no existe un modo de validación por-request alternativo — la sesión de M6 es siempre HS256 propia. `sso_enabled` (default `False`) solo habilita/deshabilita el endpoint de canje.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
|
| 189 |
### 5.4 Cirugía programada
|
| 190 |
|
| 191 |
+
`POST /quirofanos/{quirofanoId}/reservas` crea una reserva `PROGRAMADA` en estado `RESERVADA`. Disponibilidad consultable con `GET /quirofanos/disponibilidad?desde&hasta&specialty_id`. El estado se avanza con `PATCH /quirofanos/{quirofanoId}/reservas/{reservaId}` (`EN_CURSO`, `COMPLETADA`, `CANCELADA`) — vía manual, o automáticamente por horario (ver abajo).
|
| 192 |
+
|
| 193 |
+
**Auto-transición por horario.** `cama_service.procesar_transiciones_automaticas` (invocada por `POST /api/v1/internal/reservas/tick`, `app/routers/internal.py`) avanza sola las reservas que no se resolvieron a mano: al llegar `fecha_hora_inicio`, una reserva `RESERVADA` pasa a `EN_CURSO`; al llegar `fecha_hora_fin_estimada`, una `EN_CURSO` pasa a `COMPLETADA`. Reusa `update_reserva_estado` tal cual — mismos side-effects que la transición manual (cama a `OCUPADA`/`EN_LIMPIEZA`, auditoría con `rol=SISTEMA`). Que el filtro de origen sea `estado=RESERVADA` ya resuelve "si no se canceló, arranca sola": una reserva `CANCELADA` nunca es candidata, sin lógica adicional. El tick es idempotente: una reserva ya transicionada no vuelve a matchear el filtro en la siguiente pasada.
|
| 194 |
+
|
| 195 |
+
El endpoint no usa `get_current_user` (no hay un usuario humano detrás de un cron) — se protege con un secreto compartido simple (`settings.internal_tick_secret`, header `X-Internal-Token`). Está pensado para que lo dispare un **cron externo** (GitHub Actions con `schedule:`, o cron-job.org), no un scheduler en memoria: el deploy de M6 en HF Spaces es del tier gratuito, que duerme el contenedor tras inactividad — un loop interno de `asyncio`/APScheduler se congelaría junto con el proceso. La propia request del cron despierta el Space si estaba dormido y ejecuta el chequeo. Se descartó también `pg_cron` de Supabase: sobrevive al sleep, pero reimplementar los side-effects de `update_reserva_estado` en SQL duplicaría la máquina de estados en dos lenguajes.
|
| 196 |
+
|
| 197 |
+
Margen de precisión aceptable: con un cron cada 1–5 minutos, una cirugía puede reflejarse en el sistema hasta ese margen tarde respecto del horario real — razonable para este caso de uso.
|
| 198 |
|
| 199 |
### 5.5 Cirugía urgente con priorización ASAP
|
| 200 |
|
|
|
|
| 243 |
|
| 244 |
### 7.2 Webhooks salientes (M6 → otros módulos)
|
| 245 |
|
| 246 |
+
| Evento | Receptor | Endpoint receptor / evento del bus | Cuándo |
|
| 247 |
|--------|----------|-------------------|--------|
|
| 248 |
+
| `SOLICITUD_RESUELTA` | M1 HCE | `POST /hce/solicitudes/{solicitudHceId}/resultado` (REST); evento pendiente de `event_type_id` de M1 | Al aprobar o rechazar una solicitud |
|
| 249 |
+
| `ALTA_MONITOREO` | M9 Monitoreo | `POST /webhooks/internacion/alta-monitoreo` (REST); evento pendiente de `event_type_id` de M9 | Al asignar cama (ingreso o destino de traslado) |
|
| 250 |
+
| `BAJA_MONITOREO` | M9 Monitoreo | `POST /webhooks/internacion/baja-monitoreo` (REST); evento pendiente de `event_type_id` de M9 | 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`):
|
| 254 |
+
cola `facturacion.requests`, `event_type_id: 19`, `publisher_module: "modulo_6"`. El
|
| 255 |
+
payload del evento es mucho más rico que el REST (que sigue siendo solo el mínimo de
|
| 256 |
+
siempre): `{evento: CIERRE_INTERNACION, idEventoExterno, idInternacionExterna,
|
| 257 |
+
idEpisodioExterno, idPacienteExterno, fechaIngreso, fechaAlta, tipoAlta, timestampEvento}`
|
| 258 |
+
(`app/integrations/facturacion.py::notify_cama_lista`). `timestampEvento` es obligatorio
|
| 259 |
+
por contrato — M7 rechaza el evento si falta.
|
| 260 |
+
|
| 261 |
+
Para armar ese payload, M6 empezó a persistir datos del episodio en curso directamente en
|
| 262 |
+
la fila de `Cama` (`solicitud_hce_id`, `fecha_ingreso`, `alta_tipo`, `alta_timestamp` —
|
| 263 |
+
ver `app/models/cama.py`), seteados al aprobar la solicitud y al procesar el alta médica,
|
| 264 |
+
y limpiados al cerrar el episodio (`cama_service.py`, tras `notify_cama_lista`). En un
|
| 265 |
+
traslado, el episodio (fecha de ingreso e id de internación original) se **hereda de la
|
| 266 |
+
cama origen**, no de la solicitud de traslado — es la misma internación, solo cambió de
|
| 267 |
+
cama física.
|
| 268 |
+
|
| 269 |
+
**`idEpisodioExterno` viaja como `None`, a propósito:** ningún webhook de M1 lo provee hoy
|
| 270 |
+
(ni `SolicitudHceWebhook` ni `AltaMedicaWebhook` tienen ese campo). Pendiente coordinar
|
| 271 |
+
con M1 que lo agregue a `AltaMedicaWebhook` — ver `documentation/M6_INTEGRACION_M1_HCE.md`.
|
| 272 |
+
M7 confirmó que sin ese dato el evento no se rechaza, queda pendiente de completar del
|
| 273 |
+
lado de ellos.
|
| 274 |
|
| 275 |
### 7.3 APIs externas consumidas (REST sincrónico)
|
| 276 |
|
| 277 |
| Módulo | Endpoint | Cuándo |
|
| 278 |
|--------|----------|--------|
|
|
|
|
| 279 |
| M10 Core | `GET /usuarios/{pacienteId}` | Al aprobar una internación (datos del paciente) |
|
| 280 |
| M1 HCE | `GET /hce/pacientes/{pacienteId}/contraindicaciones` | Al aprobar una internación |
|
| 281 |
| M1 HCE | `GET /hce/pacientes/{pacienteId}` | Al mostrar el detalle del paciente internado en una cama |
|
|
|
|
| 288 |
|
| 289 |
Todos los endpoints `[EXT]` (los que expone otro módulo) se mockean localmente para la 2da entrega. El mock vive en la capa de clientes HTTP: la misma interfaz que en producción, pero devolviendo respuestas canned. Esto permite que la 3ra entrega solo cambie la URL base del cliente, sin tocar la lógica de servicios.
|
| 290 |
|
| 291 |
+
### 7.5 Bus de eventos del Core (M10): migración en curso
|
| 292 |
+
|
| 293 |
+
Los webhooks REST de §7.1 tienen dos problemas: (1) exigen `get_current_user` (JWT de
|
| 294 |
+
usuario) pero M1/M9/M2 no tienen un usuario humano detrás de un webhook — no hay forma
|
| 295 |
+
legítima de que llamen hoy sin credenciales que no deberían tener; (2) son integraciones
|
| 296 |
+
point-to-point ad hoc, cuando el Core ya expone un bus de eventos pensado para esto
|
| 297 |
+
(`documentation/integrations/M10_integration.md`, "Tutorial: Comunicación entre
|
| 298 |
+
microservicios"): *"RabbitMQ para escuchar; Core para configurar y publicar."* Migrar a
|
| 299 |
+
la cola resuelve el problema de auth (se consume con credenciales RabbitMQ propias, no un
|
| 300 |
+
JWT de usuario) y suma at-least-once delivery + DLQ que hoy no existen.
|
| 301 |
+
|
| 302 |
+
**Lado entrante — ya migrado, en paralelo con REST.** Cola propia `internacion.requests`
|
| 303 |
+
(+ `internacion.requests.dlq`) y 5 event types bindeados, dados de alta en el Core real:
|
| 304 |
+
|
| 305 |
+
| Evento | Id | Reemplaza (REST) | Emisor | Payload |
|
| 306 |
+
|---|---|---|---|---|
|
| 307 |
+
| `internacion.solicitud.creada` | 14 | `POST /webhooks/hce/solicitud` | M1 | `SolicitudHceWebhook` |
|
| 308 |
+
| `internacion.alta-medica.registrada` | 15 | `POST /webhooks/hce/alta-medica` | M1 | `AltaMedicaWebhook` |
|
| 309 |
+
| `internacion.alerta-emergencia.detectada` | 16 | `POST /webhooks/monitoreo/alerta-emergencia` | M9 | `AlertaEmergenciaRequest` |
|
| 310 |
+
| `internacion.alerta-resuelta.notificada` | 17 | `POST /webhooks/monitoreo/alerta-resuelta` | M9 | `AlertaResueltaRequest` |
|
| 311 |
+
| `internacion.turno.cancelado` | 18 | `POST /turnos/{turnoId}/cancelacion` | M2 | `CancelacionQuirofanoRequest` + `turno_id` (viaja en el payload; en el REST equivalente viene del path) |
|
| 312 |
+
|
| 313 |
+
Los 5 son notificaciones fire-and-forget (sin `correlation_id`/`response_event_id`), y
|
| 314 |
+
reusan tal cual los schemas Pydantic del webhook REST equivalente. El consumer
|
| 315 |
+
(`app/integrations/rabbit_consumer.py`) despacha por `event_type_name` a la misma función
|
| 316 |
+
de servicio que ya usa el router REST (`solicitud_service.recibir_solicitud`,
|
| 317 |
+
`procesar_alta_medica`, `procesar_alerta_emergencia`, `procesar_alerta_resuelta`,
|
| 318 |
+
`cancelar_reserva_por_turno`) — cero lógica de negocio nueva, incluida la deduplicación
|
| 319 |
+
por id de origen (§6). Gateado por `settings.rabbitmq_consumer_enabled` (default `False`:
|
| 320 |
+
falta el host/puerto/vhost real del broker compartido — las credenciales sí son las
|
| 321 |
+
mismas `core_service_email`/`core_service_password` de siempre).
|
| 322 |
+
|
| 323 |
+
**Los endpoints REST de §7.1 se mantienen activos sin cambios** durante la transición —
|
| 324 |
+
cada equipo (M1/M9/M2) migra su emisor a su propio ritmo; se retiran recién cuando los
|
| 325 |
+
tres confirmen que publican por la cola.
|
| 326 |
+
|
| 327 |
+
**Cirugía urgente queda excluida** de esta migración: `POST /webhooks/hce/cirugia-urgente`
|
| 328 |
+
devuelve sincrónicamente qué quirófano/reserva se asignó y qué reservas se desplazaron —
|
| 329 |
+
no hay hoy un canal async equivalente. Migrarla requiere antes acordar con M1 un evento de
|
| 330 |
+
respuesta (`correlation_id` + `response_event_id`). Sigue siendo solo REST.
|
| 331 |
+
|
| 332 |
+
**Lado saliente — código listo, apagado hasta tener los `event_type_id` reales.** Las 4
|
| 333 |
+
notificaciones de §7.2 (`SOLICITUD_RESUELTA`, `ALTA_MONITOREO`, `BAJA_MONITOREO`,
|
| 334 |
+
`CAMA_LISTA`) siguen el mismo bus, pero el evento y la cola los crea y posee **el
|
| 335 |
+
receptor** (M1/M9/M7), no M6 — por la misma regla del tutorial que aplica al revés en
|
| 336 |
+
§7.1. M6 todavía no tiene esos `event_type_id` porque los equipos no respondieron.
|
| 337 |
+
|
| 338 |
+
En vez de crear infraestructura mock en el Core (tráfico real sin nadie consumiéndolo),
|
| 339 |
+
`app/integrations/core_events.py::publish_event(event_type_id, payload)` es un no-op
|
| 340 |
+
explícito mientras `event_type_id is None` (settings `hce_solicitud_resuelta_event_type_id`,
|
| 341 |
+
`monitoreo_alta_event_type_id`, `monitoreo_baja_event_type_id`,
|
| 342 |
+
`facturacion_cama_lista_event_type_id`, todas `None` por default). Las 4 funciones
|
| 343 |
+
`notify_*` (`hce.notify_resultado_solicitud`, `monitoreo.notify_alta`/`notify_baja`,
|
| 344 |
+
`facturacion.notify_cama_lista`) hacen **dual-write**: siguen llamando al webhook REST
|
| 345 |
+
directo exactamente como hoy (sin cambios observables) y además llaman a `publish_event`,
|
| 346 |
+
que hoy no dispara nada. El día que cada equipo comparta su ID, se carga en config — sin
|
| 347 |
+
tocar código — y empieza a salir por las dos vías hasta coordinar cuándo retirar la REST.
|
| 348 |
+
|
| 349 |
---
|
| 350 |
|
| 351 |
## 8. Contrato de API (recursos propios)
|
|
|
|
| 404 |
|
| 405 |
## 10. Persistencia
|
| 406 |
|
| 407 |
+
Tablas principales en PostgreSQL (Supabase): `camas` (incluye quirófanos), `reservas_quirofano`, `solicitudes`, `auditoria`.
|
| 408 |
|
| 409 |
+
- **`camas`** guarda también los quirófanos (`sector=QUIROFANO`, `tipo=CIRUGIA`). Es la decisión de modelo que explica que `QuirofanoResponse.estado` use `EstadoCamaEnum` y que `ReservaQuirofanoResponse` referencie la cama. Alternativa rechazada: tabla `quirofanos` separada, que duplicaría la máquina de estados de disponibilidad. Además de sus columnas originales, `camas` guarda los datos del **episodio en curso** (`solicitud_hce_id`, `fecha_ingreso`, `alta_tipo`, `alta_timestamp`) — necesarios para el payload rico que M7 pide al cerrar la internación (§7.2, §14). Se setean al aprobar la solicitud y al procesar el alta médica, y se limpian al notificar a M7. Decisión: no se creó una tabla `episodios` separada (mencionada en versiones previas de este documento como plan, nunca implementada) — para el alcance actual (una cama activa = un episodio en curso, sin necesidad de historizar episodios pasados) alcanza con estas columnas en `camas`, siguiendo el mismo patrón ya usado por `ultimo_movimiento_tipo`.
|
|
|
|
| 410 |
- **`auditoria`** es el log append-only de auditoría de `CAMA`/`SOLICITUD`/`RESERVA_QUIROFANO`, instrumentado explícitamente en la capa de servicios (no triggers, no middleware) para capturar el actor del JWT y el contexto de negocio completo. Registrar un evento es *best-effort*: nunca propaga una excepción que rompa la operación de negocio. Habilitada para Supabase Realtime (§9). Modelo completo, enums y puntos de instrumentación en `docs/superpowers/specs/2026-06-26-auditoria-cama-design.md`.
|
| 411 |
- La asignación de cama (validar `DISPONIBLE` → set `OCUPADA` + `paciente_id`) se hace en una transacción con bloqueo de fila para evitar doble ocupación.
|
| 412 |
|
|
|
|
| 518 |
26. **Nuevo endpoint `POST /auth/sso-exchange`.** Canjea un ticket SSO de un solo uso del Core (`app/routers/auth.py`, activo con `SSO_ENABLED=true`) por una sesión propia de M6: JWT HS256 con el rol ya resuelto. Request `{ticket}`; response `{token, user, rol}`; errores `401` (ticket inválido/usado/expirado), `403` (roles del usuario sin mapeo a M6), `404` (SSO deshabilitado), `502` (Core inalcanzable). Actualizar `M6_openapi.json` con este endpoint.
|
| 519 |
27. **Eliminado el lookup `GET /roles` y la verificación de JWT del Core por-request.** El rol ya no se resuelve con una llamada aparte cacheada: viene directo en `user.roles[]` de la respuesta del canje SSO (`models.AuthResponse` → `models.User` → `models.Role`). Se retiraron `core_auth.resolve_user_roles`, `_fetch_roles_index`, `verify_core_token`, `get_signing_key` y sus caches (`_roles_index_cache`, `_jwks_cache`); con ellos, las settings `jwks_cache_ttl_seconds`/`core_roles_cache_ttl_seconds`. Se conserva `map_core_roles_to_internal` (§11), que ahora traduce `user.roles[].name` en vez de un índice cacheado.
|
| 520 |
28. **`app/config.py::auth_mode` reemplazado por `sso_enabled`.** Ya no existe un modo de validación por-request alternativo — la sesión de M6 es siempre HS256 propia. `sso_enabled` (default `False`) solo habilita/deshabilita el endpoint de canje.
|
| 521 |
+
|
| 522 |
+
### 14.6 Migración de webhooks entrantes al bus de eventos del Core (2026-07)
|
| 523 |
+
|
| 524 |
+
29. **Cola `internacion.requests` + 5 event types dados de alta en el Core real** (ids 14–18: `internacion.solicitud.creada`, `internacion.alta-medica.registrada`, `internacion.alerta-emergencia.detectada`, `internacion.alerta-resuelta.notificada`, `internacion.turno.cancelado`), bindeados a esa cola. Reemplazan, en paralelo con REST durante la transición, a los webhooks entrantes de §7.1 (excepto cirugía urgente, excluida — ver §7.5).
|
| 525 |
+
30. **Nuevo consumer `app/integrations/rabbit_consumer.py`** (`aio-pika`, gateado por `settings.rabbitmq_consumer_enabled`, default `False` hasta tener host/puerto/vhost real del broker). Despacha por `event_type_name` a las mismas funciones de servicio que ya usa el router REST — sin lógica de negocio nueva.
|
| 526 |
+
31. **Nuevo publisher `app/integrations/core_events.py::publish_event`** para las 4 notificaciones salientes de §7.2. No-op explícito mientras el `event_type_id` correspondiente sea `None` (default hasta que M1/M9/M7 compartan el suyo — cada uno crea y posee su propio evento, no M6). Las 4 funciones `notify_*` (`hce.notify_resultado_solicitud`, `monitoreo.notify_alta`/`notify_baja`, `facturacion.notify_cama_lista`) quedan en dual-write: REST sin cambios + `publish_event` adicional.
|
| 527 |
+
32. **Sin infraestructura mock creada en el Core para el lado saliente.** Se descartó explícitamente crear event types/colas placeholder en el Core compartido para simular a M1/M9/M7 — hubiera generado tráfico real sin receptor. El código queda listo y probado; activar la publicación real es cambiar 4 valores de config, sin tocar código.
|
| 528 |
+
|
| 529 |
+
### 14.7 Eliminación de código zombie en la integración con M7/M9 (2026-07)
|
| 530 |
+
|
| 531 |
+
33. **Eliminado `facturacion.notify_cierre_cama`.** Apuntaba a `POST /api/v1/webhooks/internacion/cierre-cama`, un endpoint que nunca estuvo en la tabla de webhooks salientes (§7.2) ni pasó por la revisión contra el backend real de M7 que sí tuvo `notify_cama_lista` (changelog #14). Estaba activamente cableada en `procesar_alta_medica` y era **bloqueante**: `if not facturacion.notify_cierre_cama(...): raise 502` — con `mock_external_services=False` en producción, cualquier alta médica real hubiera fallado con `502` contra un endpoint que M7 nunca implementó. Sin test para el camino real (pasaba siempre por el atajo de `mock_external_services=True`).
|
| 532 |
+
34. **Corregido el gating bloqueante de `monitoreo.notify_baja` en `procesar_alta_medica`.** Era el único de los 5 call sites de `notify_alta`/`notify_baja` en todo el código que trataba la llamada como bloqueante (`if not ...: raise 502`); los otros 4 (`cama_service.py` ingreso/traslado, `solicitud_service.py` aprobar internación/traslado) ya la tratan fire-and-forget. Alineado con el resto del código y con el principio de §2 ("que el receptor esté caído no debe revertir el alta del paciente"): ahora es `monitoreo.notify_baja(paciente_id)` sin gate.
|
| 533 |
+
35. **El alta médica ya no depende de M7 ni M9 para completarse.** La notificación real a M7 (`CAMA_LISTA`) sigue ocurriendo, fire-and-forget, más adelante en el flujo (al completar la limpieza, `cama_service.py`). Blindado con tests: `test_alta_medica_ok_aunque_monitoreo_falle` y `test_alta_medica_no_llama_a_facturacion` (`tests/test_webhooks.py`).
|
| 534 |
+
|
| 535 |
+
### 14.8 Auto-transición de reservas de quirófano por horario (2026-07)
|
| 536 |
+
|
| 537 |
+
36. **Nuevo `cama_service.procesar_transiciones_automaticas`** (§5.4): avanza `RESERVADA→EN_CURSO` y `EN_CURSO→COMPLETADA` según `fecha_hora_inicio`/`fecha_hora_fin_estimada`, reusando `update_reserva_estado` — mismos side-effects que la transición manual, cero lógica de negocio duplicada. Nuevas queries `reserva_crud.get_pendientes_de_inicio`/`get_pendientes_de_fin`.
|
| 538 |
+
37. **Nuevo endpoint `POST /api/v1/internal/reservas/tick`** (`app/routers/internal.py`), protegido con secreto compartido (`settings.internal_tick_secret`, header `X-Internal-Token`) en vez de JWT de sesión — no hay usuario humano detrás de un cron. Pensado para dispararse desde un cron externo (GitHub Actions/cron-job.org), no un scheduler en memoria: el deploy en HF Spaces (tier gratuito) duerme el contenedor tras inactividad, y un loop interno se congelaría con él. Verificado en vivo contra la base real: primer tick transicionó reservas vencidas (`{"iniciadas":7,"completadas":7}`), el segundo tick inmediato confirmó la idempotencia (`{"iniciadas":0,"completadas":0}`).
|
| 539 |
+
|
| 540 |
+
### 14.9 Integración real con M7: evento `facturacion.internacion.cama-lista.requested` (2026-07)
|
| 541 |
+
|
| 542 |
+
38. **M7 confirmó su integración por escrito** (`documentation/integrations/M7_integration.md`): cola `facturacion.requests`, `event_type_id: 19` (activado en config, ya no `None`), `publisher_module: "modulo_6"`. Verificado en vivo: `POST /events/log` contra el Core real con este `event_type_id` devuelve `201`.
|
| 543 |
+
39. **Payload rico, distinto del REST.** El evento del Core lleva `{evento: CIERRE_INTERNACION, idEventoExterno, idInternacionExterna, idEpisodioExterno, idPacienteExterno, fechaIngreso, fechaAlta, tipoAlta, timestampEvento}` — mucho más rico que el REST de siempre (que M7 documenta como fallback/testing manual y no cambió). `notify_cama_lista` ahora arma **dos payloads distintos** para los dos canales (`app/integrations/facturacion.py`).
|
| 544 |
+
40. **Nuevas columnas en `camas`: `solicitud_hce_id`, `fecha_ingreso`, `alta_tipo`, `alta_timestamp`** (§10). Sin esto, M6 no tenía cómo reconstruir el payload rico en el momento de `notify_cama_lista` — esos datos ocurrían antes (aprobación de solicitud, alta médica) y se perdían. Se setean en `_aprobar_internacion`/`_aprobar_traslado`/`procesar_alta_medica` y se limpian al cerrar el episodio. En un traslado, se heredan de la cama origen (mismo episodio), no de la solicitud de traslado.
|
| 545 |
+
41. **`core_events.publish_event` gana el parámetro `publisher_module`** (default `"internacion"`, sin cambiar los otros 3 call sites de M1/M9). M7 es el primero en confirmar por escrito que espera `"modulo_6"`.
|
| 546 |
+
42. **`solicitud_service.procesar_alta_medica` cambia de firma**: recibe el `AltaMedicaWebhook` completo en vez de solo `paciente_id`, para poder persistir `tipo_alta`/`timestamp` en la cama. Actualizados los dos call sites (`app/routers/webhooks.py`, `app/integrations/rabbit_consumer.py`).
|
| 547 |
+
43. **Bloqueante externo, documentado explícitamente: `idEpisodioExterno` viaja como `None`.** Ningún webhook de M1 provee ese dato hoy. Pendiente coordinar con M1 que lo agregue a `AltaMedicaWebhook` (ver `documentation/M6_INTEGRACION_M1_HCE.md`). Confirmado con M7 (vía su documentación) que el evento no se rechaza por esto — queda pendiente de completar de su lado.
|
| 548 |
+
44. **Revierte parcialmente la decisión del changelog #14** ("M6 no es intermediario del episodio... no enviamos idEpisodioExterno"). Esa decisión asumía que el payload rico era una recomendación opcional de M7; ahora M7 confirmó por escrito que es el contrato real de la integración final, no una opción descartable.
|
documentation/M6_demo_payloads.md
DELETED
|
@@ -1,291 +0,0 @@
|
|
| 1 |
-
# M6 — Payloads de demo (webhooks entrantes)
|
| 2 |
-
|
| 3 |
-
Ejemplos listos para copiar y pegar de los webhooks que **otros módulos llaman sobre M6**.
|
| 4 |
-
Backend real (desplegado): `https://modulo-6-api.hf.space/api/v1`.
|
| 5 |
-
Docs interactivas: `https://modulo-6-api.hf.space/api/v1/docs`.
|
| 6 |
-
|
| 7 |
-
> Todos estos endpoints requieren **autenticación JWT** (`Authorization: Bearer <token>`).
|
| 8 |
-
> Si el backend tiene habilitado el endpoint de token de desarrollo (`ENVIRONMENT=development`),
|
| 9 |
-
> obtené uno así:
|
| 10 |
-
>
|
| 11 |
-
> ```bash
|
| 12 |
-
> curl "https://modulo-6-api.hf.space/api/v1/auth/token?usuario=ADMINISTRATIVO&password=x"
|
| 13 |
-
> ```
|
| 14 |
-
>
|
| 15 |
-
> Respuesta: `{ "access_token": "eyJ...", "token_type": "bearer", "rol": "ADMINISTRATIVO" }`.
|
| 16 |
-
> Si está en modo producción, ese endpoint devuelve `404` y el token lo tenés que emitir
|
| 17 |
-
> desde Core (M10). En cualquier caso, exportalo para reutilizarlo en los `curl` de abajo:
|
| 18 |
-
>
|
| 19 |
-
> ```bash
|
| 20 |
-
> export TOKEN="eyJ..."
|
| 21 |
-
> ```
|
| 22 |
-
|
| 23 |
-
Convenciones: timestamps en **ISO 8601 UTC con sufijo `Z`**. IDs de cama/paciente son `integer`;
|
| 24 |
-
los IDs de origen externos (`solicitud_hce_id`, etc.) son `string` con prefijo.
|
| 25 |
-
|
| 26 |
-
---
|
| 27 |
-
|
| 28 |
-
## 1. [M1] Recibir solicitud — internación o traslado
|
| 29 |
-
|
| 30 |
-
`POST /webhooks/hce/solicitud` · emisor: **M1 HCE** · crea la solicitud en estado `PENDIENTE`.
|
| 31 |
-
El mismo endpoint cubre los dos casos según `tipo`.
|
| 32 |
-
|
| 33 |
-
### 1.a — Internación (desde guardia)
|
| 34 |
-
|
| 35 |
-
```bash
|
| 36 |
-
curl -X POST "https://modulo-6-api.hf.space/api/v1/webhooks/hce/solicitud" \
|
| 37 |
-
-H "Authorization: Bearer $TOKEN" \
|
| 38 |
-
-H "Content-Type: application/json" \
|
| 39 |
-
-d '{
|
| 40 |
-
"tipo": "INTERNACION",
|
| 41 |
-
"solicitud_hce_id": "HCE-SOL-001",
|
| 42 |
-
"paciente_id": 7,
|
| 43 |
-
"medico_solicitante_id": 10,
|
| 44 |
-
"cama_solicitada_id": 101,
|
| 45 |
-
"origen": "GUARDIA",
|
| 46 |
-
"diagnostico_ingreso": "Neumonía adquirida en la comunidad",
|
| 47 |
-
"obra_social_id": "OSDE-210",
|
| 48 |
-
"numero_afiliado": "A-99887766",
|
| 49 |
-
"prioridad": "ALTA",
|
| 50 |
-
"hospital_id": "HOSP-001",
|
| 51 |
-
"observaciones": "Paciente requiere oxígeno suplementario",
|
| 52 |
-
"timestamp": "2025-01-18T10:30:00Z"
|
| 53 |
-
}'
|
| 54 |
-
```
|
| 55 |
-
|
| 56 |
-
### 1.b — Internación por cirugía programada
|
| 57 |
-
|
| 58 |
-
Igual que 1.a pero con `origen: "CIRUGIA_PROGRAMADA"` y `turno_id` del turno quirúrgico
|
| 59 |
-
(M6 lo valida contra M2 antes de aprobar).
|
| 60 |
-
|
| 61 |
-
```bash
|
| 62 |
-
curl -X POST "https://modulo-6-api.hf.space/api/v1/webhooks/hce/solicitud" \
|
| 63 |
-
-H "Authorization: Bearer $TOKEN" \
|
| 64 |
-
-H "Content-Type: application/json" \
|
| 65 |
-
-d '{
|
| 66 |
-
"tipo": "INTERNACION",
|
| 67 |
-
"solicitud_hce_id": "HCE-SOL-002",
|
| 68 |
-
"paciente_id": 12,
|
| 69 |
-
"medico_solicitante_id": 10,
|
| 70 |
-
"cama_solicitada_id": 205,
|
| 71 |
-
"origen": "CIRUGIA_PROGRAMADA",
|
| 72 |
-
"turno_id": 5501,
|
| 73 |
-
"diagnostico_ingreso": "Postoperatorio colecistectomía",
|
| 74 |
-
"prioridad": "MEDIA",
|
| 75 |
-
"hospital_id": "HOSP-001",
|
| 76 |
-
"timestamp": "2025-01-18T11:00:00Z"
|
| 77 |
-
}'
|
| 78 |
-
```
|
| 79 |
-
|
| 80 |
-
### 1.c — Traslado / pase de piso
|
| 81 |
-
|
| 82 |
-
```bash
|
| 83 |
-
curl -X POST "https://modulo-6-api.hf.space/api/v1/webhooks/hce/solicitud" \
|
| 84 |
-
-H "Authorization: Bearer $TOKEN" \
|
| 85 |
-
-H "Content-Type: application/json" \
|
| 86 |
-
-d '{
|
| 87 |
-
"tipo": "TRASLADO",
|
| 88 |
-
"solicitud_hce_id": "HCE-SOL-003",
|
| 89 |
-
"paciente_id": 7,
|
| 90 |
-
"medico_solicitante_id": 10,
|
| 91 |
-
"cama_origen_id": 101,
|
| 92 |
-
"cama_destino_solicitada_id": 310,
|
| 93 |
-
"motivo_traslado": "Mejora clínica, pasa de UTI a sala común",
|
| 94 |
-
"prioridad": "BAJA",
|
| 95 |
-
"hospital_id": "HOSP-001",
|
| 96 |
-
"timestamp": "2025-01-18T14:20:00Z"
|
| 97 |
-
}'
|
| 98 |
-
```
|
| 99 |
-
|
| 100 |
-
**Campos.** Requeridos siempre: `tipo`, `solicitud_hce_id`, `paciente_id`, `medico_solicitante_id`, `timestamp`.
|
| 101 |
-
`tipo`: `INTERNACION` | `TRASLADO`. `origen`: `GUARDIA` | `CIRUGIA_PROGRAMADA`.
|
| 102 |
-
`prioridad`: `MUY_BAJA` | `BAJA` | `MEDIA` | `ALTA` | `MUY_ALTA` | `URGENTE`.
|
| 103 |
-
Para `TRASLADO` se usan `cama_origen_id` y `cama_destino_solicitada_id`; el resto es opcional.
|
| 104 |
-
|
| 105 |
-
**Respuesta 200:**
|
| 106 |
-
|
| 107 |
-
```json
|
| 108 |
-
{
|
| 109 |
-
"mensaje": "Solicitud recibida y pendiente de aprobación",
|
| 110 |
-
"solicitud_id": "SOL-00001",
|
| 111 |
-
"estado": "PENDIENTE"
|
| 112 |
-
}
|
| 113 |
-
```
|
| 114 |
-
|
| 115 |
-
---
|
| 116 |
-
|
| 117 |
-
## 2. [M1] Recibir solicitud de cirugía urgente
|
| 118 |
-
|
| 119 |
-
`POST /webhooks/hce/cirugia-urgente` · emisor: **M1 HCE**.
|
| 120 |
-
Algoritmo **ASAP**: `fecha_hora_inicio` se interpreta como "no antes de" y la resta con
|
| 121 |
-
`fecha_hora_fin_estimada` como la duración de la cirugía. M6 calcula, entre los quirófanos
|
| 122 |
-
compatibles (mismo hospital, operables), el inicio más temprano posible y asigna ahí —
|
| 123 |
-
el horario final puede no coincidir con el pedido. Si para lograrlo hay que correr alguna
|
| 124 |
-
reserva programada, esa reserva **no se cancela**: se **reprograma** en M2 (algoritmo
|
| 125 |
-
`reprogramar()`) preservando su duración. Reservas `EN_CURSO` o ya `URGENTE` nunca se
|
| 126 |
-
desplazan; pueden ser varias las reservas desplazadas dentro de la ventana elegida.
|
| 127 |
-
|
| 128 |
-
```bash
|
| 129 |
-
curl -X POST "https://modulo-6-api.hf.space/api/v1/webhooks/hce/cirugia-urgente" \
|
| 130 |
-
-H "Authorization: Bearer $TOKEN" \
|
| 131 |
-
-H "Content-Type: application/json" \
|
| 132 |
-
-d '{
|
| 133 |
-
"solicitud_urgencia_hce_id": "HCE-URG-001",
|
| 134 |
-
"paciente_id": 33,
|
| 135 |
-
"medico_cirujano_id": 22,
|
| 136 |
-
"medico_solicitante_id": 10,
|
| 137 |
-
"fecha_hora_inicio": "2025-01-18T16:00:00Z",
|
| 138 |
-
"fecha_hora_fin_estimada": "2025-01-18T18:00:00Z",
|
| 139 |
-
"diagnostico": "Apendicitis aguda perforada",
|
| 140 |
-
"hospital_id": "HOSP-001",
|
| 141 |
-
"timestamp": "2025-01-18T15:45:00Z"
|
| 142 |
-
}'
|
| 143 |
-
```
|
| 144 |
-
|
| 145 |
-
**Campos.** Requeridos: `solicitud_urgencia_hce_id`, `paciente_id`, `medico_cirujano_id`,
|
| 146 |
-
`medico_solicitante_id`, `fecha_hora_inicio`, `fecha_hora_fin_estimada`, `timestamp`.
|
| 147 |
-
`fecha_hora_inicio` debe ser anterior a `fecha_hora_fin_estimada` (si no → `422`).
|
| 148 |
-
Opcionales: `diagnostico`, `hospital_id`, `specialty_id` (preferencia de especialidad del
|
| 149 |
-
quirófano; si no hay quirófano libre de esa especialidad se usa cualquier otro compatible
|
| 150 |
-
del hospital, no se deja al paciente sin asignar).
|
| 151 |
-
|
| 152 |
-
**Respuesta 201 (sin desplazamiento):**
|
| 153 |
-
|
| 154 |
-
```json
|
| 155 |
-
{
|
| 156 |
-
"mensaje": "Reserva urgente creada exitosamente",
|
| 157 |
-
"reserva": {
|
| 158 |
-
"id": 9,
|
| 159 |
-
"cama_id": 501,
|
| 160 |
-
"origen": "EMERGENCIA",
|
| 161 |
-
"estado": "RESERVADA",
|
| 162 |
-
"prioridad": "URGENTE",
|
| 163 |
-
"paciente_id": 33
|
| 164 |
-
},
|
| 165 |
-
"reservas_desplazadas": []
|
| 166 |
-
}
|
| 167 |
-
```
|
| 168 |
-
|
| 169 |
-
**Respuesta 201 (con desplazamiento):** `reservas_desplazadas` trae la(s) reserva(s)
|
| 170 |
-
programada(s) que fueron reprogramadas (siguen `RESERVADA`, con nuevo horario; `turno_id`
|
| 171 |
-
reprogramado en M2 si correspondía). Puede haber más de una si varias caían dentro de la
|
| 172 |
-
ventana elegida.
|
| 173 |
-
|
| 174 |
-
**Respuesta 200:** si `solicitud_urgencia_hce_id` ya se había procesado (idempotencia),
|
| 175 |
-
se devuelve la reserva existente sin crear nada nuevo, con `200` en vez de `201`.
|
| 176 |
-
|
| 177 |
-
**Respuesta 409** `SIN_QUIROFANO_COMPATIBLE`: no hay ningún quirófano operable
|
| 178 |
-
(`FUERA_DE_SERVICIO`/`BAJA_PERMANENTE`/`EN_LIMPIEZA` excluidos) para el `hospital_id`
|
| 179 |
-
indicado.
|
| 180 |
-
|
| 181 |
-
---
|
| 182 |
-
|
| 183 |
-
## 3. [M9] Recibir alerta de emergencia (código rojo)
|
| 184 |
-
|
| 185 |
-
`POST /webhooks/monitoreo/alerta-emergencia` · emisor: **M9 Monitoreo**.
|
| 186 |
-
M6 localiza la cama `OCUPADA` del paciente y la pone en `CODIGO_ROJO`.
|
| 187 |
-
|
| 188 |
-
```bash
|
| 189 |
-
curl -X POST "https://modulo-6-api.hf.space/api/v1/webhooks/monitoreo/alerta-emergencia" \
|
| 190 |
-
-H "Authorization: Bearer $TOKEN" \
|
| 191 |
-
-H "Content-Type: application/json" \
|
| 192 |
-
-d '{
|
| 193 |
-
"paciente_id": 7,
|
| 194 |
-
"observaciones": "HR > 140 sostenida por 3 min, SpO2 88%",
|
| 195 |
-
"timestamp": "2025-01-18T19:05:00Z"
|
| 196 |
-
}'
|
| 197 |
-
```
|
| 198 |
-
|
| 199 |
-
**Campos.** Requeridos: `paciente_id`, `timestamp`. Opcional: `observaciones`.
|
| 200 |
-
|
| 201 |
-
**Respuesta 200:**
|
| 202 |
-
|
| 203 |
-
```json
|
| 204 |
-
{
|
| 205 |
-
"mensaje": "Alerta registrada. Cama 101 en CODIGO_ROJO.",
|
| 206 |
-
"cama_id": 101,
|
| 207 |
-
"sector": "UTI"
|
| 208 |
-
}
|
| 209 |
-
```
|
| 210 |
-
|
| 211 |
-
> Si el paciente no tiene cama asignada → `404`.
|
| 212 |
-
|
| 213 |
-
---
|
| 214 |
-
|
| 215 |
-
## 4. [M9] Recibir alerta resuelta
|
| 216 |
-
|
| 217 |
-
`POST /webhooks/monitoreo/alerta-resuelta` · emisor: **M9 Monitoreo**.
|
| 218 |
-
La cama vuelve de `CODIGO_ROJO` a `OCUPADA` (no a `DISPONIBLE`).
|
| 219 |
-
|
| 220 |
-
```bash
|
| 221 |
-
curl -X POST "https://modulo-6-api.hf.space/api/v1/webhooks/monitoreo/alerta-resuelta" \
|
| 222 |
-
-H "Authorization: Bearer $TOKEN" \
|
| 223 |
-
-H "Content-Type: application/json" \
|
| 224 |
-
-d '{
|
| 225 |
-
"paciente_id": 7,
|
| 226 |
-
"motivo_resolucion": "Paciente estabilizado tras intervención de enfermería",
|
| 227 |
-
"timestamp": "2025-01-18T19:20:00Z"
|
| 228 |
-
}'
|
| 229 |
-
```
|
| 230 |
-
|
| 231 |
-
**Campos.** Requeridos: `paciente_id`, `timestamp`. Opcional: `motivo_resolucion`.
|
| 232 |
-
|
| 233 |
-
**Respuesta 200:**
|
| 234 |
-
|
| 235 |
-
```json
|
| 236 |
-
{
|
| 237 |
-
"mensaje": "Alerta resuelta. Cama 101 volvió a estado OCUPADA.",
|
| 238 |
-
"cama_id": 101,
|
| 239 |
-
"estado_anterior": "CODIGO_ROJO",
|
| 240 |
-
"estado_actual": "OCUPADA"
|
| 241 |
-
}
|
| 242 |
-
```
|
| 243 |
-
|
| 244 |
-
> Si no hay cama en `CODIGO_ROJO` para ese paciente → `404`.
|
| 245 |
-
|
| 246 |
-
---
|
| 247 |
-
|
| 248 |
-
## 5. [M2] Cancelar reserva de quirófano por turno
|
| 249 |
-
|
| 250 |
-
`POST /turnos/{turnoId}/cancelacion` · emisor: **M2 Turnos**.
|
| 251 |
-
`turnoId` (entero, el id del turno en M2) va en la URL. M6 busca la reserva asociada al
|
| 252 |
-
turno y la pasa a `CANCELADA`, liberando el quirófano.
|
| 253 |
-
|
| 254 |
-
```bash
|
| 255 |
-
curl -X POST "https://modulo-6-api.hf.space/api/v1/turnos/5501/cancelacion" \
|
| 256 |
-
-H "Authorization: Bearer $TOKEN" \
|
| 257 |
-
-H "Content-Type: application/json" \
|
| 258 |
-
-d '{
|
| 259 |
-
"motivo": "El paciente reprogramó la cirugía",
|
| 260 |
-
"tipo_cancelacion": "REPROGRAMACION",
|
| 261 |
-
"timestamp": "2025-01-18T09:10:00Z"
|
| 262 |
-
}'
|
| 263 |
-
```
|
| 264 |
-
|
| 265 |
-
**Campos.** Requeridos: `motivo`, `timestamp`. Opcional: `tipo_cancelacion`.
|
| 266 |
-
|
| 267 |
-
**Respuesta 200:**
|
| 268 |
-
|
| 269 |
-
```json
|
| 270 |
-
{
|
| 271 |
-
"mensaje": "Reserva de quirófano cancelada correctamente",
|
| 272 |
-
"reserva_id": 9,
|
| 273 |
-
"turno_id": 5501,
|
| 274 |
-
"cama_id": 501,
|
| 275 |
-
"estado": "CANCELADA"
|
| 276 |
-
}
|
| 277 |
-
```
|
| 278 |
-
|
| 279 |
-
> Estados de la respuesta: si la reserva ya estaba `CANCELADA`, responde igual (idempotente).
|
| 280 |
-
> Si está `EN_CURSO` o `COMPLETADA` → `409` (no cancelable). Si no existe reserva para el turno → `404`.
|
| 281 |
-
|
| 282 |
-
---
|
| 283 |
-
|
| 284 |
-
## Orden sugerido para la demo
|
| 285 |
-
|
| 286 |
-
1. Crear una cama y un quirófano (`POST /camas`, `POST /quirofanos`).
|
| 287 |
-
2. **(1.a)** Internar un paciente: webhook de solicitud → `PATCH /solicitudes/{id}` para aprobar.
|
| 288 |
-
3. **(3)** Disparar alerta de emergencia sobre ese paciente → ver cama en `CODIGO_ROJO`.
|
| 289 |
-
4. **(4)** Resolver la alerta → cama vuelve a `OCUPADA`.
|
| 290 |
-
5. **(5)** Crear una reserva programada (`POST /quirofanos/{id}/reservas`) y cancelarla por turno.
|
| 291 |
-
6. **(2)** Disparar una cirugía urgente que desplace a una programada existente.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
documentation/integracion_m7_estado.md
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Estado de Integración M6 ↔ M7 (Facturación)
|
| 2 |
+
|
| 3 |
+
> **Fecha de revisión:** 2026-07-12
|
| 4 |
+
> **Módulo origen:** M6 — Internación y Gestión de Camas
|
| 5 |
+
> **Módulo destino:** M7 — Facturación
|
| 6 |
+
> **Dirección del flujo:** unidireccional M6 → M7 (M7 no envía datos a M6)
|
| 7 |
+
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
## Método de integración
|
| 11 |
+
|
| 12 |
+
### Canal principal — Evento asincrónico vía Core/RabbitMQ (M10)
|
| 13 |
+
|
| 14 |
+
M6 publica un evento al bus del Core cuando se cierra una internación. M7 consume ese evento desde su cola `facturacion.requests`.
|
| 15 |
+
|
| 16 |
+
```
|
| 17 |
+
M6 backend
|
| 18 |
+
└─ POST /webhooks/hce/alta-medica (M1 avisa el alta médica)
|
| 19 |
+
└─ solicitud_service.procesar_alta_medica()
|
| 20 |
+
└─ facturacion.notify_cama_lista(cama, db)
|
| 21 |
+
└─ POST https://api.healthcare.cantero.ar/events/log
|
| 22 |
+
payload:
|
| 23 |
+
event_type_id: 19
|
| 24 |
+
publisher_module: "modulo_6"
|
| 25 |
+
payload: JSON.stringify({ evento: "CIERRE_INTERNACION", ... })
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
Datos del evento confirmados por M7:
|
| 29 |
+
```
|
| 30 |
+
event_name: facturacion.internacion.cama-lista.requested
|
| 31 |
+
event_type_id: 19
|
| 32 |
+
queue: facturacion.requests
|
| 33 |
+
publisher: modulo_6
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
### Canal fallback — REST directo a M7
|
| 37 |
+
|
| 38 |
+
Para testing manual o ante caída del Core, M7 expone dos endpoints REST que usan el mismo schema `InternacionM6Request`:
|
| 39 |
+
|
| 40 |
+
| Endpoint | Comportamiento |
|
| 41 |
+
|----------|---------------|
|
| 42 |
+
| `POST /api/v1/webhooks/internacion/cama-lista` | Persiste el evento, idempotente por `idEventoExterno` |
|
| 43 |
+
| `POST /api/integracion/internacion/cierre-episodio` | Igual + **si recibe paciente y episodio, consulta M1/HCE y registra los actos médicos facturables automáticamente** |
|
| 44 |
+
|
| 45 |
+
Ambos endpoints están implementados en `app/integrations/facturacion.py::notify_cama_lista()`.
|
| 46 |
+
|
| 47 |
+
> El endpoint `cierre-episodio` es el preferible para producción porque hace más trabajo automático del lado de M7.
|
| 48 |
+
|
| 49 |
+
---
|
| 50 |
+
|
| 51 |
+
## Schema `InternacionM6Request` (OpenAPI de M7)
|
| 52 |
+
|
| 53 |
+
Ambos endpoints REST usan el mismo schema. **Solo 2 campos son `required`.**
|
| 54 |
+
|
| 55 |
+
| Campo | Tipo | Req | Descripción |
|
| 56 |
+
|-------|------|-----|-------------|
|
| 57 |
+
| `idPacienteExterno` | `integer` | ✅ | ID numérico del paciente |
|
| 58 |
+
| `timestampEvento` | `datetime` | ✅ | Timestamp del cierre |
|
| 59 |
+
| `evento` | `string` | — | `"CIERRE_INTERNACION"` o `"CAMA_LISTA"` |
|
| 60 |
+
| `camaId` | `string` | — | ID de la cama |
|
| 61 |
+
| `idEventoExterno` | `string` | — | Clave de idempotencia |
|
| 62 |
+
| `idInternacionExterna` | `string` | — | ID de la solicitud HCE |
|
| 63 |
+
| `idEpisodioExterno` | `string` | — | ID del episodio clínico (M1) |
|
| 64 |
+
| `fechaIngreso` | `datetime` | — | Fecha de ingreso a la cama |
|
| 65 |
+
| `fechaAlta` | `datetime` | — | Fecha del alta médica |
|
| 66 |
+
| `tipoAlta` | `string` | — | Ej: `"ALTA_MEDICA"` |
|
| 67 |
+
| `medicoSolicitanteId` | `string` | — | ID del médico solicitante |
|
| 68 |
+
| `medicoFirmanteId` | `string` | — | ID del médico firmante del alta |
|
| 69 |
+
| `diagnosticoIngreso` | `string` | — | Diagnóstico de ingreso |
|
| 70 |
+
| `observaciones` | `string` | — | Observaciones adicionales |
|
| 71 |
+
| `camasUtilizadas` | `array` | — | Tramos de uso de cama (ver abajo) |
|
| 72 |
+
|
| 73 |
+
`camasUtilizadas[]` (cada ítem):
|
| 74 |
+
```json
|
| 75 |
+
{ "camaId": "101", "sector": "SALA_COMUN", "tipoCama": "SALA_COMUN",
|
| 76 |
+
"desde": "2026-06-20T14:30:00Z", "hasta": "2026-06-22T09:00:00Z" }
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
**Payload que enviamos actualmente** (canal Core/RabbitMQ — evento `CIERRE_INTERNACION`):
|
| 80 |
+
```json
|
| 81 |
+
{
|
| 82 |
+
"evento": "CIERRE_INTERNACION",
|
| 83 |
+
"idEventoExterno": "M6-CIERRE-INT-{cama_id}-{paciente_id}-{fecha}",
|
| 84 |
+
"idInternacionExterna": "{solicitud_hce_id}",
|
| 85 |
+
"idEpisodioExterno": null,
|
| 86 |
+
"idPacienteExterno": "{paciente_id}",
|
| 87 |
+
"fechaIngreso": "2026-06-20T14:30:00+00:00",
|
| 88 |
+
"fechaAlta": "2026-06-25T10:00:00+00:00",
|
| 89 |
+
"tipoAlta": "ALTA_MEDICA",
|
| 90 |
+
"timestampEvento": "2026-06-25T10:05:00+00:00"
|
| 91 |
+
}
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
> **Nota:** cuando M7 recibe `idPacienteExterno` + `idEpisodioExterno`, consulta M1/HCE automáticamente para registrar los actos médicos facturables del episodio. Sin `idEpisodioExterno` el cierre queda pendiente de completar de su lado.
|
| 95 |
+
|
| 96 |
+
---
|
| 97 |
+
|
| 98 |
+
## ✅ Hecho
|
| 99 |
+
|
| 100 |
+
| Qué | Dónde |
|
| 101 |
+
|-----|-------|
|
| 102 |
+
| Cliente de integración `notify_cama_lista()` | `app/integrations/facturacion.py` |
|
| 103 |
+
| Publicación de evento Core vía `publish_event()` | `app/integrations/core_events.py` |
|
| 104 |
+
| Payload rico `CIERRE_INTERNACION` (canal principal) | `facturacion.py` línea 51–64 |
|
| 105 |
+
| Payload mínimo `CAMA_LISTA` (canal fallback REST) | `facturacion.py` línea 40–48 |
|
| 106 |
+
| Persistencia de datos del episodio en `Cama` | `app/models/cama.py` (campos `solicitud_hce_id`, `fecha_ingreso`, `alta_tipo`, `alta_timestamp`) |
|
| 107 |
+
| Datos del episodio se guardan al aprobar internación | `solicitud_service.py` línea 202–203 |
|
| 108 |
+
| Datos del alta se guardan al procesar alta médica | `solicitud_service.py` línea 353–354 |
|
| 109 |
+
| Disparo en el momento correcto: alta médica (webhook de M1) | `solicitud_service.py::procesar_alta_medica` |
|
| 110 |
+
| Test de regresión: alta médica debe notificar a M7 | `tests/test_webhooks.py::test_alta_medica_notifica_a_facturacion` |
|
| 111 |
+
| Idempotencia del evento (`idEventoExterno` estable) | `facturacion.py` línea 38 |
|
| 112 |
+
| URL de M7 configurable | `config.py` → `m7_facturacion_url` |
|
| 113 |
+
| Variable de configuración `facturacion_cama_lista_event_type_id` | `config.py` línea 108 |
|
| 114 |
+
| Tests de integración (REST, evento Core, mock) | `tests/test_core_events.py` líneas 128–189 |
|
| 115 |
+
| Documentación del contrato de M7 | `documentation/integrations/M7_integration.md` |
|
| 116 |
+
|
| 117 |
+
---
|
| 118 |
+
|
| 119 |
+
## 🐛 Bugs encontrados al contrastar con el OpenAPI de M7
|
| 120 |
+
|
| 121 |
+
Hallados al comparar `app/integrations/facturacion.py` contra el schema real (`InternacionM6Request`):
|
| 122 |
+
|
| 123 |
+
### Bug 1 — REST fallback con nombres de campo incorrectos
|
| 124 |
+
|
| 125 |
+
El payload del canal REST fallback usa snake_case pero el schema espera camelCase:
|
| 126 |
+
|
| 127 |
+
| Código actual | Schema real |
|
| 128 |
+
|---------------|-------------|
|
| 129 |
+
| `"cama_id"` | `"camaId"` |
|
| 130 |
+
| `"paciente_id"` | `"idPacienteExterno"` |
|
| 131 |
+
| `"timestamp_evento"` | `"timestampEvento"` |
|
| 132 |
+
|
| 133 |
+
Esto significa que el canal REST fallback está enviando campos que M7 no reconoce (los ignora silenciosamente) y **no está enviando los campos que M7 sí lee**.
|
| 134 |
+
**Archivo:** `app/integrations/facturacion.py` línea 40–48.
|
| 135 |
+
|
| 136 |
+
### Bug 2 — `idPacienteExterno` enviado como string, el schema exige integer
|
| 137 |
+
|
| 138 |
+
El canal Core/RabbitMQ construye el payload con `"idPacienteExterno": str(paciente_id)`.
|
| 139 |
+
El OpenAPI de M7 define `idPacienteExterno` como `integer (int64)`.
|
| 140 |
+
**Archivo:** `app/integrations/facturacion.py` línea 57.
|
| 141 |
+
|
| 142 |
+
### Campos que M7 acepta y no estamos enviando (opcionales)
|
| 143 |
+
|
| 144 |
+
Los siguientes campos del schema están disponibles pero no los usamos todavía:
|
| 145 |
+
- `camaId` — ID de la cama (disponible en `cama.id`)
|
| 146 |
+
- `medicoFirmanteId` — ID del médico firmante (viene en `AltaMedicaWebhook.medico_firmante_id`, ya lo tenemos en el webhook pero no lo persistimos en `Cama`)
|
| 147 |
+
- `diagnosticoIngreso` — no se persiste en M6
|
| 148 |
+
- `camasUtilizadas[]` — tramos de uso de cama (ver sección dedicada abajo)
|
| 149 |
+
|
| 150 |
+
---
|
| 151 |
+
|
| 152 |
+
## 🟡 A medias / pendiente de activar
|
| 153 |
+
|
| 154 |
+
### 1. `idEpisodioExterno` va siempre como `null`
|
| 155 |
+
|
| 156 |
+
M1 no provee el ID del episodio clínico en el webhook `AltaMedicaWebhook`. El campo viaja como `null` en el evento a M7.
|
| 157 |
+
**Impacto:** M7 confirmó que el evento no se rechaza, pero queda "pendiente de completar" de su lado hasta que M1 lo provea.
|
| 158 |
+
**Desbloqueante:** coordinación con el equipo de M1 para que incluyan `episodio_id` en el payload del alta.
|
| 159 |
+
|
| 160 |
+
### 2. `FACTURACION_CAMA_LISTA_EVENT_TYPE_ID` ya configurado en `.env`, pero bloqueado por mock
|
| 161 |
+
|
| 162 |
+
El `event_type_id=19` está seteado en el `.env` real (`FACTURACION_CAMA_LISTA_EVENT_TYPE_ID=19`). Sin embargo, `MOCK_EXTERNAL_SERVICES=true` hace que `notify_cama_lista()` retorne `True` de inmediato sin hacer ningún request.
|
| 163 |
+
**Impacto:** el canal Core/RabbitMQ está configurado pero inactivo en dev. En producción, para que realmente dispare hay que asegurarse de que `MOCK_EXTERNAL_SERVICES=false`.
|
| 164 |
+
**Nota:** el `.env.example` lo tiene comentado por diseño (para que quien clone el repo no active el event bus sin querer).
|
| 165 |
+
|
| 166 |
+
### 3. Credenciales de cuenta de servicio no configuradas
|
| 167 |
+
|
| 168 |
+
El header `Authorization` de las llamadas al Core requiere `CORE_SERVICE_EMAIL` y `CORE_SERVICE_PASSWORD`. Sin estos, el POST a `/events/log` sale sin auth.
|
| 169 |
+
**Para activar:** obtener las credenciales con el equipo de M10 y agregarlas al `.env`.
|
| 170 |
+
|
| 171 |
+
---
|
| 172 |
+
|
| 173 |
+
## 🔴 Falta
|
| 174 |
+
|
| 175 |
+
No hay bloqueantes de backend para el flujo principal. El único pendiente es coordinar `idEpisodioExterno` con M1 (ver sección 🟡).
|
| 176 |
+
|
| 177 |
+
---
|
| 178 |
+
|
| 179 |
+
## Flujo completo (cuando todo esté activado)
|
| 180 |
+
|
| 181 |
+
```
|
| 182 |
+
1. M1 → POST /webhooks/hce/alta-medica
|
| 183 |
+
└─ cama pasa a EN_LIMPIEZA
|
| 184 |
+
└─ se persisten alta_tipo y alta_timestamp en la cama
|
| 185 |
+
└─ facturacion.notify_cama_lista(cama, db) ←── acá se dispara M7
|
| 186 |
+
|
| 187 |
+
2. notify_cama_lista():
|
| 188 |
+
a) REST fallback → POST M7_URL/api/v1/webhooks/internacion/cama-lista (payload mínimo)
|
| 189 |
+
b) Core/RabbitMQ → POST Core/events/log (payload rico CIERRE_INTERNACION, event_type_id=19)
|
| 190 |
+
|
| 191 |
+
3. Personal de limpieza → PATCH /camas/{id} { estado: DISPONIBLE }
|
| 192 |
+
└─ cama_service limpia los campos del episodio de la cama (paciente_id, alta_tipo, etc.)
|
| 193 |
+
└─ cama queda disponible para el próximo paciente
|
| 194 |
+
|
| 195 |
+
4. M7 recibe el evento desde su cola facturacion.requests
|
| 196 |
+
└─ consulta a M1 con idPacienteExterno + idEpisodioExterno
|
| 197 |
+
└─ factura la internación con su propio ABM de obras sociales
|
| 198 |
+
```
|
| 199 |
+
|
| 200 |
+
---
|
| 201 |
+
|
| 202 |
+
## `camasUtilizadas[]` — cómo reconstruir los tramos
|
| 203 |
+
|
| 204 |
+
El campo `camasUtilizadas` es opcional en el schema de M7. Representa los tramos de uso de cada cama durante toda la internación (relevante cuando hubo traslados).
|
| 205 |
+
|
| 206 |
+
### Caso sin traslados (mayoría de casos)
|
| 207 |
+
|
| 208 |
+
En el momento en que `notify_cama_lista(cama, db)` dispara, la `cama` ya tiene todos los datos del único tramo:
|
| 209 |
+
|
| 210 |
+
```python
|
| 211 |
+
camas_utilizadas = [{
|
| 212 |
+
"camaId": str(cama.id),
|
| 213 |
+
"sector": cama.sector,
|
| 214 |
+
"tipoCama": cama.tipo,
|
| 215 |
+
"desde": cama.fecha_ingreso.isoformat() if cama.fecha_ingreso else None,
|
| 216 |
+
"hasta": cama.alta_timestamp.isoformat() if cama.alta_timestamp else None,
|
| 217 |
+
}]
|
| 218 |
+
```
|
| 219 |
+
|
| 220 |
+
### Caso con traslados — reconstrucción desde auditoria
|
| 221 |
+
|
| 222 |
+
Si el paciente pasó por múltiples camas, la información está en la tabla `auditoria`. Los eventos relevantes son:
|
| 223 |
+
|
| 224 |
+
| Evento | Qué marca |
|
| 225 |
+
|--------|-----------|
|
| 226 |
+
| `CAMA_ASIGNADA` | Inicio del tramo en esa cama (campo `cama_id`, `creado_en`) |
|
| 227 |
+
| `SOLICITUD_APROBADA` (traslado) | Fin del tramo anterior + inicio del siguiente (`detalle.cama_origen_id`, `detalle.cama_asignada_id`) |
|
| 228 |
+
| `CAMA_ALTA` | Fin del último tramo |
|
| 229 |
+
|
| 230 |
+
**Reconstrucción para un paciente que pasó por cama A → cama B:**
|
| 231 |
+
|
| 232 |
+
```
|
| 233 |
+
auditoria (ordenada por creado_en ASC, filtrada por paciente_id):
|
| 234 |
+
|
| 235 |
+
T1 → CAMA_ASIGNADA cama_id=1 ← ingreso a cama A
|
| 236 |
+
T2 → SOLICITUD_APROBADA cama_id=2, detalle.cama_origen_id=1 ← traslado A→B
|
| 237 |
+
T3 → CAMA_ALTA cama_id=2 ← alta médica en cama B
|
| 238 |
+
|
| 239 |
+
Tramos resultantes:
|
| 240 |
+
{ camaId:"1", desde:T1, hasta:T2 } ← tramo cama A
|
| 241 |
+
{ camaId:"2", desde:T2, hasta:T3 } ← tramo cama B (= cama final)
|
| 242 |
+
```
|
| 243 |
+
|
| 244 |
+
Para `sector` y `tipoCama` de cada `camaId` histórico: query a `camas` por id. Se asume que no cambiaron de sector/tipo desde que el paciente estuvo ahí.
|
| 245 |
+
|
| 246 |
+
### Query a auditoria
|
| 247 |
+
|
| 248 |
+
```python
|
| 249 |
+
resp = db.table("auditoria") \
|
| 250 |
+
.select("*") \
|
| 251 |
+
.eq("paciente_id", paciente_id) \
|
| 252 |
+
.in_("evento", ["CAMA_ASIGNADA", "SOLICITUD_APROBADA", "CAMA_ALTA"]) \
|
| 253 |
+
.order("creado_en") \
|
| 254 |
+
.execute()
|
| 255 |
+
```
|
| 256 |
+
|
| 257 |
+
### Implementación pendiente
|
| 258 |
+
|
| 259 |
+
Para implementar `camasUtilizadas` completo se requiere:
|
| 260 |
+
1. Pasar `db: Client` a `notify_cama_lista(cama, db)` (hoy no recibe la sesión de DB)
|
| 261 |
+
2. Actualizar el call site en `cama_service.py` línea 145
|
| 262 |
+
3. Agregar la función `_reconstruir_tramos(db, paciente_id, cama_final)` en `facturacion.py`
|
| 263 |
+
4. Actualizar tests en `test_core_events.py` (nueva firma + assert del campo)
|
| 264 |
+
|
| 265 |
+
**Estado:** pendiente de implementar. El campo es opcional, M7 no lo requiere para procesar el cierre.
|
| 266 |
+
|
| 267 |
+
---
|
| 268 |
+
|
| 269 |
+
## Checklist para poner el canal principal en producción
|
| 270 |
+
|
| 271 |
+
**Fixes de código requeridos (ver sección 🐛):**
|
| 272 |
+
- [ ] Corregir nombres de campo del REST fallback: `cama_id`→`camaId`, `paciente_id`→`idPacienteExterno`, `timestamp_evento`→`timestampEvento` (`facturacion.py` línea 40–48)
|
| 273 |
+
- [ ] Corregir tipo de `idPacienteExterno`: de `str(paciente_id)` a `paciente_id` (int) (`facturacion.py` línea 57)
|
| 274 |
+
|
| 275 |
+
**Configuración:**
|
| 276 |
+
- [ ] ~~`FACTURACION_CAMA_LISTA_EVENT_TYPE_ID=19`~~ ya configurado en `.env` ✓ — verificar que esté en el deploy de producción
|
| 277 |
+
- [ ] Setear `MOCK_EXTERNAL_SERVICES=false` en producción (hoy bloquea toda llamada saliente)
|
| 278 |
+
- [ ] Configurar `CORE_SERVICE_EMAIL` y `CORE_SERVICE_PASSWORD` con las credenciales reales de M6 en M10
|
| 279 |
+
- [ ] Confirmar con M10 que la cola `facturacion.requests` está bindeada al `event_type_id=19`
|
| 280 |
+
|
| 281 |
+
**Coordinación entre módulos:**
|
| 282 |
+
- [ ] Coordinar con M1 para que provea `episodio_id` en el webhook de alta (desbloquea `idEpisodioExterno` → M7 factura automáticamente)
|
| 283 |
+
- [ ] Verificar con M7 que los eventos están llegando y siendo procesados
|
| 284 |
+
|
| 285 |
+
**Mejoras opcionales (enriquecen el payload):**
|
| 286 |
+
- [ ] Implementar `camasUtilizadas[]` reconstruyendo tramos desde auditoria (requiere pasar `db` a `notify_cama_lista`)
|
| 287 |
+
- [ ] Persistir `medico_firmante_id` en `Cama` al procesar el alta médica para poder enviarlo como `medicoFirmanteId`
|
documentation/{M10_SSO_INTEGRATION_GUIDE.md → integrations/M10_SSO_INTEGRATION_GUIDE.md}
RENAMED
|
File without changes
|
documentation/{M10_integration.md → integrations/M10_integration.md}
RENAMED
|
File without changes
|
documentation/integrations/M7_integration.md
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Buenas, ya dejamos desplegado el Módulo 7 y lista la integración para recibir el evento de Módulo 6 vía Core/RabbitMQ.
|
| 2 |
+
|
| 3 |
+
Datos generales de M7:
|
| 4 |
+
|
| 5 |
+
URL base pública:
|
| 6 |
+
|
| 7 |
+
```txt
|
| 8 |
+
https://modulo7-backend.onrender.com
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
Swagger:
|
| 12 |
+
|
| 13 |
+
```txt
|
| 14 |
+
https://modulo7-backend.onrender.com/swagger-ui/index.html
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
OpenAPI:
|
| 18 |
+
|
| 19 |
+
```txt
|
| 20 |
+
https://modulo7-backend.onrender.com/v3/api-docs
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
Para endpoints REST, la base es:
|
| 24 |
+
|
| 25 |
+
```txt
|
| 26 |
+
https://modulo7-backend.onrender.com/api
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
Para la integración M6 → M7, la forma principal va por eventos usando Core/Módulo 10.
|
| 30 |
+
|
| 31 |
+
Datos del evento creado en Core:
|
| 32 |
+
|
| 33 |
+
```txt
|
| 34 |
+
event_name: facturacion.internacion.cama-lista.requested
|
| 35 |
+
event_type_id: 19
|
| 36 |
+
queue: facturacion.requests
|
| 37 |
+
publisher_module esperado: modulo_6
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
Ustedes tienen que publicar el evento en Core usando:
|
| 41 |
+
|
| 42 |
+
```http
|
| 43 |
+
POST https://api.healthcare.cantero.ar/events/log
|
| 44 |
+
Authorization: Bearer <token>
|
| 45 |
+
Content-Type: application/json
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
Body de ejemplo:
|
| 49 |
+
|
| 50 |
+
```json
|
| 51 |
+
{
|
| 52 |
+
"event_type_id": 19,
|
| 53 |
+
"publisher_module": "modulo_6",
|
| 54 |
+
"payload": "{\"evento\":\"CIERRE_INTERNACION\",\"idEventoExterno\":\"M6-CIERRE-INT-000123\",\"idInternacionExterna\":\"INT-000123\",\"idEpisodioExterno\":\"700\",\"idPacienteExterno\":\"10500\",\"fechaIngreso\":\"2026-06-20T14:30:00Z\",\"fechaAlta\":\"2026-06-25T10:00:00Z\",\"tipoAlta\":\"ALTA_MEDICA\",\"timestampEvento\":\"2026-06-25T10:05:00Z\"}"
|
| 55 |
+
}
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
Importante: el campo `payload` tiene que viajar como string JSON, no como objeto JSON directo.
|
| 59 |
+
|
| 60 |
+
Payload interno recomendado:
|
| 61 |
+
|
| 62 |
+
```json
|
| 63 |
+
{
|
| 64 |
+
"evento": "CIERRE_INTERNACION",
|
| 65 |
+
"idEventoExterno": "M6-CIERRE-INT-000123",
|
| 66 |
+
"idInternacionExterna": "INT-000123",
|
| 67 |
+
"idEpisodioExterno": "700",
|
| 68 |
+
"idPacienteExterno": "10500",
|
| 69 |
+
"fechaIngreso": "2026-06-20T14:30:00Z",
|
| 70 |
+
"fechaAlta": "2026-06-25T10:00:00Z",
|
| 71 |
+
"tipoAlta": "ALTA_MEDICA",
|
| 72 |
+
"timestampEvento": "2026-06-25T10:05:00Z"
|
| 73 |
+
}
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
Campos mínimos que necesitamos para poder continuar el flujo:
|
| 77 |
+
|
| 78 |
+
```txt
|
| 79 |
+
idPacienteExterno
|
| 80 |
+
idEpisodioExterno
|
| 81 |
+
idInternacionExterna
|
| 82 |
+
fechaIngreso
|
| 83 |
+
fechaAlta
|
| 84 |
+
tipoAlta
|
| 85 |
+
timestampEvento
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
Con `idPacienteExterno` e `idEpisodioExterno`, M7 consulta a M1 para obtener cobertura, episodio y actos médicos. Después M7 factura usando su propio ABM de obras sociales, planes, convenios y nomenclador.
|
| 89 |
+
|
| 90 |
+
No necesitamos que M6 nos mande obra social, plan, convenio, precios, copagos ni montos. Eso lo resuelve M7.
|
| 91 |
+
|
| 92 |
+
Como fallback/manual testing, también dejamos estos endpoints REST disponibles:
|
| 93 |
+
|
| 94 |
+
```http
|
| 95 |
+
POST https://modulo7-backend.onrender.com/api/v1/webhooks/internacion/cama-lista
|
| 96 |
+
POST https://modulo7-backend.onrender.com/api/integracion/internacion/cierre-episodio
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
Pero para la integración final usemos el evento de Core con `event_type_id: 19`.
|
| 100 |
+
|
| 101 |
+
Detalle importante: si el evento viene sin `timestampEvento` o `timestamp_evento`, M7 lo rechaza porque es obligatorio por contrato.
|
documentation/{M10_openapi.yaml → integrations/openapi_docs/M10_openapi.yaml}
RENAMED
|
File without changes
|
documentation/{M1_docs.html → integrations/openapi_docs/M1_docs.html}
RENAMED
|
File without changes
|
documentation/{M2_openapi.json → integrations/openapi_docs/M2_openapi.json}
RENAMED
|
File without changes
|
requirements.txt
CHANGED
|
@@ -9,3 +9,4 @@ python-jose[cryptography]==3.3.0
|
|
| 9 |
httpx==0.27.2
|
| 10 |
sqlalchemy==2.0.36
|
| 11 |
psycopg2-binary==2.9.10
|
|
|
|
|
|
| 9 |
httpx==0.27.2
|
| 10 |
sqlalchemy==2.0.36
|
| 11 |
psycopg2-binary==2.9.10
|
| 12 |
+
aio-pika==9.5.8
|
tests/factories.py
CHANGED
|
@@ -26,6 +26,10 @@ def make_cama(**overrides) -> SimpleNamespace:
|
|
| 26 |
"contraindicaciones_incompatibles": [],
|
| 27 |
"ultima_actualizacion": _NOW,
|
| 28 |
"ultimo_movimiento_tipo": None,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
}
|
| 30 |
data.update(overrides)
|
| 31 |
return SimpleNamespace(**data)
|
|
|
|
| 26 |
"contraindicaciones_incompatibles": [],
|
| 27 |
"ultima_actualizacion": _NOW,
|
| 28 |
"ultimo_movimiento_tipo": None,
|
| 29 |
+
"solicitud_hce_id": None,
|
| 30 |
+
"fecha_ingreso": None,
|
| 31 |
+
"alta_tipo": None,
|
| 32 |
+
"alta_timestamp": None,
|
| 33 |
}
|
| 34 |
data.update(overrides)
|
| 35 |
return SimpleNamespace(**data)
|
tests/test_config.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests de `app/config.py::Settings._blank_non_str_env_vars_fall_back_to_default`.
|
| 3 |
+
|
| 4 |
+
Contexto real: dos incidentes en producción (HF Spaces) donde una env var declarada
|
| 5 |
+
pero vacía tiró abajo el arranque entero de la app (`ValidationError` en `Settings()`,
|
| 6 |
+
antes de que `main.py` llegue a levantar cualquier endpoint) — primero con los
|
| 7 |
+
`*_event_type_id`, después con `RABBITMQ_PORT`/`RABBITMQ_CONSUMER_ENABLED`.
|
| 8 |
+
"""
|
| 9 |
+
from app.config import Settings
|
| 10 |
+
|
| 11 |
+
_REQUIRED = {"supabase_url": "https://x.supabase.co", "supabase_key": "x", "jwt_secret": "x"}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_int_vacio_cae_al_default():
|
| 15 |
+
s = Settings(**_REQUIRED, rabbitmq_port="")
|
| 16 |
+
assert s.rabbitmq_port == 5672
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_bool_vacio_cae_al_default():
|
| 20 |
+
s = Settings(**_REQUIRED, rabbitmq_consumer_enabled="")
|
| 21 |
+
assert s.rabbitmq_consumer_enabled is False
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_int_or_none_vacio_cae_a_none():
|
| 25 |
+
s = Settings(**_REQUIRED, facturacion_cama_lista_event_type_id="")
|
| 26 |
+
assert s.facturacion_cama_lista_event_type_id is None
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_str_vacio_se_conserva_tal_cual():
|
| 30 |
+
"""Para campos str, "" ya es la semántica normal de "no configurado" — no tocar."""
|
| 31 |
+
s = Settings(**_REQUIRED, core_service_email="")
|
| 32 |
+
assert s.core_service_email == ""
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_int_con_valor_real_no_se_toca():
|
| 36 |
+
s = Settings(**_REQUIRED, rabbitmq_port="6672")
|
| 37 |
+
assert s.rabbitmq_port == 6672
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_int_or_none_con_valor_real_no_se_toca():
|
| 41 |
+
s = Settings(**_REQUIRED, facturacion_cama_lista_event_type_id="19")
|
| 42 |
+
assert s.facturacion_cama_lista_event_type_id == 19
|
tests/test_core_events.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests de la publicación saliente al bus del Core (`app/integrations/core_events.py`) y
|
| 3 |
+
de que los 4 puntos de notificación (`hce.notify_resultado_solicitud`,
|
| 4 |
+
`monitoreo.notify_alta`/`notify_baja`, `facturacion.notify_cama_lista`) sigan haciendo el
|
| 5 |
+
mismo request REST que hoy, sin cambios observables, mientras el `event_type_id`
|
| 6 |
+
correspondiente esté en `None` (default actual — ver `M6_DISEÑO.md` §7).
|
| 7 |
+
"""
|
| 8 |
+
from datetime import datetime, timezone
|
| 9 |
+
|
| 10 |
+
from app.config import settings
|
| 11 |
+
from app.integrations import core_events, facturacion, hce, monitoreo
|
| 12 |
+
from tests.factories import make_cama
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# ─── publish_event: no-op mientras no haya event_type_id ──────────────────
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_publish_event_sin_id_no_hace_ningun_request(monkeypatch):
|
| 19 |
+
called = []
|
| 20 |
+
monkeypatch.setattr("app.integrations.core_events._post", lambda *a, **k: called.append((a, k)))
|
| 21 |
+
|
| 22 |
+
result = core_events.publish_event(None, {"foo": "bar"})
|
| 23 |
+
|
| 24 |
+
assert result is True
|
| 25 |
+
assert called == []
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_publish_event_con_id_publica_al_core(monkeypatch):
|
| 29 |
+
calls = []
|
| 30 |
+
|
| 31 |
+
def _fake_post(url, body):
|
| 32 |
+
calls.append((url, body))
|
| 33 |
+
return {"id": 999}
|
| 34 |
+
|
| 35 |
+
monkeypatch.setattr(core_events, "_post", _fake_post)
|
| 36 |
+
|
| 37 |
+
result = core_events.publish_event(14, {"foo": "bar"})
|
| 38 |
+
|
| 39 |
+
assert result is True
|
| 40 |
+
assert len(calls) == 1
|
| 41 |
+
url, body = calls[0]
|
| 42 |
+
assert url == f"{settings.m10_core_url}/events/log"
|
| 43 |
+
assert body["event_type_id"] == 14
|
| 44 |
+
assert body["publisher_module"] == "internacion"
|
| 45 |
+
assert body["payload"] == '{"foo": "bar"}'
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def test_publish_event_con_id_pero_post_falla_devuelve_false(monkeypatch):
|
| 49 |
+
monkeypatch.setattr(core_events, "_post", lambda *a, **k: None)
|
| 50 |
+
|
| 51 |
+
assert core_events.publish_event(14, {"foo": "bar"}) is False
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# ─── notify_* : REST sin cambios + publish_event adicional (hoy no-op) ─────
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_notify_resultado_solicitud_sigue_llamando_rest_igual_que_antes(monkeypatch):
|
| 58 |
+
monkeypatch.setattr(settings, "mock_external_services", False)
|
| 59 |
+
monkeypatch.setattr(settings, "hce_solicitud_resuelta_event_type_id", None)
|
| 60 |
+
rest_calls = []
|
| 61 |
+
publish_calls = []
|
| 62 |
+
monkeypatch.setattr(
|
| 63 |
+
"app.integrations.hce._post",
|
| 64 |
+
lambda url, payload: rest_calls.append((url, payload)) or {"ok": True},
|
| 65 |
+
)
|
| 66 |
+
monkeypatch.setattr(
|
| 67 |
+
"app.integrations.core_events.publish_event",
|
| 68 |
+
lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
ok = hce.notify_resultado_solicitud("HCE-SOL-1", "APROBADA", motivo=None)
|
| 72 |
+
|
| 73 |
+
assert ok is True
|
| 74 |
+
assert len(rest_calls) == 1
|
| 75 |
+
url, rest_payload = rest_calls[0]
|
| 76 |
+
assert url == f"{settings.m1_hce_url}/api/v1/hce/solicitudes/HCE-SOL-1/resultado"
|
| 77 |
+
assert "solicitud_hce_id" not in rest_payload # el body REST no cambia
|
| 78 |
+
assert len(publish_calls) == 1
|
| 79 |
+
event_type_id, event_payload = publish_calls[0]
|
| 80 |
+
assert event_type_id is None # no configurado todavía
|
| 81 |
+
assert event_payload["solicitud_hce_id"] == "HCE-SOL-1"
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_notify_alta_sigue_llamando_rest_igual_que_antes(monkeypatch):
|
| 85 |
+
monkeypatch.setattr(settings, "mock_external_services", False)
|
| 86 |
+
monkeypatch.setattr(settings, "monitoreo_alta_event_type_id", None)
|
| 87 |
+
rest_calls = []
|
| 88 |
+
publish_calls = []
|
| 89 |
+
monkeypatch.setattr(
|
| 90 |
+
"app.integrations.monitoreo._post",
|
| 91 |
+
lambda url, payload: rest_calls.append((url, payload)) or {"ok": True},
|
| 92 |
+
)
|
| 93 |
+
monkeypatch.setattr(
|
| 94 |
+
"app.integrations.core_events.publish_event",
|
| 95 |
+
lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
ok = monitoreo.notify_alta(7)
|
| 99 |
+
|
| 100 |
+
assert ok is True
|
| 101 |
+
assert len(rest_calls) == 1
|
| 102 |
+
assert len(publish_calls) == 1
|
| 103 |
+
assert publish_calls[0][0] is None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def test_notify_baja_sigue_llamando_rest_igual_que_antes(monkeypatch):
|
| 107 |
+
monkeypatch.setattr(settings, "mock_external_services", False)
|
| 108 |
+
monkeypatch.setattr(settings, "monitoreo_baja_event_type_id", None)
|
| 109 |
+
rest_calls = []
|
| 110 |
+
publish_calls = []
|
| 111 |
+
monkeypatch.setattr(
|
| 112 |
+
"app.integrations.monitoreo._post",
|
| 113 |
+
lambda url, payload: rest_calls.append((url, payload)) or {"ok": True},
|
| 114 |
+
)
|
| 115 |
+
monkeypatch.setattr(
|
| 116 |
+
"app.integrations.core_events.publish_event",
|
| 117 |
+
lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
ok = monitoreo.notify_baja(7)
|
| 121 |
+
|
| 122 |
+
assert ok is True
|
| 123 |
+
assert len(rest_calls) == 1
|
| 124 |
+
assert len(publish_calls) == 1
|
| 125 |
+
assert publish_calls[0][0] is 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)
|
| 131 |
+
monkeypatch.setattr(settings, "facturacion_cama_lista_event_type_id", None)
|
| 132 |
+
rest_calls = []
|
| 133 |
+
monkeypatch.setattr(
|
| 134 |
+
"app.integrations.facturacion._post",
|
| 135 |
+
lambda url, payload: rest_calls.append((url, payload)) or {"ok": True},
|
| 136 |
+
)
|
| 137 |
+
monkeypatch.setattr("app.integrations.core_events.publish_event", lambda *a, **k: True)
|
| 138 |
+
|
| 139 |
+
cama = make_cama(id=315, paciente_id=7)
|
| 140 |
+
ok = facturacion.notify_cama_lista(cama, db=None)
|
| 141 |
+
|
| 142 |
+
assert ok is True
|
| 143 |
+
assert len(rest_calls) == 1
|
| 144 |
+
url, payload = rest_calls[0]
|
| 145 |
+
assert url == f"{settings.m7_facturacion_url}/api/v1/webhooks/internacion/cama-lista"
|
| 146 |
+
assert payload == {
|
| 147 |
+
"evento": "CAMA_LISTA",
|
| 148 |
+
"idEventoExterno": payload["idEventoExterno"],
|
| 149 |
+
"camaId": "315",
|
| 150 |
+
"idPacienteExterno": 7,
|
| 151 |
+
"timestampEvento": payload["timestampEvento"],
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def test_notify_cama_lista_publica_evento_rico_con_datos_del_episodio(monkeypatch):
|
| 156 |
+
"""El evento del Core (event_type_id=19, confirmado por M7) lleva el payload rico
|
| 157 |
+
CIERRE_INTERNACION con los datos del episodio persistidos en la Cama."""
|
| 158 |
+
monkeypatch.setattr(settings, "mock_external_services", False)
|
| 159 |
+
monkeypatch.setattr(settings, "facturacion_cama_lista_event_type_id", 19)
|
| 160 |
+
monkeypatch.setattr("app.integrations.facturacion._post", lambda *a, **k: {"ok": True})
|
| 161 |
+
publish_calls = []
|
| 162 |
+
monkeypatch.setattr(
|
| 163 |
+
"app.integrations.core_events.publish_event",
|
| 164 |
+
lambda event_type_id, payload, publisher_module="internacion": publish_calls.append(
|
| 165 |
+
(event_type_id, payload, publisher_module)
|
| 166 |
+
)
|
| 167 |
+
or True,
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
cama = make_cama(
|
| 171 |
+
id=315,
|
| 172 |
+
paciente_id=7,
|
| 173 |
+
solicitud_hce_id="HCE-SOL-00123",
|
| 174 |
+
fecha_ingreso=datetime(2026, 6, 20, 14, 30, tzinfo=timezone.utc),
|
| 175 |
+
alta_tipo="ALTA_MEDICA",
|
| 176 |
+
alta_timestamp=datetime(2026, 6, 25, 10, 0, tzinfo=timezone.utc),
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
facturacion.notify_cama_lista(cama, db=None)
|
| 180 |
+
|
| 181 |
+
assert len(publish_calls) == 1
|
| 182 |
+
event_type_id, payload, publisher_module = publish_calls[0]
|
| 183 |
+
assert event_type_id == 19
|
| 184 |
+
assert publisher_module == "modulo_6"
|
| 185 |
+
assert payload["evento"] == "CIERRE_INTERNACION"
|
| 186 |
+
assert payload["camaId"] == "315"
|
| 187 |
+
assert payload["idInternacionExterna"] == "HCE-SOL-00123"
|
| 188 |
+
assert payload["idEpisodioExterno"] is None # bloqueante externo — M1 no lo provee aún
|
| 189 |
+
assert payload["idPacienteExterno"] == 7
|
| 190 |
+
assert payload["fechaIngreso"] == "2026-06-20T14:30:00+00:00"
|
| 191 |
+
assert payload["fechaAlta"] == "2026-06-25T10:00:00+00:00"
|
| 192 |
+
assert payload["tipoAlta"] == "ALTA_MEDICA"
|
| 193 |
+
assert "timestampEvento" in payload and payload["timestampEvento"] # siempre presente
|
| 194 |
+
assert isinstance(payload["camasUtilizadas"], list) and len(payload["camasUtilizadas"]) >= 1
|
tests/test_internal.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests de `POST /api/v1/internal/reservas/tick`: no usa `get_current_user` (no hay usuario
|
| 3 |
+
humano detrás de un cron externo) — se protege con `X-Internal-Token` comparado contra
|
| 4 |
+
`settings.internal_tick_secret`.
|
| 5 |
+
"""
|
| 6 |
+
from fastapi.testclient import TestClient
|
| 7 |
+
|
| 8 |
+
from app.config import settings
|
| 9 |
+
|
| 10 |
+
TICK_URL = "/api/v1/internal/reservas/tick"
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_tick_sin_header_401(client: TestClient, monkeypatch):
|
| 14 |
+
monkeypatch.setattr(settings, "internal_tick_secret", "el-secreto-correcto")
|
| 15 |
+
resp = client.post(TICK_URL)
|
| 16 |
+
assert resp.status_code == 422 # Header(...) obligatorio, FastAPI valida antes
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_tick_token_incorrecto_401(client: TestClient, monkeypatch):
|
| 20 |
+
monkeypatch.setattr(settings, "internal_tick_secret", "el-secreto-correcto")
|
| 21 |
+
resp = client.post(TICK_URL, headers={"X-Internal-Token": "otro-valor"})
|
| 22 |
+
assert resp.status_code == 401
|
| 23 |
+
assert resp.json()["detail"]["codigo"] == "NO_AUTENTICADO"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_tick_secreto_no_configurado_401(client: TestClient, monkeypatch):
|
| 27 |
+
"""internal_tick_secret="" (default) rechaza todo — falla cerrado, no abierto."""
|
| 28 |
+
monkeypatch.setattr(settings, "internal_tick_secret", "")
|
| 29 |
+
resp = client.post(TICK_URL, headers={"X-Internal-Token": "cualquiera"})
|
| 30 |
+
assert resp.status_code == 401
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_tick_ok(client: TestClient, monkeypatch):
|
| 34 |
+
monkeypatch.setattr(settings, "internal_tick_secret", "el-secreto-correcto")
|
| 35 |
+
monkeypatch.setattr(
|
| 36 |
+
"app.services.cama_service.procesar_transiciones_automaticas",
|
| 37 |
+
lambda db: {"iniciadas": 2, "completadas": 1},
|
| 38 |
+
)
|
| 39 |
+
resp = client.post(TICK_URL, headers={"X-Internal-Token": "el-secreto-correcto"})
|
| 40 |
+
assert resp.status_code == 200
|
| 41 |
+
assert resp.json() == {"iniciadas": 2, "completadas": 1}
|
tests/test_rabbit_consumer.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests del consumer de `internacion.requests` (`app/integrations/rabbit_consumer.py`).
|
| 3 |
+
|
| 4 |
+
No abren conexión real a RabbitMQ: `dispatch()` se prueba monkeypatcheando las
|
| 5 |
+
funciones de servicio (misma lógica de negocio que ya cubre `tests/test_webhooks.py`
|
| 6 |
+
para la vía REST); `_on_message` se prueba con un mensaje fake (sin `aio_pika` real),
|
| 7 |
+
corriendo la coroutine con `asyncio.run` — no hace falta pytest-asyncio para esto.
|
| 8 |
+
"""
|
| 9 |
+
import asyncio
|
| 10 |
+
import json
|
| 11 |
+
from datetime import datetime, timezone
|
| 12 |
+
|
| 13 |
+
import pytest
|
| 14 |
+
|
| 15 |
+
from app.integrations import rabbit_consumer
|
| 16 |
+
from app.services import solicitud_service
|
| 17 |
+
|
| 18 |
+
_NOW_ISO = datetime.now(timezone.utc).isoformat()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class _FakeMessage:
|
| 22 |
+
def __init__(self, body: bytes):
|
| 23 |
+
self.body = body
|
| 24 |
+
self.acked = False
|
| 25 |
+
self.rejected_requeue = None
|
| 26 |
+
|
| 27 |
+
async def ack(self):
|
| 28 |
+
self.acked = True
|
| 29 |
+
|
| 30 |
+
async def reject(self, requeue=False):
|
| 31 |
+
self.rejected_requeue = requeue
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _envelope(event_type_name: str, payload: dict, log_id: int = 1) -> bytes:
|
| 35 |
+
return json.dumps(
|
| 36 |
+
{
|
| 37 |
+
"event_type_id": 1,
|
| 38 |
+
"event_type_name": event_type_name,
|
| 39 |
+
"source_module": "test",
|
| 40 |
+
"publisher_module": "test",
|
| 41 |
+
"log_id": log_id,
|
| 42 |
+
"payload": json.dumps(payload),
|
| 43 |
+
"published_at": _NOW_ISO,
|
| 44 |
+
}
|
| 45 |
+
).encode()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# ─── dispatch(): despacho por event_type_name ──────────────────────────────
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_dispatch_solicitud_creada(monkeypatch):
|
| 52 |
+
calls = []
|
| 53 |
+
monkeypatch.setattr(rabbit_consumer, "get_db", lambda: "FAKE_DB")
|
| 54 |
+
monkeypatch.setattr(
|
| 55 |
+
solicitud_service, "recibir_solicitud", lambda db, data: calls.append((db, data))
|
| 56 |
+
)
|
| 57 |
+
payload = {
|
| 58 |
+
"tipo": "INTERNACION",
|
| 59 |
+
"solicitud_hce_id": "HCE-SOL-1",
|
| 60 |
+
"paciente_id": 7,
|
| 61 |
+
"medico_solicitante_id": 10,
|
| 62 |
+
"timestamp": _NOW_ISO,
|
| 63 |
+
}
|
| 64 |
+
rabbit_consumer.dispatch("internacion.solicitud.creada", payload)
|
| 65 |
+
assert len(calls) == 1
|
| 66 |
+
db, data = calls[0]
|
| 67 |
+
assert db == "FAKE_DB"
|
| 68 |
+
assert data.solicitud_hce_id == "HCE-SOL-1"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_dispatch_alta_medica(monkeypatch):
|
| 72 |
+
calls = []
|
| 73 |
+
monkeypatch.setattr(rabbit_consumer, "get_db", lambda: "FAKE_DB")
|
| 74 |
+
monkeypatch.setattr(
|
| 75 |
+
solicitud_service, "procesar_alta_medica", lambda db, data: calls.append(data.paciente_id)
|
| 76 |
+
)
|
| 77 |
+
payload = {
|
| 78 |
+
"paciente_id": 7,
|
| 79 |
+
"medico_firmante_id": 10,
|
| 80 |
+
"tipo_alta": "ALTA_MEDICA",
|
| 81 |
+
"timestamp": _NOW_ISO,
|
| 82 |
+
}
|
| 83 |
+
rabbit_consumer.dispatch("internacion.alta-medica.registrada", payload)
|
| 84 |
+
assert calls == [7]
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_dispatch_alerta_emergencia(monkeypatch):
|
| 88 |
+
calls = []
|
| 89 |
+
monkeypatch.setattr(rabbit_consumer, "get_db", lambda: "FAKE_DB")
|
| 90 |
+
monkeypatch.setattr(
|
| 91 |
+
solicitud_service, "procesar_alerta_emergencia", lambda db, paciente_id: calls.append(paciente_id)
|
| 92 |
+
)
|
| 93 |
+
payload = {"paciente_id": 7, "timestamp": _NOW_ISO}
|
| 94 |
+
rabbit_consumer.dispatch("internacion.alerta-emergencia.detectada", payload)
|
| 95 |
+
assert calls == [7]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_dispatch_alerta_resuelta(monkeypatch):
|
| 99 |
+
calls = []
|
| 100 |
+
monkeypatch.setattr(rabbit_consumer, "get_db", lambda: "FAKE_DB")
|
| 101 |
+
monkeypatch.setattr(
|
| 102 |
+
solicitud_service, "procesar_alerta_resuelta", lambda db, paciente_id: calls.append(paciente_id)
|
| 103 |
+
)
|
| 104 |
+
payload = {"paciente_id": 7, "timestamp": _NOW_ISO}
|
| 105 |
+
rabbit_consumer.dispatch("internacion.alerta-resuelta.notificada", payload)
|
| 106 |
+
assert calls == [7]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def test_dispatch_turno_cancelado(monkeypatch):
|
| 110 |
+
calls = []
|
| 111 |
+
monkeypatch.setattr(rabbit_consumer, "get_db", lambda: "FAKE_DB")
|
| 112 |
+
monkeypatch.setattr(
|
| 113 |
+
solicitud_service,
|
| 114 |
+
"cancelar_reserva_por_turno",
|
| 115 |
+
lambda db, turno_id, motivo: calls.append((turno_id, motivo)),
|
| 116 |
+
)
|
| 117 |
+
# turno_id viaja en el payload del evento (en el REST equivalente viene del path).
|
| 118 |
+
payload = {"turno_id": 5501, "motivo": "paciente cancela", "timestamp": _NOW_ISO}
|
| 119 |
+
rabbit_consumer.dispatch("internacion.turno.cancelado", payload)
|
| 120 |
+
assert calls == [(5501, "paciente cancela")]
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def test_dispatch_event_type_name_no_reconocido():
|
| 124 |
+
with pytest.raises(KeyError):
|
| 125 |
+
rabbit_consumer.dispatch("algo.que.no.existe", {})
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# ─── _on_message(): ack/reject según el resultado del dispatch ────────────
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def test_on_message_ack_tras_procesar_ok(monkeypatch):
|
| 132 |
+
calls = []
|
| 133 |
+
monkeypatch.setattr(rabbit_consumer, "dispatch", lambda name, payload: calls.append((name, payload)))
|
| 134 |
+
msg = _FakeMessage(_envelope("internacion.alta-medica.registrada", {"paciente_id": 7}))
|
| 135 |
+
|
| 136 |
+
asyncio.run(rabbit_consumer._on_message(msg))
|
| 137 |
+
|
| 138 |
+
assert msg.acked
|
| 139 |
+
assert msg.rejected_requeue is None
|
| 140 |
+
assert calls == [("internacion.alta-medica.registrada", {"paciente_id": 7})]
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_on_message_json_malformado_reject_sin_requeue():
|
| 144 |
+
msg = _FakeMessage(b"esto no es json")
|
| 145 |
+
|
| 146 |
+
asyncio.run(rabbit_consumer._on_message(msg))
|
| 147 |
+
|
| 148 |
+
assert not msg.acked
|
| 149 |
+
assert msg.rejected_requeue is False
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def test_on_message_envelope_sin_event_type_name_reject():
|
| 153 |
+
msg = _FakeMessage(json.dumps({"payload": "{}"}).encode())
|
| 154 |
+
|
| 155 |
+
asyncio.run(rabbit_consumer._on_message(msg))
|
| 156 |
+
|
| 157 |
+
assert not msg.acked
|
| 158 |
+
assert msg.rejected_requeue is False
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def test_on_message_dispatch_lanza_excepcion_reject_sin_crashear(monkeypatch):
|
| 162 |
+
def _raise(name, payload):
|
| 163 |
+
raise RuntimeError("fallo de negocio")
|
| 164 |
+
|
| 165 |
+
monkeypatch.setattr(rabbit_consumer, "dispatch", _raise)
|
| 166 |
+
msg = _FakeMessage(_envelope("internacion.alta-medica.registrada", {"paciente_id": 7}))
|
| 167 |
+
|
| 168 |
+
asyncio.run(rabbit_consumer._on_message(msg)) # no debe propagar la excepción
|
| 169 |
+
|
| 170 |
+
assert not msg.acked
|
| 171 |
+
assert msg.rejected_requeue is False
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def test_on_message_event_type_name_no_mapeado_reject(monkeypatch):
|
| 175 |
+
msg = _FakeMessage(_envelope("algo.no.mapeado", {}))
|
| 176 |
+
|
| 177 |
+
asyncio.run(rabbit_consumer._on_message(msg))
|
| 178 |
+
|
| 179 |
+
assert not msg.acked
|
| 180 |
+
assert msg.rejected_requeue is False
|
tests/test_reserva_scheduler.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests de `cama_service.procesar_transiciones_automaticas`: avance automático de
|
| 3 |
+
RESERVADA→EN_CURSO→COMPLETADA según horario, reusando `update_reserva_estado` (mismos
|
| 4 |
+
side-effects que la transición manual vía PATCH).
|
| 5 |
+
"""
|
| 6 |
+
from unittest.mock import MagicMock
|
| 7 |
+
|
| 8 |
+
from tests.factories import make_quirofano, make_reserva
|
| 9 |
+
from app.services import cama_service
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_reserva_vencida_pasa_a_en_curso(monkeypatch):
|
| 13 |
+
quirofano = make_quirofano(estado="DISPONIBLE")
|
| 14 |
+
reserva = make_reserva(estado="RESERVADA", cama_id=501, paciente_id=7)
|
| 15 |
+
|
| 16 |
+
monkeypatch.setattr("app.crud.reserva.get_pendientes_de_inicio", lambda db, ahora: [reserva])
|
| 17 |
+
monkeypatch.setattr("app.crud.reserva.get_pendientes_de_fin", lambda db, ahora: [])
|
| 18 |
+
monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: quirofano)
|
| 19 |
+
# update_reserva_estado vuelve a buscar la reserva por (cama_id, reserva_id) — no
|
| 20 |
+
# recibe la instancia de get_pendientes_de_inicio directamente.
|
| 21 |
+
monkeypatch.setattr("app.crud.reserva.get_by_cama_and_id", lambda db, cid, rid: reserva)
|
| 22 |
+
monkeypatch.setattr("app.crud.reserva.save", lambda db, r: r)
|
| 23 |
+
monkeypatch.setattr("app.crud.cama.save", lambda db, c: c)
|
| 24 |
+
|
| 25 |
+
result = cama_service.procesar_transiciones_automaticas(MagicMock())
|
| 26 |
+
|
| 27 |
+
assert result == {"iniciadas": 1, "completadas": 0}
|
| 28 |
+
assert reserva.estado == "EN_CURSO"
|
| 29 |
+
assert quirofano.estado == "OCUPADA"
|
| 30 |
+
assert quirofano.paciente_id == 7
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_reserva_en_curso_vencida_pasa_a_completada(monkeypatch):
|
| 34 |
+
quirofano = make_quirofano(estado="OCUPADA", paciente_id=7)
|
| 35 |
+
reserva = make_reserva(estado="EN_CURSO", cama_id=501, paciente_id=7)
|
| 36 |
+
|
| 37 |
+
monkeypatch.setattr("app.crud.reserva.get_pendientes_de_inicio", lambda db, ahora: [])
|
| 38 |
+
monkeypatch.setattr("app.crud.reserva.get_pendientes_de_fin", lambda db, ahora: [reserva])
|
| 39 |
+
monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: quirofano)
|
| 40 |
+
monkeypatch.setattr("app.crud.reserva.get_by_cama_and_id", lambda db, cid, rid: reserva)
|
| 41 |
+
monkeypatch.setattr("app.crud.reserva.save", lambda db, r: r)
|
| 42 |
+
monkeypatch.setattr("app.crud.cama.save", lambda db, c: c)
|
| 43 |
+
|
| 44 |
+
result = cama_service.procesar_transiciones_automaticas(MagicMock())
|
| 45 |
+
|
| 46 |
+
assert result == {"iniciadas": 0, "completadas": 1}
|
| 47 |
+
assert reserva.estado == "COMPLETADA"
|
| 48 |
+
assert quirofano.estado == "EN_LIMPIEZA"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_reserva_cancelada_no_es_candidata(monkeypatch):
|
| 52 |
+
"""El filtro de origen ya excluye CANCELADA — no hace falta lógica extra acá; este
|
| 53 |
+
test blinda que get_pendientes_de_inicio nunca devuelva una CANCELADA."""
|
| 54 |
+
monkeypatch.setattr("app.crud.reserva.get_pendientes_de_inicio", lambda db, ahora: [])
|
| 55 |
+
monkeypatch.setattr("app.crud.reserva.get_pendientes_de_fin", lambda db, ahora: [])
|
| 56 |
+
|
| 57 |
+
result = cama_service.procesar_transiciones_automaticas(MagicMock())
|
| 58 |
+
|
| 59 |
+
assert result == {"iniciadas": 0, "completadas": 0}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_varias_reservas_se_procesan_en_el_mismo_tick(monkeypatch):
|
| 63 |
+
quirofano_a = make_quirofano(id=501, estado="DISPONIBLE")
|
| 64 |
+
quirofano_b = make_quirofano(id=502, estado="OCUPADA", paciente_id=8)
|
| 65 |
+
reserva_a = make_reserva(id=1, cama_id=501, estado="RESERVADA", paciente_id=7)
|
| 66 |
+
reserva_b = make_reserva(id=2, cama_id=502, estado="EN_CURSO", paciente_id=8)
|
| 67 |
+
|
| 68 |
+
monkeypatch.setattr("app.crud.reserva.get_pendientes_de_inicio", lambda db, ahora: [reserva_a])
|
| 69 |
+
monkeypatch.setattr("app.crud.reserva.get_pendientes_de_fin", lambda db, ahora: [reserva_b])
|
| 70 |
+
monkeypatch.setattr(
|
| 71 |
+
"app.crud.cama.get_by_id",
|
| 72 |
+
lambda db, cid: quirofano_a if cid == 501 else quirofano_b,
|
| 73 |
+
)
|
| 74 |
+
monkeypatch.setattr(
|
| 75 |
+
"app.crud.reserva.get_by_cama_and_id",
|
| 76 |
+
lambda db, cid, rid: reserva_a if rid == 1 else reserva_b,
|
| 77 |
+
)
|
| 78 |
+
monkeypatch.setattr("app.crud.reserva.save", lambda db, r: r)
|
| 79 |
+
monkeypatch.setattr("app.crud.cama.save", lambda db, c: c)
|
| 80 |
+
|
| 81 |
+
result = cama_service.procesar_transiciones_automaticas(MagicMock())
|
| 82 |
+
|
| 83 |
+
assert result == {"iniciadas": 1, "completadas": 1}
|
| 84 |
+
assert reserva_a.estado == "EN_CURSO"
|
| 85 |
+
assert reserva_b.estado == "COMPLETADA"
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def test_registra_auditoria_con_rol_sistema(monkeypatch):
|
| 89 |
+
quirofano = make_quirofano(estado="DISPONIBLE")
|
| 90 |
+
reserva = make_reserva(estado="RESERVADA", cama_id=501, paciente_id=7)
|
| 91 |
+
auditoria_calls = []
|
| 92 |
+
|
| 93 |
+
monkeypatch.setattr("app.crud.reserva.get_pendientes_de_inicio", lambda db, ahora: [reserva])
|
| 94 |
+
monkeypatch.setattr("app.crud.reserva.get_pendientes_de_fin", lambda db, ahora: [])
|
| 95 |
+
monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: quirofano)
|
| 96 |
+
monkeypatch.setattr("app.crud.reserva.get_by_cama_and_id", lambda db, cid, rid: reserva)
|
| 97 |
+
monkeypatch.setattr("app.crud.reserva.save", lambda db, r: r)
|
| 98 |
+
monkeypatch.setattr("app.crud.cama.save", lambda db, c: c)
|
| 99 |
+
monkeypatch.setattr(
|
| 100 |
+
"app.crud.auditoria.registrar",
|
| 101 |
+
lambda db, **kwargs: auditoria_calls.append(kwargs),
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
cama_service.procesar_transiciones_automaticas(MagicMock())
|
| 105 |
+
|
| 106 |
+
assert auditoria_calls # al menos la de RESERVA_QUIROFANO (y la de CAMA, si cambió)
|
| 107 |
+
for call in auditoria_calls:
|
| 108 |
+
assert call["actor"] is None # rol SISTEMA por default en auditoria_crud.registrar
|
tests/test_solicitudes.py
CHANGED
|
@@ -6,8 +6,11 @@ disparan llamadas a módulos externos (Core/HCE/Monitoreo); esos se cubren con
|
|
| 6 |
tests dedicados que mockean la capa de integraciones.
|
| 7 |
"""
|
| 8 |
from datetime import datetime, timezone
|
|
|
|
|
|
|
| 9 |
from fastapi.testclient import TestClient
|
| 10 |
|
|
|
|
| 11 |
from tests.factories import make_cama, make_solicitud
|
| 12 |
|
| 13 |
PREFIX = "/api/v1/solicitudes"
|
|
@@ -106,6 +109,64 @@ def test_resolver_solicitud_aprobar_ok(client: TestClient, admin_headers, monkey
|
|
| 106 |
assert data["accion"] == "APROBAR"
|
| 107 |
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
def test_resolver_solicitud_rechazar_ok(client: TestClient, admin_headers, monkeypatch):
|
| 110 |
sol = make_solicitud()
|
| 111 |
monkeypatch.setattr("app.crud.solicitud.get_by_id", lambda db, num: sol)
|
|
|
|
| 6 |
tests dedicados que mockean la capa de integraciones.
|
| 7 |
"""
|
| 8 |
from datetime import datetime, timezone
|
| 9 |
+
from unittest.mock import MagicMock
|
| 10 |
+
|
| 11 |
from fastapi.testclient import TestClient
|
| 12 |
|
| 13 |
+
from app.services import solicitud_service
|
| 14 |
from tests.factories import make_cama, make_solicitud
|
| 15 |
|
| 16 |
PREFIX = "/api/v1/solicitudes"
|
|
|
|
| 109 |
assert data["accion"] == "APROBAR"
|
| 110 |
|
| 111 |
|
| 112 |
+
def test_resolver_solicitud_aprobar_setea_episodio_en_la_cama(client: TestClient, admin_headers, monkeypatch):
|
| 113 |
+
"""
|
| 114 |
+
Datos necesarios para el payload rico que M7 pide en notify_cama_lista
|
| 115 |
+
(idInternacionExterna, fechaIngreso) — se persisten en la propia Cama al aprobar,
|
| 116 |
+
porque se necesitan recién más adelante, al completar la limpieza.
|
| 117 |
+
"""
|
| 118 |
+
sol = make_solicitud(solicitud_hce_id="HCE-SOL-001")
|
| 119 |
+
saved_camas = []
|
| 120 |
+
monkeypatch.setattr("app.crud.solicitud.get_by_id", lambda db, num: sol)
|
| 121 |
+
monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_cama(estado="DISPONIBLE"))
|
| 122 |
+
monkeypatch.setattr(
|
| 123 |
+
"app.crud.cama.save", lambda db, c: saved_camas.append(c) or c
|
| 124 |
+
)
|
| 125 |
+
monkeypatch.setattr("app.crud.solicitud.save", lambda db, s: s)
|
| 126 |
+
monkeypatch.setattr("app.integrations.core.validate_patient", lambda pid: {"id": pid})
|
| 127 |
+
monkeypatch.setattr("app.integrations.hce.get_contraindicaciones", lambda pid: [])
|
| 128 |
+
monkeypatch.setattr("app.integrations.hce.notify_movimiento", lambda *a, **k: None)
|
| 129 |
+
monkeypatch.setattr("app.integrations.hce.notify_resultado_solicitud", lambda *a, **k: None)
|
| 130 |
+
monkeypatch.setattr("app.integrations.monitoreo.notify_alta", lambda *a, **k: None)
|
| 131 |
+
|
| 132 |
+
resp = client.patch(f"{PREFIX}/SOL-00001", json={"accion": "APROBAR"}, headers=admin_headers)
|
| 133 |
+
|
| 134 |
+
assert resp.status_code == 200
|
| 135 |
+
assert saved_camas[0].solicitud_hce_id == "HCE-SOL-001"
|
| 136 |
+
assert saved_camas[0].fecha_ingreso is not None
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def test_aprobar_traslado_hereda_episodio_de_la_cama_origen(monkeypatch):
|
| 140 |
+
"""
|
| 141 |
+
El episodio (idInternacionExterna/fechaIngreso para M7) es continuo a través de un
|
| 142 |
+
traslado: se hereda de la cama origen, no de la solicitud de traslado — si no, se
|
| 143 |
+
perdería el dato real de cuándo empezó la internación original.
|
| 144 |
+
"""
|
| 145 |
+
fecha_ingreso_original = datetime(2026, 6, 20, 14, 30, tzinfo=timezone.utc)
|
| 146 |
+
cama_origen = make_cama(id=101, estado="OCUPADA", solicitud_hce_id="HCE-SOL-ORIGINAL", fecha_ingreso=fecha_ingreso_original)
|
| 147 |
+
cama_destino = make_cama(id=202, estado="DISPONIBLE")
|
| 148 |
+
sol = make_solicitud(
|
| 149 |
+
tipo="TRASLADO", solicitud_hce_id="HCE-SOL-TRASLADO", cama_origen_id=101, cama_destino_solicitada_id=202,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
def _get_cama(db, cid):
|
| 153 |
+
return cama_origen if cid == 101 else cama_destino
|
| 154 |
+
|
| 155 |
+
monkeypatch.setattr("app.crud.cama.get_by_id", _get_cama)
|
| 156 |
+
monkeypatch.setattr("app.crud.cama.save", lambda db, c: c)
|
| 157 |
+
monkeypatch.setattr("app.integrations.hce.get_contraindicaciones", lambda pid: [])
|
| 158 |
+
monkeypatch.setattr("app.integrations.hce.notify_movimiento", lambda *a, **k: None)
|
| 159 |
+
monkeypatch.setattr("app.integrations.hce.notify_resultado_solicitud", lambda *a, **k: None)
|
| 160 |
+
monkeypatch.setattr("app.integrations.monitoreo.notify_alta", lambda *a, **k: None)
|
| 161 |
+
monkeypatch.setattr("app.integrations.monitoreo.notify_baja", lambda *a, **k: None)
|
| 162 |
+
|
| 163 |
+
solicitud_service._aprobar_traslado(MagicMock(), sol, None, None, resuelto_por=1, accion="APROBAR")
|
| 164 |
+
|
| 165 |
+
# El destino hereda el episodio del origen — no el solicitud_hce_id de ESTE traslado.
|
| 166 |
+
assert cama_destino.solicitud_hce_id == "HCE-SOL-ORIGINAL"
|
| 167 |
+
assert cama_destino.fecha_ingreso == fecha_ingreso_original
|
| 168 |
+
|
| 169 |
+
|
| 170 |
def test_resolver_solicitud_rechazar_ok(client: TestClient, admin_headers, monkeypatch):
|
| 171 |
sol = make_solicitud()
|
| 172 |
monkeypatch.setattr("app.crud.solicitud.get_by_id", lambda db, num: sol)
|
tests/test_webhooks.py
CHANGED
|
@@ -34,6 +34,51 @@ def test_alta_medica_ok(client: TestClient, admin_headers, monkeypatch):
|
|
| 34 |
assert "cama_id" in data
|
| 35 |
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
def test_alta_medica_404(client: TestClient, admin_headers, monkeypatch):
|
| 38 |
monkeypatch.setattr("app.crud.cama.get_by_paciente", lambda db, pid, estados: None)
|
| 39 |
payload = {
|
|
|
|
| 34 |
assert "cama_id" in data
|
| 35 |
|
| 36 |
|
| 37 |
+
def test_alta_medica_ok_aunque_monitoreo_falle(client: TestClient, admin_headers, monkeypatch):
|
| 38 |
+
"""
|
| 39 |
+
notify_baja (M9) es fire-and-forget (M6_DISEÑO.md §2): que M9 esté caído no debe
|
| 40 |
+
revertir el alta. Antes de la limpieza de código zombie, esto bloqueaba con 502.
|
| 41 |
+
"""
|
| 42 |
+
cama = make_cama(estado="OCUPADA", paciente_id=7)
|
| 43 |
+
monkeypatch.setattr("app.crud.cama.get_by_paciente", lambda db, pid, estados: cama)
|
| 44 |
+
monkeypatch.setattr("app.crud.cama.save", lambda db, c: c)
|
| 45 |
+
monkeypatch.setattr("app.integrations.monitoreo.notify_baja", lambda *a, **k: False)
|
| 46 |
+
payload = {
|
| 47 |
+
"paciente_id": 7,
|
| 48 |
+
"medico_firmante_id": 10,
|
| 49 |
+
"tipo_alta": "ALTA_MEDICA",
|
| 50 |
+
"timestamp": _NOW_ISO,
|
| 51 |
+
}
|
| 52 |
+
resp = client.post(f"{WEBHOOKS_PREFIX}/hce/alta-medica", json=payload, headers=admin_headers)
|
| 53 |
+
assert resp.status_code == 200
|
| 54 |
+
assert resp.json()["estado_cama"] == "EN_LIMPIEZA"
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_alta_medica_notifica_a_facturacion(client: TestClient, admin_headers, monkeypatch):
|
| 58 |
+
"""
|
| 59 |
+
El alta médica dispara notify_cama_lista (fire-and-forget) para cerrar la internación
|
| 60 |
+
del lado de M7. El alta no debe fallar aunque M7 esté caído.
|
| 61 |
+
"""
|
| 62 |
+
cama = make_cama(estado="OCUPADA", paciente_id=7)
|
| 63 |
+
monkeypatch.setattr("app.crud.cama.get_by_paciente", lambda db, pid, estados: cama)
|
| 64 |
+
monkeypatch.setattr("app.crud.cama.save", lambda db, c: c)
|
| 65 |
+
monkeypatch.setattr("app.integrations.monitoreo.notify_baja", lambda *a, **k: True)
|
| 66 |
+
facturacion_calls = []
|
| 67 |
+
monkeypatch.setattr(
|
| 68 |
+
"app.integrations.facturacion.notify_cama_lista",
|
| 69 |
+
lambda c, db: facturacion_calls.append(c) or True,
|
| 70 |
+
)
|
| 71 |
+
payload = {
|
| 72 |
+
"paciente_id": 7,
|
| 73 |
+
"medico_firmante_id": 10,
|
| 74 |
+
"tipo_alta": "ALTA_MEDICA",
|
| 75 |
+
"timestamp": _NOW_ISO,
|
| 76 |
+
}
|
| 77 |
+
resp = client.post(f"{WEBHOOKS_PREFIX}/hce/alta-medica", json=payload, headers=admin_headers)
|
| 78 |
+
assert resp.status_code == 200
|
| 79 |
+
assert len(facturacion_calls) == 1
|
| 80 |
+
|
| 81 |
+
|
| 82 |
def test_alta_medica_404(client: TestClient, admin_headers, monkeypatch):
|
| 83 |
monkeypatch.setattr("app.crud.cama.get_by_paciente", lambda db, pid, estados: None)
|
| 84 |
payload = {
|