Get paciente
Browse files- app/integrations/hce.py +25 -0
- app/routers/pacientes.py +22 -1
- app/schemas/paciente.py +16 -0
- documentation/M6_DISEΓO.md +15 -6
- documentation/roles.md +1 -0
- scripts/seed_datos_reales.py +258 -0
- tests/test_pacientes.py +29 -2
app/integrations/hce.py
CHANGED
|
@@ -20,6 +20,31 @@ def get_contraindicaciones(paciente_id: int) -> list[str]:
|
|
| 20 |
return [d.get("descripcion", "") for d in data.get("detalle", [])]
|
| 21 |
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
def get_ficha_medica(paciente_id: int) -> dict | None:
|
| 24 |
"""
|
| 25 |
Ficha mΓ©dica del paciente (grupo sanguΓneo, peso, altura, observaciones generales) β
|
|
|
|
| 20 |
return [d.get("descripcion", "") for d in data.get("detalle", [])]
|
| 21 |
|
| 22 |
|
| 23 |
+
def get_paciente(paciente_id: int) -> dict | None:
|
| 24 |
+
"""
|
| 25 |
+
Datos bΓ‘sicos del paciente cacheados en M1 (`datos_personales`: nombre, apellido, dni,
|
| 26 |
+
gΓ©nero, fecha de nacimiento, obra social como string libre) β para mostrar en la
|
| 27 |
+
pΓ‘gina de detalle de cama del front. Mismo criterio que `get_ficha_medica`: `None`
|
| 28 |
+
significa que no se pudo obtener (paciente inexistente en la cachΓ© de M1, o M1 no
|
| 29 |
+
respondiΓ³), y el router lo traduce a 404.
|
| 30 |
+
"""
|
| 31 |
+
if settings.mock_external_services:
|
| 32 |
+
return {
|
| 33 |
+
"id_paciente": paciente_id,
|
| 34 |
+
"datos_personales": {
|
| 35 |
+
"dni": "00000000",
|
| 36 |
+
"nombre": "Paciente",
|
| 37 |
+
"apellido": "Mock",
|
| 38 |
+
"genero": "X",
|
| 39 |
+
"fecha_nacimiento": "1990-01-01",
|
| 40 |
+
"obra_social": "OSDE 210",
|
| 41 |
+
},
|
| 42 |
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
| 43 |
+
"updated_at": datetime.now(timezone.utc).isoformat(),
|
| 44 |
+
}
|
| 45 |
+
return _get(f"{settings.m1_hce_url}/api/v1/pacientes/{paciente_id}")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
def get_ficha_medica(paciente_id: int) -> dict | None:
|
| 49 |
"""
|
| 50 |
Ficha mΓ©dica del paciente (grupo sanguΓneo, peso, altura, observaciones generales) β
|
app/routers/pacientes.py
CHANGED
|
@@ -11,7 +11,7 @@ from fastapi import APIRouter, Depends, HTTPException, status
|
|
| 11 |
|
| 12 |
from app.dependencies import require_roles
|
| 13 |
from app.integrations import hce
|
| 14 |
-
from app.schemas.paciente import AntecedenteResponse, FichaMedicaResponse
|
| 15 |
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
|
@@ -23,6 +23,27 @@ _ERR_404 = {
|
|
| 23 |
}
|
| 24 |
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
@router.get(
|
| 27 |
"/{paciente_id}/ficha-medica",
|
| 28 |
response_model=FichaMedicaResponse,
|
|
|
|
| 11 |
|
| 12 |
from app.dependencies import require_roles
|
| 13 |
from app.integrations import hce
|
| 14 |
+
from app.schemas.paciente import AntecedenteResponse, FichaMedicaResponse, PacienteResponse
|
| 15 |
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
|
|
|
| 23 |
}
|
| 24 |
|
| 25 |
|
| 26 |
+
@router.get(
|
| 27 |
+
"/{paciente_id}",
|
| 28 |
+
response_model=PacienteResponse,
|
| 29 |
+
summary="Obtener datos bΓ‘sicos de un paciente (M1 HCE)",
|
| 30 |
+
responses={
|
| 31 |
+
401: {"description": "No autenticado"},
|
| 32 |
+
403: {"description": "Sin permisos"},
|
| 33 |
+
404: {"description": "Paciente no encontrado en M1, o M1 no respondiΓ³"},
|
| 34 |
+
},
|
| 35 |
+
)
|
| 36 |
+
def get_paciente(
|
| 37 |
+
paciente_id: int,
|
| 38 |
+
user: dict = Depends(require_roles("ADMINISTRATIVO", "MEDICO", "LIMPIEZA")),
|
| 39 |
+
):
|
| 40 |
+
data = hce.get_paciente(paciente_id)
|
| 41 |
+
if data is None:
|
| 42 |
+
logger.warning("Paciente no disponible en M1 β paciente_id=%s", paciente_id)
|
| 43 |
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=_ERR_404)
|
| 44 |
+
return PacienteResponse.model_validate(data)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
@router.get(
|
| 48 |
"/{paciente_id}/ficha-medica",
|
| 49 |
response_model=FichaMedicaResponse,
|
app/schemas/paciente.py
CHANGED
|
@@ -12,6 +12,22 @@ from pydantic import BaseModel, ConfigDict
|
|
| 12 |
from app.schemas.enums import TipoAntecedenteEnum
|
| 13 |
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
class FichaMedicaResponse(BaseModel):
|
| 16 |
model_config = ConfigDict(from_attributes=True)
|
| 17 |
|
|
|
|
| 12 |
from app.schemas.enums import TipoAntecedenteEnum
|
| 13 |
|
| 14 |
|
| 15 |
+
class PacienteResponse(BaseModel):
|
| 16 |
+
"""
|
| 17 |
+
Datos bΓ‘sicos del paciente cacheados en M1. `datos_personales` viaja tal cual lo
|
| 18 |
+
expone M1 (`PacienteSchema.datos_personales` es `additionalProperties: true` en su
|
| 19 |
+
propio OpenAPI β objeto libre, sin schema fijo: nombre/apellido/dni/gΓ©nero/fecha de
|
| 20 |
+
nacimiento/obra social, no siempre los mismos campos presentes) β se pasa como `dict`
|
| 21 |
+
en vez de tipar cada campo, para no romper si M1 agrega/saca alguno.
|
| 22 |
+
"""
|
| 23 |
+
model_config = ConfigDict(from_attributes=True)
|
| 24 |
+
|
| 25 |
+
id_paciente: int
|
| 26 |
+
datos_personales: Optional[dict] = None
|
| 27 |
+
created_at: datetime
|
| 28 |
+
updated_at: datetime
|
| 29 |
+
|
| 30 |
+
|
| 31 |
class FichaMedicaResponse(BaseModel):
|
| 32 |
model_config = ConfigDict(from_attributes=True)
|
| 33 |
|
documentation/M6_DISEΓO.md
CHANGED
|
@@ -278,21 +278,30 @@ lado de ellos.
|
|
| 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 |
|
| 282 |
| M1 HCE | `POST /hce/movimientos` | Al asignar cama o trasladar (movimiento unificado) |
|
| 283 |
| M1 HCE | `POST /hce/solicitudes/{solicitudHceId}/resultado` | Al resolver una solicitud |
|
| 284 |
| M1 HCE | `POST /hce/episodios/{episodioId}/eventos` | Al recibir una alerta de emergencia de M9 |
|
|
|
|
| 285 |
| M1 HCE | `GET /api/v1/pacientes/{pacienteId}/ficha-medica` | Consulta bajo demanda del front (2026-07) β pΓ‘gina de detalle de cama |
|
| 286 |
| M1 HCE | `GET /api/v1/pacientes/{pacienteId}/antecedentes` | Consulta bajo demanda del front (2026-07) β pΓ‘gina de detalle de cama |
|
| 287 |
| M2 Turnos | `GET /api/v1/appointments/{appointmentId}` | Al aprobar solicitud con `origen=CIRUGIA_PROGRAMADA` |
|
| 288 |
|
| 289 |
-
|
| 290 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
`app/routers/pacientes.py`) β a diferencia del resto de esta tabla, no se disparan desde
|
| 292 |
un flujo de negocio interno sino que el front los llama directamente cuando el usuario
|
| 293 |
-
abre el detalle de una cama. `hce.get_ficha_medica`/`get_antecedentes` no
|
| 294 |
-
"paciente sin ese dato" de "M1 no respondiΓ³": ambos casos devuelven `None` y el
|
| 295 |
-
responde `404` β simplificaciΓ³n aceptada, documentada en el docstring de esas
|
|
|
|
| 296 |
|
| 297 |
### 7.4 Estrategia de mock (2da entrega)
|
| 298 |
|
|
|
|
| 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 | `POST /hce/movimientos` | Al asignar cama o trasladar (movimiento unificado) |
|
| 282 |
| M1 HCE | `POST /hce/solicitudes/{solicitudHceId}/resultado` | Al resolver una solicitud |
|
| 283 |
| M1 HCE | `POST /hce/episodios/{episodioId}/eventos` | Al recibir una alerta de emergencia de M9 |
|
| 284 |
+
| M1 HCE | `GET /api/v1/pacientes/{pacienteId}` | Consulta bajo demanda del front (2026-07) β datos bΓ‘sicos del paciente en el detalle de cama |
|
| 285 |
| M1 HCE | `GET /api/v1/pacientes/{pacienteId}/ficha-medica` | Consulta bajo demanda del front (2026-07) β pΓ‘gina de detalle de cama |
|
| 286 |
| M1 HCE | `GET /api/v1/pacientes/{pacienteId}/antecedentes` | Consulta bajo demanda del front (2026-07) β pΓ‘gina de detalle de cama |
|
| 287 |
| M2 Turnos | `GET /api/v1/appointments/{appointmentId}` | Al aprobar solicitud con `origen=CIRUGIA_PROGRAMADA` |
|
| 288 |
|
| 289 |
+
> **CorrecciΓ³n 2026-07:** esta tabla documentaba antes `GET /hce/pacientes/{pacienteId}`
|
| 290 |
+
> (con prefijo `/hce/`) para el detalle de paciente β ese path nunca existiΓ³ realmente en
|
| 291 |
+
> M1 (mismo tipo de desvΓo doc-vs-cΓ³digo que `contraindicaciones`, ver punto 1 del
|
| 292 |
+
> changelog mΓ‘s abajo). El endpoint real, verificado en vivo contra M1
|
| 293 |
+
> (`documentation/integrations/openapi_docs/M1_openapi.json`), es
|
| 294 |
+
> `GET /api/v1/pacientes/{pacienteId}` β sin prefijo `/hce/` β y es el que consume
|
| 295 |
+
> `app.integrations.hce.get_paciente`.
|
| 296 |
+
|
| 297 |
+
Los tres endpoints de M1 marcados "consulta bajo demanda" son proxies puros expuestos por
|
| 298 |
+
M6 (`GET /api/v1/pacientes/{id}`, `/ficha-medica` y `/antecedentes`, ver
|
| 299 |
`app/routers/pacientes.py`) β a diferencia del resto de esta tabla, no se disparan desde
|
| 300 |
un flujo de negocio interno sino que el front los llama directamente cuando el usuario
|
| 301 |
+
abre el detalle de una cama. `hce.get_paciente`/`get_ficha_medica`/`get_antecedentes` no
|
| 302 |
+
distinguen "paciente sin ese dato" de "M1 no respondiΓ³": ambos casos devuelven `None` y el
|
| 303 |
+
router responde `404` β simplificaciΓ³n aceptada, documentada en el docstring de esas
|
| 304 |
+
funciones.
|
| 305 |
|
| 306 |
### 7.4 Estrategia de mock (2da entrega)
|
| 307 |
|
documentation/roles.md
CHANGED
|
@@ -90,6 +90,7 @@ LIMPIEZA no tiene acceso al historial de auditorΓa β no necesita visibilidad
|
|
| 90 |
|
| 91 |
| Endpoint | ADMINISTRATIVO | MEDICO | LIMPIEZA |
|
| 92 |
|---|:---:|:---:|:---:|
|
|
|
|
| 93 |
| `GET /pacientes/{pacienteId}/ficha-medica` | β | β | β |
|
| 94 |
| `GET /pacientes/{pacienteId}/antecedentes` | β | β | β |
|
| 95 |
|
|
|
|
| 90 |
|
| 91 |
| Endpoint | ADMINISTRATIVO | MEDICO | LIMPIEZA |
|
| 92 |
|---|:---:|:---:|:---:|
|
| 93 |
+
| `GET /pacientes/{pacienteId}` β datos bΓ‘sicos | β | β | β |
|
| 94 |
| `GET /pacientes/{pacienteId}/ficha-medica` | β | β | β |
|
| 95 |
| `GET /pacientes/{pacienteId}/antecedentes` | β | β | β |
|
| 96 |
|
scripts/seed_datos_reales.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
NormalizaciΓ³n de datos reales en Supabase β 3 fases (ver plan aprobado en
|
| 3 |
+
`docs/superpowers` o el historial de conversaciΓ³n del 2026-07-14).
|
| 4 |
+
|
| 5 |
+
Fase 1: corrige los campos de las 17 camas ya cargadas (piso/sector/tipo/hospital_id/
|
| 6 |
+
specialty_id/contraindicaciones) para que tengan sentido semΓ‘ntico y mΓ©dico, deja
|
| 7 |
+
el piso 5 exclusivo para quirΓ³fanos, y vacΓa TODAS las camas dejΓ‘ndolas DISPONIBLE.
|
| 8 |
+
Fase 2: trunca `solicitudes`/`reservas_quirofano` (datos de prueba viejos, confirmado con
|
| 9 |
+
el usuario) y siembra 6 internaciones + 3 traslados + 4 reservas de quirΓ³fano
|
| 10 |
+
usando los 7 pacientes reales de M1 (vΓa el service layer real de la app, no SQL
|
| 11 |
+
a mano) y episodios reales abiertos en M1.
|
| 12 |
+
Fase 3: sobre las camas que quedan sin paciente tras la fase 2, marca variedad de estados
|
| 13 |
+
(FUERA_DE_SERVICIO, BAJA_PERMANENTE) β sin tocar los quirΓ³fanos, que tienen
|
| 14 |
+
reservas activas dependientes de que sigan DISPONIBLE.
|
| 15 |
+
|
| 16 |
+
Uso:
|
| 17 |
+
.venv/bin/python scripts/seed_datos_reales.py
|
| 18 |
+
|
| 19 |
+
Requiere el `.env` real del proyecto (Supabase + cuenta de servicio de M6 en el Core).
|
| 20 |
+
`mock_external_services` se fuerza a `True` en este proceso: no hace falta generar
|
| 21 |
+
trΓ‘fico real hacia M1/M9/M7 por una carga de datos, solo hacia M1 (pacientes/episodios,
|
| 22 |
+
por `httpx` directo) y M10 (login de la cuenta de servicio).
|
| 23 |
+
"""
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
import sys
|
| 27 |
+
from datetime import datetime, timedelta, timezone
|
| 28 |
+
|
| 29 |
+
import httpx
|
| 30 |
+
|
| 31 |
+
from app.config import settings
|
| 32 |
+
# Fuerza mock para las notificaciones salientes del service layer (HCE/M9/M7) β no
|
| 33 |
+
# quiere decir que no consultemos M1 real: las consultas de este script (pacientes,
|
| 34 |
+
# episodios) van directo por httpx, no pasan por `app.integrations.hce`.
|
| 35 |
+
settings.mock_external_services = True
|
| 36 |
+
|
| 37 |
+
from app.dependencies import get_db # noqa: E402
|
| 38 |
+
from app.integrations import core_auth # noqa: E402
|
| 39 |
+
from app.schemas.solicitud import SolicitudHceWebhook, SolicitudResolucionRequest # noqa: E402
|
| 40 |
+
from app.schemas.reserva import ReservaQuirofanoCreateRequest # noqa: E402
|
| 41 |
+
from app.services import solicitud_service, cama_service # noqa: E402
|
| 42 |
+
|
| 43 |
+
# `settings.m1_hce_url` apunta al hostname interno de docker (`http://modulo1:8001`),
|
| 44 |
+
# solo resoluble dentro del cluster donde corre M6 desplegado. Este script corre standalone
|
| 45 |
+
# (fuera del cluster), asΓ que necesita el host pΓΊblico real de M1.
|
| 46 |
+
M1_PUBLIC_URL = "https://healthgrid-hce-backend.onrender.com"
|
| 47 |
+
|
| 48 |
+
RESUELTO_POR = 1 # id de usuario ADMINISTRATIVO, mismo criterio que datos previos
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _m1_headers() -> dict:
|
| 52 |
+
token = core_auth.get_service_token()
|
| 53 |
+
if not token:
|
| 54 |
+
print("ERROR: no se pudo obtener token de la cuenta de servicio (CORE_SERVICE_EMAIL/PASSWORD).", file=sys.stderr)
|
| 55 |
+
sys.exit(1)
|
| 56 |
+
return {"Authorization": f"Bearer {token}"}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _abrir_episodio_m1(paciente_id: int, tipo: str, diagnostico: str) -> int:
|
| 60 |
+
"""POST /api/v1/patients/{id}/episodes en M1 real β devuelve id_episodio real."""
|
| 61 |
+
r = httpx.post(
|
| 62 |
+
f"{M1_PUBLIC_URL}/api/v1/patients/{paciente_id}/episodes",
|
| 63 |
+
json={"tipo": tipo, "estado": "open", "diagnostico_principal": diagnostico},
|
| 64 |
+
headers=_m1_headers(),
|
| 65 |
+
timeout=15,
|
| 66 |
+
)
|
| 67 |
+
r.raise_for_status()
|
| 68 |
+
return r.json()["id_episodio"]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# βββ Fase 1: normalizar camas βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 72 |
+
|
| 73 |
+
# id de cama -> (numero, piso, sector, tipo, specialty_id, contraindicaciones)
|
| 74 |
+
CAMAS_FASE1 = {
|
| 75 |
+
9: ("101", 1, "GUARDIA", "ESTANDAR", None, []),
|
| 76 |
+
10: ("102", 1, "GUARDIA", "CRITICA", None, []),
|
| 77 |
+
18: ("103", 1, "GUARDIA", "PEDIATRICA", None, []),
|
| 78 |
+
11: ("201", 2, "SALA_COMUN", "ESTANDAR", None, []),
|
| 79 |
+
12: ("202", 2, "SALA_COMUN", "ESTANDAR", None, []),
|
| 80 |
+
13: ("203", 2, "SALA_COMUN", "AISLAMIENTO", None, ["COVID"]),
|
| 81 |
+
15: ("204", 2, "SALA_COMUN", "ESTANDAR", None, []),
|
| 82 |
+
16: ("205", 2, "SALA_COMUN", "ESTANDAR", None, []),
|
| 83 |
+
20: ("206", 2, "SALA_COMUN", "ESTANDAR", None, []),
|
| 84 |
+
5: ("301", 3, "UTI", "CRITICA", None, []),
|
| 85 |
+
6: ("302", 3, "UTI", "AISLAMIENTO", None, ["INMUNOSUPRIMIDO"]),
|
| 86 |
+
8: ("303", 3, "UTI", "CRITICA", None, []),
|
| 87 |
+
14: ("401", 4, "NEONATOLOGIA", "PEDIATRICA", None, []),
|
| 88 |
+
21: ("402", 4, "NEONATOLOGIA", "PEDIATRICA", None, ["ALERGIA_LATEX"]),
|
| 89 |
+
7: ("501", 5, "QUIROFANO", "CIRUGIA", 1, []),
|
| 90 |
+
17: ("502", 5, "QUIROFANO", "CIRUGIA", 22, []),
|
| 91 |
+
19: ("503", 5, "QUIROFANO", "CIRUGIA", 43, []),
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
# numero (nuevo) -> id de cama, para referenciar por nΓΊmero "de piso" en las fases 2/3
|
| 95 |
+
CAMA_ID_POR_NUMERO = {v[0]: k for k, v in CAMAS_FASE1.items()}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def fase1_normalizar_camas(db) -> None:
|
| 99 |
+
print("\n=== FASE 1: normalizar camas ===")
|
| 100 |
+
now = datetime.now(timezone.utc).isoformat()
|
| 101 |
+
for cama_id, (numero, piso, sector, tipo, specialty_id, contraindicaciones) in CAMAS_FASE1.items():
|
| 102 |
+
updates = {
|
| 103 |
+
"numero": numero,
|
| 104 |
+
"piso": piso,
|
| 105 |
+
"sector": sector,
|
| 106 |
+
"tipo": tipo,
|
| 107 |
+
"specialty_id": specialty_id,
|
| 108 |
+
"hospital_id": "1",
|
| 109 |
+
"contraindicaciones_incompatibles": contraindicaciones,
|
| 110 |
+
"estado": "DISPONIBLE",
|
| 111 |
+
"paciente_id": None,
|
| 112 |
+
"ultimo_movimiento_tipo": None,
|
| 113 |
+
"solicitud_hce_id": None,
|
| 114 |
+
"fecha_ingreso": None,
|
| 115 |
+
"alta_tipo": None,
|
| 116 |
+
"alta_timestamp": None,
|
| 117 |
+
"episodio_id": None,
|
| 118 |
+
"ultima_actualizacion": now,
|
| 119 |
+
}
|
| 120 |
+
db.table("camas").update(updates).eq("id", cama_id).execute()
|
| 121 |
+
print(f" cama id={cama_id} -> numero={numero} piso={piso} sector={sector} tipo={tipo}")
|
| 122 |
+
print(f"Fase 1 OK β {len(CAMAS_FASE1)} camas normalizadas, todas DISPONIBLE.")
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# βββ Fase 2: poblar con pacientes reales de M1 ββββββββββββββββββββββββββββββ
|
| 126 |
+
|
| 127 |
+
INTERNACIONES = [
|
| 128 |
+
# (paciente_id, cama_numero_destino, medico_solicitante_id, diagnostico, prioridad)
|
| 129 |
+
(3001, "101", 10, "Dolor torΓ‘cico agudo a estudio", "ALTA"),
|
| 130 |
+
(3002, "201", 10, "NeumonΓa adquirida en la comunidad", "MEDIA"),
|
| 131 |
+
(3003, "301", 14, "Sepsis de foco urinario", "MUY_ALTA"),
|
| 132 |
+
(3004, "202", 10, "Pielonefritis aguda", "MEDIA"),
|
| 133 |
+
(3005, "102", 14, "Apendicitis aguda, prequirΓΊrgico", "ALTA"),
|
| 134 |
+
(22, "302", 14, "Politraumatismo, aislamiento por sospecha infecciosa", "MUY_ALTA"),
|
| 135 |
+
]
|
| 136 |
+
|
| 137 |
+
TRASLADOS = [
|
| 138 |
+
# (paciente_id, cama_origen_numero, cama_destino_numero, motivo)
|
| 139 |
+
(3001, "101", "205", "Estabilizado en guardia, pasa a sala comΓΊn"),
|
| 140 |
+
(3003, "301", "204", "Sale de terapia intensiva, mejorΓa clΓnica"),
|
| 141 |
+
(22, "302", "203", "ContinΓΊa aislamiento fuera de UTI"),
|
| 142 |
+
]
|
| 143 |
+
|
| 144 |
+
RESERVAS = [
|
| 145 |
+
# (paciente_id, quirofano_numero, medico_cirujano_id, procedimiento, inicio, fin)
|
| 146 |
+
(3005, "501", 30, "ApendicectomΓa laparoscΓ³pica",
|
| 147 |
+
datetime(2026, 7, 20, 9, 0, tzinfo=timezone.utc), timedelta(hours=2)),
|
| 148 |
+
(3003, "502", 30, "Drenaje programado",
|
| 149 |
+
datetime(2026, 7, 21, 9, 0, tzinfo=timezone.utc), timedelta(hours=1, minutes=30)),
|
| 150 |
+
(216, "503", 22, "Hernia inguinal (cirugΓa ambulatoria)",
|
| 151 |
+
datetime(2026, 7, 22, 10, 0, tzinfo=timezone.utc), timedelta(hours=1)),
|
| 152 |
+
(3004, "501", 30, "ColecistectomΓa programada",
|
| 153 |
+
datetime(2026, 7, 20, 14, 0, tzinfo=timezone.utc), timedelta(hours=2)),
|
| 154 |
+
]
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _truncar_datos_viejos(db) -> None:
|
| 158 |
+
print("Truncando solicitudes/reservas_quirofano viejas...")
|
| 159 |
+
db.table("solicitudes").delete().gte("id", 0).execute()
|
| 160 |
+
db.table("reservas_quirofano").delete().gte("id", 0).execute()
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def fase2_poblar_pacientes_reales(db) -> None:
|
| 164 |
+
print("\n=== FASE 2: poblar con pacientes reales de M1 ===")
|
| 165 |
+
_truncar_datos_viejos(db)
|
| 166 |
+
|
| 167 |
+
# --- Internaciones ---
|
| 168 |
+
for i, (paciente_id, cama_num, medico_id, diagnostico, prioridad) in enumerate(INTERNACIONES, start=1):
|
| 169 |
+
cama_id = CAMA_ID_POR_NUMERO[cama_num]
|
| 170 |
+
episodio_id = _abrir_episodio_m1(paciente_id, "internacion", diagnostico)
|
| 171 |
+
webhook = SolicitudHceWebhook(
|
| 172 |
+
tipo="INTERNACION",
|
| 173 |
+
solicitud_hce_id=f"HCE-INT-{paciente_id}",
|
| 174 |
+
paciente_id=paciente_id,
|
| 175 |
+
medico_solicitante_id=medico_id,
|
| 176 |
+
cama_solicitada_id=cama_id,
|
| 177 |
+
origen="GUARDIA",
|
| 178 |
+
diagnostico_ingreso=diagnostico,
|
| 179 |
+
prioridad=prioridad,
|
| 180 |
+
hospital_id="1",
|
| 181 |
+
episodio_id=episodio_id,
|
| 182 |
+
timestamp=datetime.now(timezone.utc),
|
| 183 |
+
)
|
| 184 |
+
sol = solicitud_service.recibir_solicitud(db, webhook)
|
| 185 |
+
solicitud_service.resolver_solicitud(
|
| 186 |
+
db, sol.solicitud_id, SolicitudResolucionRequest(accion="APROBAR"), resuelto_por=RESUELTO_POR,
|
| 187 |
+
)
|
| 188 |
+
print(f" [{i}/6] INTERNACION paciente={paciente_id} -> cama {cama_num} (episodio_id={episodio_id}) OK")
|
| 189 |
+
|
| 190 |
+
# --- Traslados ---
|
| 191 |
+
for i, (paciente_id, origen_num, destino_num, motivo) in enumerate(TRASLADOS, start=1):
|
| 192 |
+
origen_id = CAMA_ID_POR_NUMERO[origen_num]
|
| 193 |
+
destino_id = CAMA_ID_POR_NUMERO[destino_num]
|
| 194 |
+
webhook = SolicitudHceWebhook(
|
| 195 |
+
tipo="TRASLADO",
|
| 196 |
+
solicitud_hce_id=f"HCE-TRA-{paciente_id}",
|
| 197 |
+
paciente_id=paciente_id,
|
| 198 |
+
medico_solicitante_id=10,
|
| 199 |
+
cama_origen_id=origen_id,
|
| 200 |
+
cama_destino_solicitada_id=destino_id,
|
| 201 |
+
motivo_traslado=motivo,
|
| 202 |
+
hospital_id="1",
|
| 203 |
+
timestamp=datetime.now(timezone.utc),
|
| 204 |
+
)
|
| 205 |
+
sol = solicitud_service.recibir_solicitud(db, webhook)
|
| 206 |
+
solicitud_service.resolver_solicitud(
|
| 207 |
+
db, sol.solicitud_id, SolicitudResolucionRequest(accion="APROBAR"), resuelto_por=RESUELTO_POR,
|
| 208 |
+
)
|
| 209 |
+
print(f" [{i}/3] TRASLADO paciente={paciente_id} -> {origen_num} => {destino_num} OK")
|
| 210 |
+
|
| 211 |
+
# --- Reservas de quirΓ³fano ---
|
| 212 |
+
for i, (paciente_id, quir_num, medico_id, procedimiento, inicio, duracion) in enumerate(RESERVAS, start=1):
|
| 213 |
+
quir_id = CAMA_ID_POR_NUMERO[quir_num]
|
| 214 |
+
data = ReservaQuirofanoCreateRequest(
|
| 215 |
+
turno_id=9000 + i,
|
| 216 |
+
paciente_id=paciente_id,
|
| 217 |
+
medico_cirujano_id=medico_id,
|
| 218 |
+
fecha_hora_inicio=inicio,
|
| 219 |
+
fecha_hora_fin_estimada=inicio + duracion,
|
| 220 |
+
prioridad="MEDIA",
|
| 221 |
+
observaciones=procedimiento,
|
| 222 |
+
)
|
| 223 |
+
cama_service.create_reserva(db, quir_id, data)
|
| 224 |
+
print(f" [{i}/4] RESERVA paciente={paciente_id} -> quirΓ³fano {quir_num} ({procedimiento}) OK")
|
| 225 |
+
|
| 226 |
+
print("Fase 2 OK.")
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
# βββ Fase 3: variedad de estados en camas sin paciente ββββββββββββββββββββββ
|
| 230 |
+
|
| 231 |
+
CAMAS_FASE3 = {
|
| 232 |
+
"303": ("FUERA_DE_SERVICIO", "Mantenimiento preventivo de monitor"),
|
| 233 |
+
"103": ("BAJA_PERMANENTE", "Cama retirada de servicio"),
|
| 234 |
+
"206": ("FUERA_DE_SERVICIO", "Mantenimiento"),
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def fase3_variedad_estados(db) -> None:
|
| 239 |
+
print("\n=== FASE 3: variedad de estados en camas sin paciente ===")
|
| 240 |
+
now = datetime.now(timezone.utc).isoformat()
|
| 241 |
+
for numero, (estado, motivo) in CAMAS_FASE3.items():
|
| 242 |
+
cama_id = CAMA_ID_POR_NUMERO[numero]
|
| 243 |
+
db.table("camas").update({"estado": estado, "ultima_actualizacion": now}).eq("id", cama_id).execute()
|
| 244 |
+
print(f" cama numero={numero} (id={cama_id}) -> {estado} ({motivo})")
|
| 245 |
+
print("Fase 3 OK β quirΓ³fanos (501/502/503) y neonatologΓa (401/402) sin tocar.")
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def main() -> int:
|
| 249 |
+
db = get_db()
|
| 250 |
+
fase1_normalizar_camas(db)
|
| 251 |
+
fase2_poblar_pacientes_reales(db)
|
| 252 |
+
fase3_variedad_estados(db)
|
| 253 |
+
print("\nβ Seed completo.")
|
| 254 |
+
return 0
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
if __name__ == "__main__":
|
| 258 |
+
raise SystemExit(main())
|
tests/test_pacientes.py
CHANGED
|
@@ -1,12 +1,39 @@
|
|
| 1 |
"""
|
| 2 |
-
Tests del router de Pacientes (proxy de consulta a M1 HCE): ficha mΓ©dica y
|
| 3 |
-
clΓnicos, para la pΓ‘gina de detalle de cama del front.
|
| 4 |
"""
|
| 5 |
from fastapi.testclient import TestClient
|
| 6 |
|
| 7 |
PREFIX = "/api/v1/pacientes"
|
| 8 |
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
# βββ Ficha mΓ©dica βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
|
| 12 |
def test_get_ficha_medica_sin_token_401(client: TestClient):
|
|
|
|
| 1 |
"""
|
| 2 |
+
Tests del router de Pacientes (proxy de consulta a M1 HCE): datos bΓ‘sicos, ficha mΓ©dica y
|
| 3 |
+
antecedentes clΓnicos, para la pΓ‘gina de detalle de cama del front.
|
| 4 |
"""
|
| 5 |
from fastapi.testclient import TestClient
|
| 6 |
|
| 7 |
PREFIX = "/api/v1/pacientes"
|
| 8 |
|
| 9 |
|
| 10 |
+
# βββ Datos bΓ‘sicos del paciente βββββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
+
|
| 12 |
+
def test_get_paciente_sin_token_401(client: TestClient):
|
| 13 |
+
resp = client.get(f"{PREFIX}/7")
|
| 14 |
+
assert resp.status_code == 401
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_get_paciente_ok_mock(client: TestClient, medico_headers):
|
| 18 |
+
resp = client.get(f"{PREFIX}/7", headers=medico_headers)
|
| 19 |
+
assert resp.status_code == 200
|
| 20 |
+
data = resp.json()
|
| 21 |
+
assert data["id_paciente"] == 7
|
| 22 |
+
assert data["datos_personales"]["obra_social"] == "OSDE 210"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_get_paciente_no_disponible_404(client: TestClient, medico_headers, monkeypatch):
|
| 26 |
+
monkeypatch.setattr("app.integrations.hce.get_paciente", lambda pid: None)
|
| 27 |
+
resp = client.get(f"{PREFIX}/7", headers=medico_headers)
|
| 28 |
+
assert resp.status_code == 404
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_get_paciente_rol_limpieza_ok(client: TestClient, limpieza_headers):
|
| 32 |
+
"""Los 3 roles pueden consultar β mismo criterio que GET /camas."""
|
| 33 |
+
resp = client.get(f"{PREFIX}/7", headers=limpieza_headers)
|
| 34 |
+
assert resp.status_code == 200
|
| 35 |
+
|
| 36 |
+
|
| 37 |
# βββ Ficha mΓ©dica βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 38 |
|
| 39 |
def test_get_ficha_medica_sin_token_401(client: TestClient):
|