Mate11 commited on
Commit
31c8dd6
·
1 Parent(s): 5f12c93

CARPETA DUPLICADA

Browse files
app/config.py CHANGED
@@ -17,7 +17,7 @@ class Settings(BaseSettings):
17
  jwt_expire_minutes: int = 60
18
 
19
  # Entorno — controla comportamiento de endpoints de desarrollo
20
- environment: str = "production"
21
 
22
  # CORS — lista explícita de orígenes permitidos
23
  allowed_origins: list[str] = ["http://localhost:3000", "http://localhost:5173"]
 
17
  jwt_expire_minutes: int = 60
18
 
19
  # Entorno — controla comportamiento de endpoints de desarrollo
20
+ environment: str = "development"
21
 
22
  # CORS — lista explícita de orígenes permitidos
23
  allowed_origins: list[str] = ["http://localhost:3000", "http://localhost:5173"]
app/main.py CHANGED
@@ -2,6 +2,7 @@
2
  Health Grid - Módulo 6: Internación y Gestión de Camas
3
  API REST: http://localhost:8006/api/v1
4
  """
 
5
  import logging
6
  from contextlib import asynccontextmanager
7
  from fastapi import FastAPI, Request, status
@@ -12,9 +13,9 @@ from app.config import settings
12
  from app.dependencies import engine, Base, create_access_token
13
 
14
  # Registrar modelos antes de create_all
15
- import app.models.cama # noqa: F401
16
- import app.models.solicitud # noqa: F401
17
- import app.models.reserva # noqa: F401
18
 
19
  from app.routers import camas, solicitudes, webhooks
20
 
@@ -28,6 +29,7 @@ logging.basicConfig(
28
 
29
  # ─── Startup / Shutdown ────────────────────────────────────────────────────
30
 
 
31
  @asynccontextmanager
32
  async def lifespan(app: FastAPI):
33
  Base.metadata.create_all(bind=engine)
@@ -66,21 +68,33 @@ app.include_router(webhooks.router, prefix=PREFIX)
66
 
67
  # ─── Endpoint de auth local (mock de M10 — solo para desarrollo) ───────────
68
 
69
- @app.get(f"{PREFIX}/auth/token", tags=["Auth (dev)"], summary="Obtener JWT de desarrollo", include_in_schema=True)
 
 
 
 
 
 
70
  def get_dev_token(usuario: str, password: str):
71
  """
72
  Solo habilitado si ENVIRONMENT=development.
73
  Genera un JWT de prueba. Roles válidos: ADMINISTRATIVO | MEDICO | LIMPIEZA
74
  """
75
  if settings.environment != "development":
76
- return JSONResponse(status_code=404, content={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "Not Found"})
 
 
 
77
 
78
  roles_validos = {"ADMINISTRATIVO", "MEDICO", "LIMPIEZA"}
79
  rol = usuario.upper()
80
  if rol not in roles_validos:
81
  return JSONResponse(
82
  status_code=status.HTTP_401_UNAUTHORIZED,
83
- content={"codigo": "NO_AUTENTICADO", "mensaje": f"Rol inválido. Usar: {roles_validos}"},
 
 
 
84
  )
85
  token = create_access_token(sub="1", rol=rol)
86
  return {"access_token": token, "token_type": "bearer", "rol": rol}
@@ -88,6 +102,7 @@ def get_dev_token(usuario: str, password: str):
88
 
89
  # ─── Health check ──────────────────────────────────────────────────────────
90
 
 
91
  @app.get("/health", tags=["Health"])
92
  def health():
93
  return {"status": "ok", "module": "M6 - Internación"}
@@ -95,11 +110,15 @@ def health():
95
 
96
  # ─── Manejadores de errores globales ───────────────────────────────────────
97
 
 
98
  @app.exception_handler(404)
99
  async def not_found_handler(request: Request, exc: Exception):
100
  return JSONResponse(
101
  status_code=404,
102
- content={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "El recurso solicitado no existe"},
 
 
 
103
  )
104
 
105
 
@@ -107,5 +126,8 @@ async def not_found_handler(request: Request, exc: Exception):
107
  async def method_not_allowed_handler(request: Request, exc: Exception):
108
  return JSONResponse(
109
  status_code=405,
110
- content={"codigo": "METODO_NO_PERMITIDO", "mensaje": "Método HTTP no permitido"},
 
 
 
111
  )
 
2
  Health Grid - Módulo 6: Internación y Gestión de Camas
3
  API REST: http://localhost:8006/api/v1
4
  """
5
+
6
  import logging
7
  from contextlib import asynccontextmanager
8
  from fastapi import FastAPI, Request, status
 
13
  from app.dependencies import engine, Base, create_access_token
14
 
15
  # Registrar modelos antes de create_all
16
+ import app.models.cama # noqa: F401
17
+ import app.models.solicitud # noqa: F401
18
+ import app.models.reserva # noqa: F401
19
 
20
  from app.routers import camas, solicitudes, webhooks
21
 
 
29
 
30
  # ─── Startup / Shutdown ────────────────────────────────────────────────────
31
 
32
+
33
  @asynccontextmanager
34
  async def lifespan(app: FastAPI):
35
  Base.metadata.create_all(bind=engine)
 
68
 
69
  # ─── Endpoint de auth local (mock de M10 — solo para desarrollo) ───────────
70
 
71
+
72
+ @app.get(
73
+ f"{PREFIX}/auth/token",
74
+ tags=["Auth (dev)"],
75
+ summary="Obtener JWT de desarrollo",
76
+ include_in_schema=True,
77
+ )
78
  def get_dev_token(usuario: str, password: str):
79
  """
80
  Solo habilitado si ENVIRONMENT=development.
81
  Genera un JWT de prueba. Roles válidos: ADMINISTRATIVO | MEDICO | LIMPIEZA
82
  """
83
  if settings.environment != "development":
84
+ return JSONResponse(
85
+ status_code=404,
86
+ content={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "Not Found"},
87
+ )
88
 
89
  roles_validos = {"ADMINISTRATIVO", "MEDICO", "LIMPIEZA"}
90
  rol = usuario.upper()
91
  if rol not in roles_validos:
92
  return JSONResponse(
93
  status_code=status.HTTP_401_UNAUTHORIZED,
94
+ content={
95
+ "codigo": "NO_AUTENTICADO",
96
+ "mensaje": f"Rol inválido. Usar: {roles_validos}",
97
+ },
98
  )
99
  token = create_access_token(sub="1", rol=rol)
100
  return {"access_token": token, "token_type": "bearer", "rol": rol}
 
102
 
103
  # ─── Health check ──────────────────────────────────────────────────────────
104
 
105
+
106
  @app.get("/health", tags=["Health"])
107
  def health():
108
  return {"status": "ok", "module": "M6 - Internación"}
 
110
 
111
  # ─── Manejadores de errores globales ───────────────────────────────────────
112
 
113
+
114
  @app.exception_handler(404)
115
  async def not_found_handler(request: Request, exc: Exception):
116
  return JSONResponse(
117
  status_code=404,
118
+ content={
119
+ "codigo": "RECURSO_NO_ENCONTRADO",
120
+ "mensaje": "El recurso solicitado no existe",
121
+ },
122
  )
123
 
124
 
 
126
  async def method_not_allowed_handler(request: Request, exc: Exception):
127
  return JSONResponse(
128
  status_code=405,
129
+ content={
130
+ "codigo": "METODO_NO_PERMITIDO",
131
+ "mensaje": "Método HTTP no permitido",
132
+ },
133
  )
backend/Dockerfile DELETED
@@ -1,12 +0,0 @@
1
- FROM python:3.12-slim
2
-
3
- WORKDIR /app
4
-
5
- COPY requirements.txt .
6
- RUN pip install --no-cache-dir -r requirements.txt
7
-
8
- COPY . .
9
-
10
- EXPOSE 8006
11
-
12
- CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8006", "--reload"]
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/auth/__init__.py DELETED
File without changes
backend/auth/dependencies.py DELETED
@@ -1,35 +0,0 @@
1
- from fastapi import Depends, HTTPException, status
2
- from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
3
- from auth.jwt_handler import decode_token
4
-
5
- security = HTTPBearer()
6
-
7
- _ERROR_401 = {"codigo": "NO_AUTENTICADO", "mensaje": "Token ausente, expirado o malformado"}
8
- _ERROR_403 = {"codigo": "NO_AUTORIZADO", "mensaje": "No tiene permisos para esta operación"}
9
-
10
-
11
- def get_current_user(
12
- credentials: HTTPAuthorizationCredentials = Depends(security),
13
- ) -> dict:
14
- """Extrae y valida el JWT. Devuelve el payload con 'sub' y 'rol'."""
15
- try:
16
- payload = decode_token(credentials.credentials)
17
- except ValueError:
18
- raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401)
19
-
20
- if "sub" not in payload or "rol" not in payload:
21
- raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401)
22
-
23
- return payload
24
-
25
-
26
- def require_roles(*roles: str):
27
- """
28
- Devuelve una dependencia que verifica que el usuario tenga uno de los roles indicados.
29
- Uso: Depends(require_roles("ADMINISTRATIVO", "MEDICO"))
30
- """
31
- def checker(user: dict = Depends(get_current_user)) -> dict:
32
- if user.get("rol") not in roles:
33
- raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=_ERROR_403)
34
- return user
35
- return checker
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/auth/jwt_handler.py DELETED
@@ -1,35 +0,0 @@
1
- from datetime import datetime, timedelta, timezone
2
- from typing import Optional
3
- from jose import JWTError, jwt
4
- from config import settings
5
-
6
-
7
- def create_access_token(sub: str, rol: str, extra: dict = None) -> str:
8
- """Genera un JWT firmado con el secret del módulo."""
9
- now = datetime.now(timezone.utc)
10
- payload = {
11
- "sub": str(sub),
12
- "rol": rol,
13
- "iat": now,
14
- "exp": now + timedelta(minutes=settings.jwt_expire_minutes),
15
- }
16
- if extra:
17
- payload.update(extra)
18
- return jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)
19
-
20
-
21
- def decode_token(token: str) -> dict:
22
- """
23
- Decodifica y valida un JWT.
24
- En producción esto llamaría a M10 (Core) para validar.
25
- En este módulo validamos el token localmente con el secret compartido.
26
- """
27
- try:
28
- payload = jwt.decode(
29
- token,
30
- settings.jwt_secret,
31
- algorithms=[settings.jwt_algorithm],
32
- )
33
- return payload
34
- except JWTError as e:
35
- raise ValueError(f"Token inválido: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/config.py DELETED
@@ -1,28 +0,0 @@
1
- from pydantic_settings import BaseSettings
2
-
3
-
4
- class Settings(BaseSettings):
5
- # Base de datos
6
- database_url: str = "postgresql://admin:secret@localhost:5432/internacion_db"
7
-
8
- # JWT
9
- jwt_secret: str = "supersecretkey_change_in_production"
10
- jwt_algorithm: str = "HS256"
11
- jwt_expire_minutes: int = 60
12
-
13
- # URLs de módulos externos
14
- m1_hce_url: str = "http://localhost:8001"
15
- m2_turnos_url: str = "http://localhost:8002"
16
- m7_facturacion_url: str = "http://localhost:8007"
17
- m9_monitoreo_url: str = "http://localhost:8009"
18
- m10_core_url: str = "http://localhost:8010"
19
-
20
- # Mock externos (si True, no llama a los otros módulos)
21
- mock_external_services: bool = True
22
-
23
- class Config:
24
- env_file = ".env"
25
- case_sensitive = False
26
-
27
-
28
- settings = Settings()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/database.py DELETED
@@ -1,24 +0,0 @@
1
- from sqlalchemy import create_engine
2
- from sqlalchemy.orm import sessionmaker, DeclarativeBase
3
- from config import settings
4
-
5
- engine = create_engine(
6
- settings.database_url,
7
- pool_pre_ping=True,
8
- pool_size=5,
9
- max_overflow=10,
10
- )
11
-
12
- SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
13
-
14
-
15
- class Base(DeclarativeBase):
16
- pass
17
-
18
-
19
- def get_db():
20
- db = SessionLocal()
21
- try:
22
- yield db
23
- finally:
24
- db.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/main.py DELETED
@@ -1,102 +0,0 @@
1
- """
2
- Health Grid - Módulo 6: Internación y Gestión de Camas
3
- Corre en http://localhost:8006/api/v1
4
- """
5
- from contextlib import asynccontextmanager
6
- from fastapi import FastAPI, Request, status
7
- from fastapi.middleware.cors import CORSMiddleware
8
- from fastapi.responses import JSONResponse
9
-
10
- from database import engine, Base
11
-
12
- # Importar modelos para que Base los registre antes del create_all
13
- import models.cama # noqa: F401
14
- import models.solicitud # noqa: F401
15
- import models.reserva # noqa: F401
16
-
17
- from routers import camas, solicitudes, webhooks
18
- from auth.jwt_handler import create_access_token
19
-
20
-
21
- # ─── Startup / Shutdown ────────────────────────────────────────────────────
22
-
23
- @asynccontextmanager
24
- async def lifespan(app: FastAPI):
25
- # Crear tablas en la BD si no existen
26
- Base.metadata.create_all(bind=engine)
27
- print("✅ Tablas creadas/verificadas correctamente")
28
- yield
29
-
30
-
31
- # ─── App ───────────────────────────────────────────────────────────────────
32
-
33
- app = FastAPI(
34
- title="Health Grid – Módulo 6: Internación y Gestión de Camas",
35
- description="API REST para gestión de camas hospitalarias y solicitudes de internación.",
36
- version="4.0.0",
37
- lifespan=lifespan,
38
- docs_url="/api/v1/docs",
39
- redoc_url="/api/v1/redoc",
40
- openapi_url="/api/v1/openapi.json",
41
- )
42
-
43
- app.add_middleware(
44
- CORSMiddleware,
45
- allow_origins=["*"],
46
- allow_credentials=True,
47
- allow_methods=["*"],
48
- allow_headers=["*"],
49
- )
50
-
51
- # ─── Prefijo global /api/v1 ────────────────────────────────────────────────
52
-
53
- PREFIX = "/api/v1"
54
-
55
- app.include_router(camas.router, prefix=PREFIX)
56
- app.include_router(solicitudes.router, prefix=PREFIX)
57
- app.include_router(webhooks.router, prefix=PREFIX)
58
-
59
-
60
- # ─── Endpoint de auth local (mock de M10 para desarrollo) ──────────────────
61
-
62
- @app.get(f"{PREFIX}/auth/token", tags=["Auth (dev)"], summary="Obtener JWT de desarrollo")
63
- def get_dev_token(usuario: str, password: str):
64
- """
65
- Genera un JWT de prueba. Solo para desarrollo local.
66
- Roles disponibles: ADMINISTRATIVO | MEDICO | LIMPIEZA
67
- Usuario = rol (ej: usuario=ADMINISTRATIVO password=cualquier_cosa)
68
- """
69
- roles_validos = {"ADMINISTRATIVO", "MEDICO", "LIMPIEZA"}
70
- rol = usuario.upper()
71
- if rol not in roles_validos:
72
- return JSONResponse(
73
- status_code=status.HTTP_401_UNAUTHORIZED,
74
- content={"codigo": "NO_AUTENTICADO", "mensaje": f"Rol inválido. Usar: {roles_validos}"},
75
- )
76
- token = create_access_token(sub="1", rol=rol)
77
- return {"access_token": token, "token_type": "bearer", "rol": rol}
78
-
79
-
80
- # ─── Health check ──────────────────────────────────────────────────────────
81
-
82
- @app.get("/health", tags=["Health"])
83
- def health():
84
- return {"status": "ok", "module": "M6 - Internación"}
85
-
86
-
87
- # ─── Manejadores de errores globales ───────────────────────────────────────
88
-
89
- @app.exception_handler(404)
90
- async def not_found_handler(request: Request, exc):
91
- return JSONResponse(
92
- status_code=404,
93
- content={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "El recurso solicitado no existe"},
94
- )
95
-
96
-
97
- @app.exception_handler(405)
98
- async def method_not_allowed_handler(request: Request, exc):
99
- return JSONResponse(
100
- status_code=405,
101
- content={"codigo": "METODO_NO_PERMITIDO", "mensaje": "Método HTTP no permitido"},
102
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/models/__init__.py DELETED
@@ -1,5 +0,0 @@
1
- from .cama import Cama
2
- from .solicitud import Solicitud
3
- from .reserva import ReservaQuirofano
4
-
5
- __all__ = ["Cama", "Solicitud", "ReservaQuirofano"]
 
 
 
 
 
 
backend/models/cama.py DELETED
@@ -1,43 +0,0 @@
1
- from __future__ import annotations
2
- from datetime import datetime, timezone
3
- from sqlalchemy import Column, Integer, String, DateTime
4
- from sqlalchemy.dialects.postgresql import ARRAY
5
- from sqlalchemy.orm import relationship
6
- from database import Base
7
-
8
-
9
- class Cama(Base):
10
- __tablename__ = "camas"
11
-
12
- id = Column(Integer, primary_key=True, autoincrement=True)
13
- numero = Column(String(20), nullable=False)
14
- piso = Column(Integer, nullable=False)
15
- # SectorEnum: UTI | SALA_COMUN | QUIROFANO | GUARDIA | NEONATOLOGIA
16
- sector = Column(String(20), nullable=False)
17
- # TipoCamaEnum: ESTANDAR | PEDIATRICA | AISLAMIENTO | CRITICA | CIRUGIA
18
- tipo = Column(String(20), nullable=False)
19
- # EstadoCamaEnum: DISPONIBLE | OCUPADA | EN_LIMPIEZA | FUERA_DE_SERVICIO | BAJA_PERMANENTE | CODIGO_ROJO
20
- estado = Column(String(20), nullable=False, default="DISPONIBLE")
21
- paciente_id = Column(Integer, nullable=True)
22
- hospital_id = Column(String(50), nullable=False)
23
- contraindicaciones_incompatibles = Column(ARRAY(String), nullable=False, default=list)
24
- ultima_actualizacion = Column(
25
- DateTime(timezone=True),
26
- default=lambda: datetime.now(timezone.utc),
27
- onupdate=lambda: datetime.now(timezone.utc),
28
- )
29
- # Rastrea si el último movimiento fue ALTA_MEDICA o TRASLADO
30
- # (para saber si hay que disparar CAMA_LISTA al pasar a DISPONIBLE)
31
- ultimo_movimiento_tipo = Column(String(20), nullable=True)
32
-
33
- solicitudes_solicitadas = relationship(
34
- "Solicitud",
35
- foreign_keys="Solicitud.cama_solicitada_id",
36
- back_populates="cama_solicitada",
37
- )
38
- solicitudes_asignadas = relationship(
39
- "Solicitud",
40
- foreign_keys="Solicitud.cama_asignada_id",
41
- back_populates="cama_asignada",
42
- )
43
- reservas = relationship("ReservaQuirofano", back_populates="cama")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/models/reserva.py DELETED
@@ -1,46 +0,0 @@
1
- from __future__ import annotations
2
- from datetime import datetime, timezone
3
- from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
4
- from sqlalchemy.orm import relationship
5
- from database import Base
6
-
7
-
8
- class ReservaQuirofano(Base):
9
- __tablename__ = "reservas_quirofano"
10
-
11
- id = Column(Integer, primary_key=True, autoincrement=True)
12
- cama_id = Column(Integer, ForeignKey("camas.id"), nullable=False)
13
-
14
- turno_id = Column(String(50), nullable=True)
15
- solicitud_urgencia_hce_id = Column(String(50), nullable=True, unique=True)
16
-
17
- # PROGRAMADA | EMERGENCIA
18
- origen = Column(String(20), nullable=False)
19
- # RESERVADA | EN_CURSO | COMPLETADA | CANCELADA
20
- estado = Column(String(20), nullable=False, default="RESERVADA")
21
- # PrioridadQuirofanoEnum: MUY_BAJA | BAJA | MEDIA | ALTA | MUY_ALTA | URGENTE
22
- prioridad = Column(String(20), nullable=False)
23
-
24
- paciente_id = Column(Integer, nullable=False)
25
- medico_cirujano_id = Column(Integer, nullable=False)
26
-
27
- fecha_hora_inicio = Column(DateTime(timezone=True), nullable=False)
28
- fecha_hora_fin_estimada = Column(DateTime(timezone=True), nullable=False)
29
- observaciones = Column(String(500), nullable=True)
30
-
31
- # Si fue desplazada por una urgente: apunta a la reserva que la desplazó
32
- desplazada_por_reserva_id = Column(
33
- Integer, ForeignKey("reservas_quirofano.id"), nullable=True
34
- )
35
-
36
- created_at = Column(
37
- DateTime(timezone=True),
38
- default=lambda: datetime.now(timezone.utc),
39
- )
40
-
41
- cama = relationship("Cama", back_populates="reservas")
42
- desplazada_por = relationship(
43
- "ReservaQuirofano",
44
- remote_side=[id],
45
- foreign_keys=[desplazada_por_reserva_id],
46
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/models/solicitud.py DELETED
@@ -1,61 +0,0 @@
1
- from __future__ import annotations
2
- from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
3
- from sqlalchemy.orm import relationship
4
- from database import Base
5
-
6
-
7
- class Solicitud(Base):
8
- __tablename__ = "solicitudes"
9
-
10
- id = Column(Integer, primary_key=True, autoincrement=True)
11
- solicitud_hce_id = Column(String(50), unique=True, nullable=False)
12
- # TipoSolicitudEnum: INTERNACION | TRASLADO
13
- tipo = Column(String(20), nullable=False)
14
- # EstadoSolicitudEnum: PENDIENTE | APROBADA | RECHAZADA
15
- estado = Column(String(20), nullable=False, default="PENDIENTE")
16
-
17
- paciente_id = Column(Integer, nullable=False)
18
- medico_solicitante_id = Column(Integer, nullable=False)
19
-
20
- cama_solicitada_id = Column(Integer, ForeignKey("camas.id"), nullable=True)
21
- cama_asignada_id = Column(Integer, ForeignKey("camas.id"), nullable=True)
22
-
23
- # OrigenIngresoEnum: GUARDIA | CIRUGIA_PROGRAMADA
24
- origen = Column(String(30), nullable=True)
25
- turno_id = Column(String(50), nullable=True)
26
- diagnostico_ingreso = Column(String(300), nullable=True)
27
- obra_social_id = Column(String(50), nullable=True)
28
- numero_afiliado = Column(String(50), nullable=True)
29
- # PrioridadSolicitudEnum: BAJA | MEDIA | ALTA | URGENTE
30
- prioridad = Column(String(20), nullable=True)
31
- observaciones = Column(String(500), nullable=True)
32
- hospital_id = Column(String(50), nullable=True)
33
-
34
- # Solo para TRASLADO
35
- cama_origen_id = Column(Integer, nullable=True)
36
- cama_destino_solicitada_id = Column(Integer, nullable=True)
37
- motivo_traslado = Column(String(300), nullable=True)
38
-
39
- # Resolución
40
- # AccionResolucionEnum: APROBAR | APROBAR_CON_CAMBIO | RECHAZAR
41
- accion = Column(String(30), nullable=True)
42
- motivo = Column(String(300), nullable=True)
43
- resuelto_por = Column(Integer, nullable=True)
44
-
45
- timestamp_solicitud = Column(DateTime(timezone=True), nullable=False)
46
- timestamp_resolucion = Column(DateTime(timezone=True), nullable=True)
47
-
48
- cama_solicitada = relationship(
49
- "Cama",
50
- foreign_keys=[cama_solicitada_id],
51
- back_populates="solicitudes_solicitadas",
52
- )
53
- cama_asignada = relationship(
54
- "Cama",
55
- foreign_keys=[cama_asignada_id],
56
- back_populates="solicitudes_asignadas",
57
- )
58
-
59
- @property
60
- def solicitud_id(self) -> str:
61
- return f"SOL-{self.id:05d}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/requirements.txt DELETED
@@ -1,9 +0,0 @@
1
- fastapi==0.115.0
2
- uvicorn[standard]==0.31.0
3
- sqlalchemy==2.0.35
4
- psycopg2-binary==2.9.10
5
- pydantic==2.9.2
6
- pydantic-settings==2.5.2
7
- python-jose[cryptography]==3.3.0
8
- httpx==0.27.2
9
- python-multipart==0.0.12
 
 
 
 
 
 
 
 
 
 
backend/routers/__init__.py DELETED
File without changes
backend/routers/camas.py DELETED
@@ -1,196 +0,0 @@
1
- from datetime import datetime
2
- from typing import Optional
3
- from fastapi import APIRouter, Depends, Query, status
4
- from sqlalchemy.orm import Session
5
-
6
- from database import get_db
7
- from auth.dependencies import get_current_user, require_roles
8
- from schemas.cama import (
9
- CamaCreateRequest,
10
- CamaUpdateRequest,
11
- CamaResponse,
12
- CamaMapaResponse,
13
- AsignacionCamaRequest,
14
- AsignacionCamaResponse,
15
- )
16
- from schemas.reserva import (
17
- ReservaQuirofanoCreateRequest,
18
- ReservaEstadoUpdateRequest,
19
- ReservaQuirofanoResponse,
20
- ReservasListResponse,
21
- )
22
- from services import cama_service
23
-
24
- router = APIRouter(prefix="/camas", tags=["Camas"])
25
-
26
-
27
- # ─── Disponibilidad (debe ir ANTES de /{camaId}) ───────────────────────────
28
-
29
- @router.get("/disponibilidad", summary="Consultar disponibilidad de quirófanos")
30
- def get_disponibilidad(
31
- desde: datetime = Query(...),
32
- hasta: datetime = Query(...),
33
- hospital_id: Optional[str] = Query(None),
34
- db: Session = Depends(get_db),
35
- user: dict = Depends(require_roles("ADMINISTRATIVO", "MEDICO")),
36
- ):
37
- quirofanos = cama_service.get_disponibilidad_quirofanos(db, desde, hasta, hospital_id)
38
- result = []
39
- for q in quirofanos:
40
- reservas_resp = [ReservaQuirofanoResponse.model_validate(r) for r in q["reservas_en_rango"]]
41
- result.append({
42
- "cama_id": q["cama_id"],
43
- "numero": q["numero"],
44
- "piso": q["piso"],
45
- "hospital_id": q["hospital_id"],
46
- "estado": q["estado"],
47
- "reservas_en_rango": [r.model_dump() for r in reservas_resp],
48
- })
49
- return {
50
- "desde": desde.isoformat(),
51
- "hasta": hasta.isoformat(),
52
- "total_quirofanos": len(result),
53
- "quirofanos": result,
54
- }
55
-
56
-
57
- # ─── CRUD Camas ────────────────────────────────────────────────────────────
58
-
59
- @router.get("", response_model=CamaMapaResponse, summary="Obtener mapa completo de camas")
60
- def get_camas(
61
- piso: Optional[int] = Query(None),
62
- sector: Optional[str] = Query(None),
63
- estado: Optional[str] = Query(None),
64
- hospital_id: Optional[str] = Query(None),
65
- db: Session = Depends(get_db),
66
- user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO", "LIMPIEZA")),
67
- ):
68
- camas = cama_service.get_camas(db, user["rol"], piso, sector, estado, hospital_id)
69
- camas_resp = [CamaResponse.model_validate(c) for c in camas]
70
- estados = [c.estado for c in camas]
71
- return CamaMapaResponse(
72
- total=len(camas_resp),
73
- disponibles=estados.count("DISPONIBLE"),
74
- ocupadas=estados.count("OCUPADA"),
75
- en_limpieza=estados.count("EN_LIMPIEZA"),
76
- fuera_de_servicio=estados.count("FUERA_DE_SERVICIO"),
77
- codigo_rojo=estados.count("CODIGO_ROJO"),
78
- camas=camas_resp,
79
- )
80
-
81
-
82
- @router.post("", response_model=CamaResponse, status_code=status.HTTP_201_CREATED, summary="Crear una nueva cama")
83
- def crear_cama(
84
- data: CamaCreateRequest,
85
- db: Session = Depends(get_db),
86
- user: dict = Depends(require_roles("ADMINISTRATIVO")),
87
- ):
88
- cama = cama_service.create_cama(db, data)
89
- return CamaResponse.model_validate(cama)
90
-
91
-
92
- @router.get("/{cama_id}", response_model=CamaResponse, summary="Obtener detalle de una cama")
93
- def get_cama(
94
- cama_id: int,
95
- db: Session = Depends(get_db),
96
- user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
97
- ):
98
- cama = cama_service.get_cama(db, cama_id)
99
- return CamaResponse.model_validate(cama)
100
-
101
-
102
- @router.patch("/{cama_id}", response_model=CamaResponse, summary="Actualizar estado o contraindicaciones de una cama")
103
- def update_cama(
104
- cama_id: int,
105
- data: CamaUpdateRequest,
106
- db: Session = Depends(get_db),
107
- user: dict = Depends(require_roles("ADMINISTRATIVO", "LIMPIEZA")),
108
- ):
109
- cama = cama_service.update_cama(db, cama_id, data, user["rol"])
110
- return CamaResponse.model_validate(cama)
111
-
112
-
113
- @router.delete("/{cama_id}", response_model=CamaResponse, summary="Dar de baja permanente una cama")
114
- def delete_cama(
115
- cama_id: int,
116
- db: Session = Depends(get_db),
117
- user: dict = Depends(require_roles("ADMINISTRATIVO")),
118
- ):
119
- cama = cama_service.delete_cama(db, cama_id)
120
- return CamaResponse.model_validate(cama)
121
-
122
-
123
- # ─── Asignación directa ────────────────────────────────────────────────────
124
-
125
- @router.post("/{cama_id}/asignar", response_model=AsignacionCamaResponse, summary="Asignar o trasladar un paciente")
126
- def asignar_cama(
127
- cama_id: int,
128
- data: AsignacionCamaRequest,
129
- db: Session = Depends(get_db),
130
- user: dict = Depends(require_roles("ADMINISTRATIVO")),
131
- ):
132
- cama = cama_service.asignar_cama(db, cama_id, data.tipo, data.paciente_id, data.cama_origen_id)
133
- return AsignacionCamaResponse(
134
- mensaje=f"Paciente {data.paciente_id} asignado a la cama {cama_id}",
135
- cama_id=cama.id,
136
- paciente_id=data.paciente_id,
137
- tipo=data.tipo,
138
- cama_origen_id=data.cama_origen_id,
139
- timestamp=cama.ultima_actualizacion,
140
- )
141
-
142
-
143
- # ─── Reservas de Quirófano ─────────────────────────────────────────────────
144
-
145
- @router.get("/{cama_id}/reservas", response_model=ReservasListResponse, summary="Listar reservas de un quirófano")
146
- def get_reservas(
147
- cama_id: int,
148
- estado: Optional[str] = Query(None),
149
- prioridad: Optional[str] = Query(None),
150
- fecha_desde: Optional[str] = Query(None),
151
- fecha_hasta: Optional[str] = Query(None),
152
- db: Session = Depends(get_db),
153
- user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
154
- ):
155
- reservas = cama_service.get_reservas(db, cama_id, estado, prioridad, fecha_desde, fecha_hasta)
156
- return ReservasListResponse(
157
- total=len(reservas),
158
- reservas=[ReservaQuirofanoResponse.model_validate(r) for r in reservas],
159
- )
160
-
161
-
162
- @router.post("/{cama_id}/reservas", summary="Crear reserva de quirófano programada")
163
- def crear_reserva(
164
- cama_id: int,
165
- data: ReservaQuirofanoCreateRequest,
166
- db: Session = Depends(get_db),
167
- user: dict = Depends(get_current_user),
168
- ):
169
- reserva, created = cama_service.create_reserva(db, cama_id, data)
170
- resp = ReservaQuirofanoResponse.model_validate(reserva)
171
- http_status = status.HTTP_201_CREATED if created else status.HTTP_200_OK
172
- from fastapi.responses import JSONResponse
173
- return JSONResponse(content=resp.model_dump(mode="json"), status_code=http_status)
174
-
175
-
176
- @router.get("/{cama_id}/reservas/{reserva_id}", response_model=ReservaQuirofanoResponse, summary="Obtener detalle de una reserva")
177
- def get_reserva(
178
- cama_id: int,
179
- reserva_id: int,
180
- db: Session = Depends(get_db),
181
- user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
182
- ):
183
- reserva = cama_service.get_reserva(db, cama_id, reserva_id)
184
- return ReservaQuirofanoResponse.model_validate(reserva)
185
-
186
-
187
- @router.patch("/{cama_id}/reservas/{reserva_id}", response_model=ReservaQuirofanoResponse, summary="Actualizar estado de una reserva")
188
- def update_reserva(
189
- cama_id: int,
190
- reserva_id: int,
191
- data: ReservaEstadoUpdateRequest,
192
- db: Session = Depends(get_db),
193
- user: dict = Depends(require_roles("ADMINISTRATIVO")),
194
- ):
195
- reserva = cama_service.update_reserva_estado(db, cama_id, reserva_id, data)
196
- return ReservaQuirofanoResponse.model_validate(reserva)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/routers/solicitudes.py DELETED
@@ -1,49 +0,0 @@
1
- from typing import Optional
2
- from fastapi import APIRouter, Depends, Query
3
- from sqlalchemy.orm import Session
4
-
5
- from database import get_db
6
- from auth.dependencies import require_roles
7
- from schemas.solicitud import SolicitudResponse, SolicitudesListResponse, SolicitudResolucionRequest
8
- from services import solicitud_service
9
-
10
- router = APIRouter(prefix="/solicitudes", tags=["Solicitudes"])
11
-
12
-
13
- @router.get("", response_model=SolicitudesListResponse, summary="Listar solicitudes")
14
- def get_solicitudes(
15
- estado: Optional[str] = Query(None),
16
- tipo: Optional[str] = Query(None),
17
- hospital_id: Optional[str] = Query(None),
18
- db: Session = Depends(get_db),
19
- user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
20
- ):
21
- solicitudes = solicitud_service.get_solicitudes(db, estado, tipo, hospital_id)
22
- respuestas = [
23
- SolicitudResponse.model_validate({**s.__dict__, "id": s.solicitud_id})
24
- for s in solicitudes
25
- ]
26
- return SolicitudesListResponse(total=len(respuestas), solicitudes=respuestas)
27
-
28
-
29
- @router.get("/{solicitud_id}", response_model=SolicitudResponse, summary="Obtener detalle de una solicitud")
30
- def get_solicitud(
31
- solicitud_id: str,
32
- db: Session = Depends(get_db),
33
- user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
34
- ):
35
- sol = solicitud_service.get_solicitud(db, solicitud_id)
36
- return SolicitudResponse.model_validate({**sol.__dict__, "id": sol.solicitud_id})
37
-
38
-
39
- @router.patch("/{solicitud_id}", response_model=SolicitudResponse, summary="Resolver una solicitud")
40
- def resolver_solicitud(
41
- solicitud_id: str,
42
- data: SolicitudResolucionRequest,
43
- db: Session = Depends(get_db),
44
- user: dict = Depends(require_roles("ADMINISTRATIVO")),
45
- ):
46
- sol = solicitud_service.resolver_solicitud(
47
- db, solicitud_id, data, resuelto_por=int(user["sub"])
48
- )
49
- return SolicitudResponse.model_validate({**sol.__dict__, "id": sol.solicitud_id})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/routers/webhooks.py DELETED
@@ -1,163 +0,0 @@
1
- """
2
- Webhooks entrantes: recibe llamadas de M1 (HCE), M2 (Turnos) y M9 (Monitoreo).
3
- """
4
- from fastapi import APIRouter, Depends, status
5
- from sqlalchemy.orm import Session
6
-
7
- from database import get_db
8
- from auth.dependencies import get_current_user
9
- from schemas.solicitud import (
10
- SolicitudHceWebhook,
11
- AltaMedicaWebhook,
12
- AlertaEmergenciaRequest,
13
- AlertaResueltaRequest,
14
- )
15
- from schemas.reserva import (
16
- CirugiaUrgenteWebhook,
17
- CirugiaUrgenteResponse,
18
- CancelacionQuirofanoRequest,
19
- CancelacionQuirofanoResponse,
20
- ReservaQuirofanoResponse,
21
- ReservaDesplazadaInfo,
22
- )
23
- from services import solicitud_service, cama_service
24
- from fastapi.responses import JSONResponse
25
-
26
- router = APIRouter(tags=["Webhooks Entrantes"])
27
-
28
-
29
- # ─── Desde M1 (HCE) ────────────────────────────────────────────────────────
30
-
31
- @router.post(
32
- "/webhooks/hce/solicitud",
33
- status_code=status.HTTP_200_OK,
34
- summary="[M1] Recibir solicitud (internación o traslado)",
35
- )
36
- def recibir_solicitud(
37
- data: SolicitudHceWebhook,
38
- db: Session = Depends(get_db),
39
- user: dict = Depends(get_current_user),
40
- ):
41
- sol = solicitud_service.recibir_solicitud(db, data)
42
- return {
43
- "mensaje": "Solicitud recibida y pendiente de aprobación",
44
- "solicitud_id": sol.solicitud_id,
45
- "estado": sol.estado,
46
- }
47
-
48
-
49
- @router.post(
50
- "/webhooks/hce/alta-medica",
51
- status_code=status.HTTP_200_OK,
52
- summary="[M1] Recibir alta médica",
53
- )
54
- def recibir_alta_medica(
55
- data: AltaMedicaWebhook,
56
- db: Session = Depends(get_db),
57
- user: dict = Depends(get_current_user),
58
- ):
59
- cama = solicitud_service.procesar_alta_medica(db, data.paciente_id)
60
- return {
61
- "mensaje": "Alta médica procesada. Cama en limpieza.",
62
- "cama_id": cama.id,
63
- "estado_cama": cama.estado,
64
- }
65
-
66
-
67
- @router.post(
68
- "/webhooks/hce/cirugia-urgente",
69
- summary="[M1] Recibir solicitud de cirugía urgente",
70
- )
71
- def recibir_cirugia_urgente(
72
- data: CirugiaUrgenteWebhook,
73
- db: Session = Depends(get_db),
74
- user: dict = Depends(get_current_user),
75
- ):
76
- reserva_urgente, reserva_desplazada = cama_service.crear_reserva_urgente(db, data)
77
-
78
- is_new = reserva_desplazada is not None or True # simplificado
79
- resp_reserva = ReservaQuirofanoResponse.model_validate(reserva_urgente)
80
-
81
- resp_desplazada = None
82
- if reserva_desplazada:
83
- resp_desplazada = ReservaDesplazadaInfo(
84
- reserva_id=reserva_desplazada.id,
85
- cama_id=reserva_desplazada.cama_id,
86
- turno_id=reserva_desplazada.turno_id,
87
- prioridad_original=reserva_desplazada.prioridad,
88
- notificado_a_m2=bool(reserva_desplazada.turno_id),
89
- )
90
-
91
- msg = "Reserva urgente creada exitosamente"
92
- if resp_desplazada:
93
- msg = f"Reserva urgente creada. Se desplazó la reserva {reserva_desplazada.id} (prioridad {reserva_desplazada.prioridad})"
94
-
95
- content = CirugiaUrgenteResponse(
96
- mensaje=msg,
97
- reserva=resp_reserva,
98
- reserva_desplazada=resp_desplazada,
99
- ).model_dump(mode="json")
100
-
101
- return JSONResponse(content=content, status_code=status.HTTP_201_CREATED)
102
-
103
-
104
- # ─── Desde M2 (Turnos) ─────────────────────────────────────────────────────
105
-
106
- @router.post(
107
- "/turnos/{turno_id}/cancelacion-quirofano",
108
- response_model=CancelacionQuirofanoResponse,
109
- summary="[M2] Cancelar reserva de quirófano por turno",
110
- )
111
- def cancelar_reserva_quirofano(
112
- turno_id: str,
113
- data: CancelacionQuirofanoRequest,
114
- db: Session = Depends(get_db),
115
- user: dict = Depends(get_current_user),
116
- ):
117
- reserva = solicitud_service.cancelar_reserva_por_turno(db, turno_id, data.motivo)
118
- return CancelacionQuirofanoResponse(
119
- mensaje="Reserva de quirófano cancelada correctamente",
120
- reserva_id=reserva.id,
121
- turno_id=reserva.turno_id,
122
- cama_id=reserva.cama_id,
123
- estado=reserva.estado,
124
- )
125
-
126
-
127
- # ─── Desde M9 (Monitoreo) ──────────────────────────────────────────────────
128
-
129
- @router.post(
130
- "/webhooks/monitoreo/alerta-emergencia",
131
- status_code=status.HTTP_200_OK,
132
- summary="[M9] Recibir alerta de emergencia",
133
- )
134
- def recibir_alerta_emergencia(
135
- data: AlertaEmergenciaRequest,
136
- db: Session = Depends(get_db),
137
- user: dict = Depends(get_current_user),
138
- ):
139
- cama = solicitud_service.procesar_alerta_emergencia(db, data.paciente_id)
140
- return {
141
- "mensaje": f"Alerta registrada. Cama {cama.id} en CODIGO_ROJO.",
142
- "cama_id": cama.id,
143
- "sector": cama.sector,
144
- }
145
-
146
-
147
- @router.post(
148
- "/webhooks/monitoreo/alerta-resuelta",
149
- status_code=status.HTTP_200_OK,
150
- summary="[M9] Recibir alerta resuelta",
151
- )
152
- def recibir_alerta_resuelta(
153
- data: AlertaResueltaRequest,
154
- db: Session = Depends(get_db),
155
- user: dict = Depends(get_current_user),
156
- ):
157
- cama = solicitud_service.procesar_alerta_resuelta(db, data.paciente_id)
158
- return {
159
- "mensaje": f"Alerta resuelta. Cama {cama.id} volvió a estado OCUPADA.",
160
- "cama_id": cama.id,
161
- "estado_anterior": "CODIGO_ROJO",
162
- "estado_actual": cama.estado,
163
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/schemas/__init__.py DELETED
File without changes
backend/schemas/cama.py DELETED
@@ -1,59 +0,0 @@
1
- from __future__ import annotations
2
- from datetime import datetime
3
- from typing import Optional
4
- from pydantic import BaseModel, ConfigDict
5
- from schemas.enums import EstadoCamaEnum, SectorEnum, TipoCamaEnum
6
-
7
-
8
- class CamaCreateRequest(BaseModel):
9
- numero: str
10
- piso: int
11
- sector: SectorEnum
12
- tipo: TipoCamaEnum
13
- hospital_id: str
14
- contraindicaciones_incompatibles: list[str] = []
15
-
16
-
17
- class CamaUpdateRequest(BaseModel):
18
- estado: Optional[EstadoCamaEnum] = None
19
- contraindicaciones_incompatibles: Optional[list[str]] = None
20
-
21
-
22
- class CamaResponse(BaseModel):
23
- model_config = ConfigDict(from_attributes=True)
24
-
25
- id: int
26
- numero: str
27
- piso: int
28
- sector: str
29
- tipo: str
30
- estado: str
31
- paciente_id: Optional[int] = None
32
- hospital_id: str
33
- contraindicaciones_incompatibles: list[str]
34
- ultima_actualizacion: datetime
35
-
36
-
37
- class CamaMapaResponse(BaseModel):
38
- total: int
39
- disponibles: int
40
- ocupadas: int
41
- en_limpieza: int
42
- fuera_de_servicio: int
43
- codigo_rojo: int
44
- camas: list[CamaResponse]
45
-
46
-
47
- class AsignacionCamaRequest(BaseModel):
48
- tipo: str # INGRESO | TRASLADO
49
- paciente_id: int
50
- cama_origen_id: Optional[int] = None
51
-
52
-
53
- class AsignacionCamaResponse(BaseModel):
54
- mensaje: str
55
- cama_id: int
56
- paciente_id: int
57
- tipo: str
58
- cama_origen_id: Optional[int] = None
59
- timestamp: datetime
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/schemas/enums.py DELETED
@@ -1,89 +0,0 @@
1
- from enum import Enum
2
-
3
-
4
- class EstadoCamaEnum(str, Enum):
5
- DISPONIBLE = "DISPONIBLE"
6
- OCUPADA = "OCUPADA"
7
- EN_LIMPIEZA = "EN_LIMPIEZA"
8
- FUERA_DE_SERVICIO = "FUERA_DE_SERVICIO"
9
- BAJA_PERMANENTE = "BAJA_PERMANENTE"
10
- CODIGO_ROJO = "CODIGO_ROJO"
11
-
12
-
13
- class SectorEnum(str, Enum):
14
- UTI = "UTI"
15
- SALA_COMUN = "SALA_COMUN"
16
- QUIROFANO = "QUIROFANO"
17
- GUARDIA = "GUARDIA"
18
- NEONATOLOGIA = "NEONATOLOGIA"
19
-
20
-
21
- class TipoCamaEnum(str, Enum):
22
- ESTANDAR = "ESTANDAR"
23
- PEDIATRICA = "PEDIATRICA"
24
- AISLAMIENTO = "AISLAMIENTO"
25
- CRITICA = "CRITICA"
26
- CIRUGIA = "CIRUGIA"
27
-
28
-
29
- class TipoSolicitudEnum(str, Enum):
30
- INTERNACION = "INTERNACION"
31
- TRASLADO = "TRASLADO"
32
-
33
-
34
- class EstadoSolicitudEnum(str, Enum):
35
- PENDIENTE = "PENDIENTE"
36
- APROBADA = "APROBADA"
37
- RECHAZADA = "RECHAZADA"
38
-
39
-
40
- class AccionResolucionEnum(str, Enum):
41
- APROBAR = "APROBAR"
42
- APROBAR_CON_CAMBIO = "APROBAR_CON_CAMBIO"
43
- RECHAZAR = "RECHAZAR"
44
-
45
-
46
- class PrioridadSolicitudEnum(str, Enum):
47
- BAJA = "BAJA"
48
- MEDIA = "MEDIA"
49
- ALTA = "ALTA"
50
- URGENTE = "URGENTE"
51
-
52
-
53
- class OrigenIngresoEnum(str, Enum):
54
- GUARDIA = "GUARDIA"
55
- CIRUGIA_PROGRAMADA = "CIRUGIA_PROGRAMADA"
56
-
57
-
58
- class TipoAltaEnum(str, Enum):
59
- ALTA_MEDICA = "ALTA_MEDICA"
60
- ALTA_VOLUNTARIA = "ALTA_VOLUNTARIA"
61
- TRASLADO_EXTERNO = "TRASLADO_EXTERNO"
62
- DEFUNCION = "DEFUNCION"
63
-
64
-
65
- class PrioridadQuirofanoEnum(str, Enum):
66
- MUY_BAJA = "MUY_BAJA"
67
- BAJA = "BAJA"
68
- MEDIA = "MEDIA"
69
- ALTA = "ALTA"
70
- MUY_ALTA = "MUY_ALTA"
71
- URGENTE = "URGENTE"
72
-
73
-
74
- class OrigenReservaEnum(str, Enum):
75
- PROGRAMADA = "PROGRAMADA"
76
- EMERGENCIA = "EMERGENCIA"
77
-
78
-
79
- class EstadoReservaEnum(str, Enum):
80
- RESERVADA = "RESERVADA"
81
- EN_CURSO = "EN_CURSO"
82
- COMPLETADA = "COMPLETADA"
83
- CANCELADA = "CANCELADA"
84
-
85
-
86
- class RolEnum(str, Enum):
87
- MEDICO = "MEDICO"
88
- ADMINISTRATIVO = "ADMINISTRATIVO"
89
- LIMPIEZA = "LIMPIEZA"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/schemas/reserva.py DELETED
@@ -1,85 +0,0 @@
1
- from __future__ import annotations
2
- from datetime import datetime
3
- from typing import Optional
4
- from pydantic import BaseModel, ConfigDict
5
- from schemas.enums import PrioridadQuirofanoEnum, OrigenReservaEnum, EstadoReservaEnum
6
-
7
-
8
- class ReservaQuirofanoCreateRequest(BaseModel):
9
- turno_id: str
10
- paciente_id: int
11
- medico_cirujano_id: int
12
- fecha_hora_inicio: datetime
13
- fecha_hora_fin_estimada: datetime
14
- prioridad: PrioridadQuirofanoEnum
15
- observaciones: Optional[str] = None
16
-
17
-
18
- class ReservaEstadoUpdateRequest(BaseModel):
19
- estado: EstadoReservaEnum
20
- observaciones: Optional[str] = None
21
-
22
-
23
- class ReservaQuirofanoResponse(BaseModel):
24
- model_config = ConfigDict(from_attributes=True)
25
-
26
- id: int
27
- cama_id: int
28
- turno_id: Optional[str] = None
29
- origen: str
30
- estado: str
31
- prioridad: str
32
- paciente_id: int
33
- medico_cirujano_id: int
34
- fecha_hora_inicio: datetime
35
- fecha_hora_fin_estimada: datetime
36
- observaciones: Optional[str] = None
37
- desplazada_por_reserva_id: Optional[int] = None
38
- created_at: datetime
39
-
40
-
41
- class ReservasListResponse(BaseModel):
42
- total: int
43
- reservas: list[ReservaQuirofanoResponse]
44
-
45
-
46
- # --- Webhooks quirofano ---
47
-
48
- class CirugiaUrgenteWebhook(BaseModel):
49
- solicitud_urgencia_hce_id: str
50
- paciente_id: int
51
- medico_cirujano_id: int
52
- medico_solicitante_id: int
53
- fecha_hora_inicio: datetime
54
- fecha_hora_fin_estimada: datetime
55
- diagnostico: Optional[str] = None
56
- hospital_id: Optional[str] = None
57
- timestamp: datetime
58
-
59
-
60
- class CancelacionQuirofanoRequest(BaseModel):
61
- motivo: str
62
- tipo_cancelacion: Optional[str] = None
63
- timestamp: datetime
64
-
65
-
66
- class CancelacionQuirofanoResponse(BaseModel):
67
- mensaje: str
68
- reserva_id: int
69
- turno_id: Optional[str] = None
70
- cama_id: int
71
- estado: str
72
-
73
-
74
- class ReservaDesplazadaInfo(BaseModel):
75
- reserva_id: int
76
- cama_id: int
77
- turno_id: Optional[str] = None
78
- prioridad_original: str
79
- notificado_a_m2: bool
80
-
81
-
82
- class CirugiaUrgenteResponse(BaseModel):
83
- mensaje: str
84
- reserva: ReservaQuirofanoResponse
85
- reserva_desplazada: Optional[ReservaDesplazadaInfo] = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/schemas/solicitud.py DELETED
@@ -1,102 +0,0 @@
1
- from __future__ import annotations
2
- from datetime import datetime
3
- from typing import Optional
4
- from pydantic import BaseModel, ConfigDict, field_validator
5
- from schemas.enums import (
6
- TipoSolicitudEnum,
7
- EstadoSolicitudEnum,
8
- AccionResolucionEnum,
9
- PrioridadSolicitudEnum,
10
- OrigenIngresoEnum,
11
- TipoAltaEnum,
12
- )
13
-
14
-
15
- class SolicitudResponse(BaseModel):
16
- model_config = ConfigDict(from_attributes=True)
17
-
18
- id: str # SOL-XXXXX
19
- solicitud_hce_id: str
20
- tipo: str
21
- estado: str
22
- paciente_id: int
23
- medico_solicitante_id: int
24
- cama_solicitada_id: Optional[int] = None
25
- cama_asignada_id: Optional[int] = None
26
- origen: Optional[str] = None
27
- turno_id: Optional[str] = None
28
- diagnostico_ingreso: Optional[str] = None
29
- obra_social_id: Optional[str] = None
30
- numero_afiliado: Optional[str] = None
31
- prioridad: Optional[str] = None
32
- cama_origen_id: Optional[int] = None
33
- cama_destino_solicitada_id: Optional[int] = None
34
- motivo_traslado: Optional[str] = None
35
- accion: Optional[str] = None
36
- motivo: Optional[str] = None
37
- resuelto_por: Optional[int] = None
38
- observaciones: Optional[str] = None
39
- timestamp_solicitud: datetime
40
- timestamp_resolucion: Optional[datetime] = None
41
-
42
- @field_validator("id", mode="before")
43
- @classmethod
44
- def format_id(cls, v):
45
- # Cuando viene del ORM el id es entero; formatearlo
46
- if isinstance(v, int):
47
- return f"SOL-{v:05d}"
48
- return v
49
-
50
-
51
- class SolicitudesListResponse(BaseModel):
52
- total: int
53
- solicitudes: list[SolicitudResponse]
54
-
55
-
56
- class SolicitudResolucionRequest(BaseModel):
57
- accion: AccionResolucionEnum
58
- cama_asignada_id: Optional[int] = None
59
- motivo: Optional[str] = None
60
-
61
-
62
- # --- Webhooks entrantes ---
63
-
64
- class SolicitudHceWebhook(BaseModel):
65
- tipo: TipoSolicitudEnum
66
- solicitud_hce_id: str
67
- paciente_id: int
68
- medico_solicitante_id: int
69
- # INTERNACION
70
- cama_solicitada_id: Optional[int] = None
71
- origen: Optional[OrigenIngresoEnum] = None
72
- turno_id: Optional[str] = None
73
- diagnostico_ingreso: Optional[str] = None
74
- obra_social_id: Optional[str] = None
75
- numero_afiliado: Optional[str] = None
76
- prioridad: Optional[PrioridadSolicitudEnum] = None
77
- observaciones: Optional[str] = None
78
- hospital_id: Optional[str] = None
79
- # TRASLADO
80
- cama_origen_id: Optional[int] = None
81
- cama_destino_solicitada_id: Optional[int] = None
82
- motivo_traslado: Optional[str] = None
83
- timestamp: datetime
84
-
85
-
86
- class AltaMedicaWebhook(BaseModel):
87
- paciente_id: int
88
- medico_firmante_id: int
89
- tipo_alta: TipoAltaEnum
90
- timestamp: datetime
91
-
92
-
93
- class AlertaEmergenciaRequest(BaseModel):
94
- paciente_id: int
95
- observaciones: Optional[str] = None
96
- timestamp: datetime
97
-
98
-
99
- class AlertaResueltaRequest(BaseModel):
100
- paciente_id: int
101
- motivo_resolucion: Optional[str] = None
102
- timestamp: datetime
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/services/__init__.py DELETED
File without changes
backend/services/cama_service.py DELETED
@@ -1,500 +0,0 @@
1
- """
2
- Lógica de negocio para Camas y Reservas de Quirófano.
3
- """
4
- from __future__ import annotations
5
- from datetime import datetime, timezone
6
- from fastapi import HTTPException, status
7
- from sqlalchemy.orm import Session
8
- from sqlalchemy import and_, or_
9
-
10
- from models.cama import Cama
11
- from models.reserva import ReservaQuirofano
12
- from schemas.cama import CamaCreateRequest, CamaUpdateRequest
13
- from schemas.reserva import ReservaQuirofanoCreateRequest, ReservaEstadoUpdateRequest
14
- from services import external_client
15
-
16
-
17
- # ─── helpers ───────────────────────────────────────────────────────────────
18
-
19
- _ERR_CAMA_NOT_FOUND = {"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "Cama no encontrada"}
20
- _ERR_RESERVA_NOT_FOUND = {"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "Reserva no encontrada"}
21
-
22
-
23
- def _get_cama_or_404(db: Session, cama_id: int) -> Cama:
24
- cama = db.query(Cama).filter(Cama.id == cama_id).first()
25
- if not cama:
26
- raise HTTPException(status_code=404, detail=_ERR_CAMA_NOT_FOUND)
27
- return cama
28
-
29
-
30
- PRIORIDAD_ORDER = {
31
- "MUY_BAJA": 0, "BAJA": 1, "MEDIA": 2, "ALTA": 3, "MUY_ALTA": 4, "URGENTE": 5
32
- }
33
-
34
- # ─── Camas ─────────────────────────────────────────────────────────────────
35
-
36
- def get_camas(
37
- db: Session,
38
- rol: str,
39
- piso: int | None = None,
40
- sector: str | None = None,
41
- estado: str | None = None,
42
- hospital_id: str | None = None,
43
- ) -> list[Cama]:
44
- q = db.query(Cama).filter(Cama.estado != "BAJA_PERMANENTE")
45
-
46
- if rol == "LIMPIEZA":
47
- q = q.filter(Cama.estado == "EN_LIMPIEZA")
48
- else:
49
- if estado:
50
- q = q.filter(Cama.estado == estado)
51
- if piso is not None:
52
- q = q.filter(Cama.piso == piso)
53
- if sector:
54
- q = q.filter(Cama.sector == sector)
55
- if hospital_id:
56
- q = q.filter(Cama.hospital_id == hospital_id)
57
-
58
- return q.all()
59
-
60
-
61
- def create_cama(db: Session, data: CamaCreateRequest) -> Cama:
62
- cama = Cama(
63
- numero=data.numero,
64
- piso=data.piso,
65
- sector=data.sector.value,
66
- tipo=data.tipo.value,
67
- hospital_id=data.hospital_id,
68
- estado="DISPONIBLE",
69
- contraindicaciones_incompatibles=data.contraindicaciones_incompatibles,
70
- ultima_actualizacion=datetime.now(timezone.utc),
71
- )
72
- db.add(cama)
73
- db.commit()
74
- db.refresh(cama)
75
- return cama
76
-
77
-
78
- def get_cama(db: Session, cama_id: int) -> Cama:
79
- return _get_cama_or_404(db, cama_id)
80
-
81
-
82
- def update_cama(db: Session, cama_id: int, data: CamaUpdateRequest, rol: str) -> Cama:
83
- cama = _get_cama_or_404(db, cama_id)
84
-
85
- if data.estado is not None:
86
- nuevo_estado = data.estado.value
87
-
88
- # Restricciones de estado
89
- if nuevo_estado in ("OCUPADA", "CODIGO_ROJO"):
90
- raise HTTPException(
91
- status_code=409,
92
- detail={
93
- "codigo": "CONFLICTO_ESTADO",
94
- "mensaje": f"El estado {nuevo_estado} solo se asigna automáticamente",
95
- },
96
- )
97
- if rol == "LIMPIEZA" and not (
98
- cama.estado == "EN_LIMPIEZA" and nuevo_estado == "DISPONIBLE"
99
- ):
100
- raise HTTPException(
101
- status_code=403,
102
- detail={
103
- "codigo": "NO_AUTORIZADO",
104
- "mensaje": "El rol LIMPIEZA solo puede transicionar de EN_LIMPIEZA a DISPONIBLE",
105
- },
106
- )
107
-
108
- estado_anterior = cama.estado
109
- cama.estado = nuevo_estado
110
-
111
- # Disparar CAMA_LISTA cuando limpieza completa (post alta médica)
112
- if (
113
- estado_anterior == "EN_LIMPIEZA"
114
- and nuevo_estado == "DISPONIBLE"
115
- and cama.ultimo_movimiento_tipo == "ALTA"
116
- ):
117
- external_client.notify_cama_lista(
118
- cama_id=cama.id,
119
- paciente_id=cama.paciente_id or 0,
120
- )
121
- cama.paciente_id = None
122
- cama.ultimo_movimiento_tipo = None
123
- elif nuevo_estado == "DISPONIBLE" and cama.paciente_id:
124
- # Traslado completado → limpiar paciente
125
- cama.paciente_id = None
126
- cama.ultimo_movimiento_tipo = None
127
-
128
- if data.contraindicaciones_incompatibles is not None:
129
- cama.contraindicaciones_incompatibles = data.contraindicaciones_incompatibles
130
-
131
- cama.ultima_actualizacion = datetime.now(timezone.utc)
132
- db.commit()
133
- db.refresh(cama)
134
- return cama
135
-
136
-
137
- def delete_cama(db: Session, cama_id: int) -> Cama:
138
- cama = _get_cama_or_404(db, cama_id)
139
- if cama.estado in ("OCUPADA", "EN_LIMPIEZA", "CODIGO_ROJO"):
140
- raise HTTPException(
141
- status_code=409,
142
- detail={
143
- "codigo": "CAMA_EN_USO",
144
- "mensaje": "No se puede dar de baja una cama en uso",
145
- "detalle": f"La cama {cama_id} está en estado {cama.estado}",
146
- },
147
- )
148
- if cama.estado == "BAJA_PERMANENTE":
149
- raise HTTPException(
150
- status_code=409,
151
- detail={"codigo": "CONFLICTO_ESTADO", "mensaje": "La cama ya está dada de baja"},
152
- )
153
- cama.estado = "BAJA_PERMANENTE"
154
- cama.ultima_actualizacion = datetime.now(timezone.utc)
155
- db.commit()
156
- db.refresh(cama)
157
- return cama
158
-
159
-
160
- def asignar_cama(db: Session, cama_id: int, tipo: str, paciente_id: int, cama_origen_id: int | None) -> Cama:
161
- cama_destino = _get_cama_or_404(db, cama_id)
162
-
163
- if cama_destino.estado != "DISPONIBLE":
164
- raise HTTPException(
165
- status_code=409,
166
- detail={
167
- "codigo": "CAMA_NO_DISPONIBLE",
168
- "mensaje": "La cama destino no está disponible",
169
- "detalle": f"La cama {cama_id} está en estado {cama_destino.estado}",
170
- },
171
- )
172
-
173
- # Verificar contraindicaciones (consulta informativa a M1)
174
- contraindicaciones_paciente = external_client.get_patient_contraindicaciones(paciente_id)
175
- incompatibles = cama_destino.contraindicaciones_incompatibles or []
176
- conflicto = set(contraindicaciones_paciente) & set(incompatibles)
177
- if conflicto:
178
- raise HTTPException(
179
- status_code=422,
180
- detail={
181
- "codigo": "CONTRAINDICACION_DETECTADA",
182
- "mensaje": "El paciente tiene contraindicaciones incompatibles con la cama destino",
183
- "detalle": f"Conflicto: {', '.join(conflicto)}",
184
- },
185
- )
186
-
187
- if tipo == "TRASLADO":
188
- if not cama_origen_id:
189
- raise HTTPException(status_code=400, detail={"codigo": "ERROR_VALIDACION", "mensaje": "cama_origen_id es requerido para TRASLADO"})
190
- cama_origen = _get_cama_or_404(db, cama_origen_id)
191
- cama_origen.estado = "EN_LIMPIEZA"
192
- cama_origen.ultimo_movimiento_tipo = "TRASLADO"
193
- cama_origen.ultima_actualizacion = datetime.now(timezone.utc)
194
- external_client.notify_movimiento("TRASLADO", paciente_id, cama_id, cama_origen_id)
195
- else:
196
- # INGRESO
197
- external_client.notify_movimiento("INGRESO", paciente_id, cama_id)
198
- external_client.notify_alta_monitoreo(paciente_id)
199
-
200
- cama_destino.estado = "OCUPADA"
201
- cama_destino.paciente_id = paciente_id
202
- cama_destino.ultima_actualizacion = datetime.now(timezone.utc)
203
- db.commit()
204
- db.refresh(cama_destino)
205
- return cama_destino
206
-
207
-
208
- # ─── Reservas de Quirófano ─────────────────────────────────────────────────
209
-
210
- def _is_quirofano(cama: Cama) -> bool:
211
- return cama.sector == "QUIROFANO" and cama.tipo == "CIRUGIA"
212
-
213
-
214
- def _reservas_superpuestas(db: Session, cama_id: int, inicio: datetime, fin: datetime, exclude_id: int | None = None):
215
- q = db.query(ReservaQuirofano).filter(
216
- ReservaQuirofano.cama_id == cama_id,
217
- ReservaQuirofano.estado.in_(["RESERVADA", "EN_CURSO"]),
218
- ReservaQuirofano.fecha_hora_inicio < fin,
219
- ReservaQuirofano.fecha_hora_fin_estimada > inicio,
220
- )
221
- if exclude_id:
222
- q = q.filter(ReservaQuirofano.id != exclude_id)
223
- return q.all()
224
-
225
-
226
- def get_reservas(
227
- db: Session,
228
- cama_id: int,
229
- estado: str | None = None,
230
- prioridad: str | None = None,
231
- fecha_desde: str | None = None,
232
- fecha_hasta: str | None = None,
233
- ) -> list[ReservaQuirofano]:
234
- cama = _get_cama_or_404(db, cama_id)
235
- if not _is_quirofano(cama):
236
- raise HTTPException(
237
- status_code=409,
238
- detail={"codigo": "CAMA_NO_ES_QUIROFANO", "mensaje": "La cama no es un quirófano"},
239
- )
240
- q = db.query(ReservaQuirofano).filter(ReservaQuirofano.cama_id == cama_id)
241
- if estado:
242
- q = q.filter(ReservaQuirofano.estado == estado)
243
- else:
244
- q = q.filter(ReservaQuirofano.estado.in_(["RESERVADA", "EN_CURSO"]))
245
- if prioridad:
246
- q = q.filter(ReservaQuirofano.prioridad == prioridad)
247
- if fecha_desde:
248
- q = q.filter(ReservaQuirofano.fecha_hora_inicio >= fecha_desde)
249
- if fecha_hasta:
250
- q = q.filter(ReservaQuirofano.fecha_hora_fin_estimada <= fecha_hasta)
251
- return q.all()
252
-
253
-
254
- def create_reserva(db: Session, cama_id: int, data: ReservaQuirofanoCreateRequest) -> tuple[ReservaQuirofano, bool]:
255
- """Retorna (reserva, created). created=False si ya existía (idempotencia)."""
256
- cama = _get_cama_or_404(db, cama_id)
257
- if not _is_quirofano(cama):
258
- raise HTTPException(
259
- status_code=409,
260
- detail={"codigo": "CAMA_NO_ES_QUIROFANO", "mensaje": "La cama no es un quirófano"},
261
- )
262
- if cama.estado in ("FUERA_DE_SERVICIO", "BAJA_PERMANENTE"):
263
- raise HTTPException(
264
- status_code=409,
265
- detail={"codigo": "CAMA_NO_DISPONIBLE", "mensaje": f"La cama está {cama.estado}"},
266
- )
267
- if data.prioridad.value == "URGENTE":
268
- raise HTTPException(
269
- status_code=422,
270
- detail={
271
- "codigo": "PRIORIDAD_URGENTE_NO_PERMITIDA",
272
- "mensaje": "La prioridad URGENTE no puede asignarse desde este endpoint",
273
- },
274
- )
275
- # Idempotencia
276
- existing = db.query(ReservaQuirofano).filter(
277
- ReservaQuirofano.turno_id == data.turno_id,
278
- ReservaQuirofano.estado.in_(["RESERVADA", "EN_CURSO"]),
279
- ).first()
280
- if existing:
281
- return existing, False
282
-
283
- # Verificar superposición
284
- solapadas = _reservas_superpuestas(db, cama_id, data.fecha_hora_inicio, data.fecha_hora_fin_estimada)
285
- if solapadas:
286
- raise HTTPException(
287
- status_code=409,
288
- detail={
289
- "codigo": "RESERVA_SUPERPUESTA",
290
- "mensaje": "El quirófano ya tiene una reserva activa en ese horario",
291
- },
292
- )
293
-
294
- reserva = ReservaQuirofano(
295
- cama_id=cama_id,
296
- turno_id=data.turno_id,
297
- origen="PROGRAMADA",
298
- estado="RESERVADA",
299
- prioridad=data.prioridad.value,
300
- paciente_id=data.paciente_id,
301
- medico_cirujano_id=data.medico_cirujano_id,
302
- fecha_hora_inicio=data.fecha_hora_inicio,
303
- fecha_hora_fin_estimada=data.fecha_hora_fin_estimada,
304
- observaciones=data.observaciones,
305
- created_at=datetime.now(timezone.utc),
306
- )
307
- db.add(reserva)
308
- db.commit()
309
- db.refresh(reserva)
310
- return reserva, True
311
-
312
-
313
- def get_reserva(db: Session, cama_id: int, reserva_id: int) -> ReservaQuirofano:
314
- _get_cama_or_404(db, cama_id)
315
- r = db.query(ReservaQuirofano).filter(
316
- ReservaQuirofano.id == reserva_id,
317
- ReservaQuirofano.cama_id == cama_id,
318
- ).first()
319
- if not r:
320
- raise HTTPException(status_code=404, detail=_ERR_RESERVA_NOT_FOUND)
321
- return r
322
-
323
-
324
- def update_reserva_estado(db: Session, cama_id: int, reserva_id: int, data: ReservaEstadoUpdateRequest) -> ReservaQuirofano:
325
- reserva = get_reserva(db, cama_id, reserva_id)
326
- cama = _get_cama_or_404(db, cama_id)
327
-
328
- TRANSICIONES_VALIDAS = {
329
- "RESERVADA": ["EN_CURSO", "CANCELADA"],
330
- "EN_CURSO": ["COMPLETADA"],
331
- }
332
- permitidas = TRANSICIONES_VALIDAS.get(reserva.estado, [])
333
- nuevo = data.estado.value
334
- if nuevo not in permitidas:
335
- raise HTTPException(
336
- status_code=409,
337
- detail={
338
- "codigo": "CONFLICTO_ESTADO",
339
- "mensaje": f"Transición inválida: {reserva.estado} → {nuevo}",
340
- },
341
- )
342
-
343
- reserva.estado = nuevo
344
- if data.observaciones:
345
- reserva.observaciones = data.observaciones
346
-
347
- # Efectos en la cama
348
- if nuevo == "EN_CURSO":
349
- cama.estado = "OCUPADA"
350
- cama.paciente_id = reserva.paciente_id
351
- elif nuevo == "COMPLETADA":
352
- cama.estado = "EN_LIMPIEZA"
353
- cama.ultimo_movimiento_tipo = "ALTA"
354
-
355
- cama.ultima_actualizacion = datetime.now(timezone.utc)
356
- db.commit()
357
- db.refresh(reserva)
358
- return reserva
359
-
360
-
361
- def get_disponibilidad_quirofanos(
362
- db: Session, desde: datetime, hasta: datetime, hospital_id: str | None = None
363
- ) -> list[dict]:
364
- q = db.query(Cama).filter(
365
- Cama.sector == "QUIROFANO",
366
- Cama.tipo == "CIRUGIA",
367
- Cama.estado.notin_(["FUERA_DE_SERVICIO", "BAJA_PERMANENTE"]),
368
- )
369
- if hospital_id:
370
- q = q.filter(Cama.hospital_id == hospital_id)
371
- quirofanos = q.all()
372
-
373
- result = []
374
- for q_cama in quirofanos:
375
- reservas_en_rango = _reservas_superpuestas(db, q_cama.id, desde, hasta)
376
- result.append({
377
- "cama_id": q_cama.id,
378
- "numero": q_cama.numero,
379
- "piso": q_cama.piso,
380
- "hospital_id": q_cama.hospital_id,
381
- "estado": q_cama.estado,
382
- "reservas_en_rango": reservas_en_rango,
383
- })
384
- return result
385
-
386
-
387
- # ─── Cirugía urgente (desde webhook M1) ────────────────────────────────────
388
-
389
- def crear_reserva_urgente(db: Session, data) -> tuple[ReservaQuirofano, ReservaQuirofano | None]:
390
- """
391
- Crea una reserva urgente (EMERGENCIA, prioridad URGENTE).
392
- Desplaza la de menor prioridad si todos los quirófanos están ocupados.
393
- Retorna (nueva_reserva, reserva_desplazada_o_None).
394
- """
395
- from schemas.reserva import CirugiaUrgenteWebhook
396
-
397
- # Idempotencia
398
- existing = db.query(ReservaQuirofano).filter(
399
- ReservaQuirofano.solicitud_urgencia_hce_id == data.solicitud_urgencia_hce_id
400
- ).first()
401
- if existing:
402
- return existing, None
403
-
404
- # Buscar quirófanos operativos
405
- quirofanos = db.query(Cama).filter(
406
- Cama.sector == "QUIROFANO",
407
- Cama.tipo == "CIRUGIA",
408
- Cama.estado.notin_(["FUERA_DE_SERVICIO", "BAJA_PERMANENTE"]),
409
- ).all()
410
-
411
- if not quirofanos:
412
- raise HTTPException(
413
- status_code=409,
414
- detail={"codigo": "SIN_QUIROFANO_DISPONIBLE", "mensaje": "No hay quirófanos en el sistema"},
415
- )
416
-
417
- # Buscar quirófano libre
418
- cama_libre = None
419
- for q in quirofanos:
420
- solapadas = _reservas_superpuestas(db, q.id, data.fecha_hora_inicio, data.fecha_hora_fin_estimada)
421
- if not solapadas:
422
- cama_libre = q
423
- break
424
-
425
- if cama_libre:
426
- reserva = _make_urgent_reserva(db, cama_libre.id, data)
427
- return reserva, None
428
-
429
- # Todos ocupados → buscar candidata a desplazar
430
- candidata = _find_desplazable(db, quirofanos, data.fecha_hora_inicio, data.fecha_hora_fin_estimada)
431
- if not candidata:
432
- raise HTTPException(
433
- status_code=409,
434
- detail={
435
- "codigo": "SIN_QUIROFANO_DISPONIBLE",
436
- "mensaje": "No hay quirófanos disponibles y no existe reserva desplazable",
437
- },
438
- )
439
-
440
- # Cancelar la candidata
441
- candidata_cama_id = candidata.cama_id
442
- candidata.estado = "CANCELADA"
443
- candidata.desplazada_por_reserva_id = None # se actualiza después
444
-
445
- # Notificar a M2 si tenía turno
446
- notificado_m2 = False
447
- if candidata.turno_id:
448
- notificado_m2 = external_client.notify_resultado_quirofano(
449
- turno_id=candidata.turno_id,
450
- reserva_id=candidata.id,
451
- cama_id=candidata_cama_id,
452
- reserva_urgente_id=0, # se actualiza luego
453
- motivo=getattr(data, "diagnostico", None),
454
- )
455
-
456
- # Crear la urgente
457
- reserva_urgente = _make_urgent_reserva(db, candidata_cama_id, data)
458
- candidata.desplazada_por_reserva_id = reserva_urgente.id
459
- db.commit()
460
- db.refresh(reserva_urgente)
461
- db.refresh(candidata)
462
-
463
- return reserva_urgente, candidata
464
-
465
-
466
- def _make_urgent_reserva(db: Session, cama_id: int, data) -> ReservaQuirofano:
467
- reserva = ReservaQuirofano(
468
- cama_id=cama_id,
469
- solicitud_urgencia_hce_id=data.solicitud_urgencia_hce_id,
470
- origen="EMERGENCIA",
471
- estado="RESERVADA",
472
- prioridad="URGENTE",
473
- paciente_id=data.paciente_id,
474
- medico_cirujano_id=data.medico_cirujano_id,
475
- fecha_hora_inicio=data.fecha_hora_inicio,
476
- fecha_hora_fin_estimada=data.fecha_hora_fin_estimada,
477
- observaciones=f"Cirugía urgente solicitada por HCE ({data.solicitud_urgencia_hce_id})",
478
- created_at=datetime.now(timezone.utc),
479
- )
480
- db.add(reserva)
481
- db.flush()
482
- return reserva
483
-
484
-
485
- def _find_desplazable(db: Session, quirofanos: list[Cama], inicio: datetime, fin: datetime):
486
- """Encuentra la reserva de menor prioridad y más cercana a desplazar."""
487
- candidata = None
488
- for q in quirofanos:
489
- solapadas = _reservas_superpuestas(db, q.id, inicio, fin)
490
- for r in solapadas:
491
- if r.prioridad == "URGENTE":
492
- continue
493
- if candidata is None:
494
- candidata = r
495
- else:
496
- p_r = PRIORIDAD_ORDER.get(r.prioridad, 99)
497
- p_c = PRIORIDAD_ORDER.get(candidata.prioridad, 99)
498
- if p_r < p_c or (p_r == p_c and r.fecha_hora_inicio < candidata.fecha_hora_inicio):
499
- candidata = r
500
- return candidata
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/services/external_client.py DELETED
@@ -1,162 +0,0 @@
1
- """
2
- Cliente HTTP para llamadas a módulos externos.
3
- Si MOCK_EXTERNAL_SERVICES=true, devuelve respuestas mockeadas
4
- en lugar de hacer llamadas reales.
5
- """
6
- import httpx
7
- from config import settings
8
-
9
-
10
- # ─── helpers ───────────────────────────────────────────────────────────────
11
-
12
- def _headers(token: str | None = None) -> dict:
13
- h = {"Content-Type": "application/json"}
14
- if token:
15
- h["Authorization"] = f"Bearer {token}"
16
- return h
17
-
18
-
19
- def _post(url: str, payload: dict, token: str | None = None) -> dict | None:
20
- try:
21
- r = httpx.post(url, json=payload, headers=_headers(token), timeout=5.0)
22
- r.raise_for_status()
23
- return r.json()
24
- except Exception:
25
- return None
26
-
27
-
28
- def _get(url: str, token: str | None = None) -> dict | None:
29
- try:
30
- r = httpx.get(url, headers=_headers(token), timeout=5.0)
31
- r.raise_for_status()
32
- return r.json()
33
- except Exception:
34
- return None
35
-
36
-
37
- # ─── M10 Core ──────────────────────────────────────────────────────────────
38
-
39
- def validate_patient(paciente_id: int) -> dict | None:
40
- """Verifica existencia del paciente en M10. Retorna datos básicos o None."""
41
- if settings.mock_external_services:
42
- return {"id": paciente_id, "nombre": "Paciente", "apellido": "Mock"}
43
- return _get(f"{settings.m10_core_url}/api/v1/usuarios/{paciente_id}")
44
-
45
-
46
- # ─── M1 HCE ────────────────────────────────────────────────────────────────
47
-
48
- def get_patient_contraindicaciones(paciente_id: int) -> list[str]:
49
- """
50
- Retorna lista de contraindicaciones del paciente (strings).
51
- Consulta informativa — no bloquea el flujo.
52
- """
53
- if settings.mock_external_services:
54
- return []
55
- data = _get(f"{settings.m1_hce_url}/api/v1/hce/pacientes/{paciente_id}/contraindicaciones")
56
- if not data:
57
- return []
58
- return [d.get("descripcion", "") for d in data.get("detalle", [])]
59
-
60
-
61
- def notify_movimiento(
62
- tipo_movimiento: str,
63
- paciente_id: int,
64
- cama_id: int | None = None,
65
- cama_origen_id: int | None = None,
66
- resultado: str | None = None,
67
- motivo: str | None = None,
68
- ) -> bool:
69
- """Notifica a M1 (HCE) un movimiento de paciente. Retorna True si OK."""
70
- if settings.mock_external_services:
71
- return True
72
- from datetime import datetime, timezone
73
- payload = {
74
- "tipo_movimiento": tipo_movimiento,
75
- "paciente_id": paciente_id,
76
- "cama_id": cama_id,
77
- "cama_origen_id": cama_origen_id,
78
- "resultado": resultado,
79
- "motivo": motivo,
80
- "timestamp": datetime.now(timezone.utc).isoformat(),
81
- }
82
- return _post(f"{settings.m1_hce_url}/api/v1/hce/movimientos", payload) is not None
83
-
84
-
85
- # ─── M9 Monitoreo ──────────────────────────────────────────────────────────
86
-
87
- def notify_alta_monitoreo(paciente_id: int) -> bool:
88
- if settings.mock_external_services:
89
- return True
90
- from datetime import datetime, timezone
91
- payload = {
92
- "evento": "ALTA_MONITOREO",
93
- "paciente_id": paciente_id,
94
- "timestamp": datetime.now(timezone.utc).isoformat(),
95
- }
96
- return _post(
97
- f"{settings.m9_monitoreo_url}/api/v1/webhooks/internacion/alta-monitoreo", payload
98
- ) is not None
99
-
100
-
101
- def notify_baja_monitoreo(paciente_id: int) -> bool:
102
- if settings.mock_external_services:
103
- return True
104
- from datetime import datetime, timezone
105
- payload = {
106
- "evento": "BAJA_MONITOREO",
107
- "paciente_id": paciente_id,
108
- "timestamp": datetime.now(timezone.utc).isoformat(),
109
- }
110
- return _post(
111
- f"{settings.m9_monitoreo_url}/api/v1/webhooks/internacion/baja-monitoreo", payload
112
- ) is not None
113
-
114
-
115
- # ─── M7 Facturación ────────────────────────────────────────────────────────
116
-
117
- def notify_cama_lista(
118
- cama_id: int,
119
- paciente_id: int,
120
- obra_social_id: str | None = None,
121
- numero_afiliado: str | None = None,
122
- ) -> bool:
123
- if settings.mock_external_services:
124
- return True
125
- from datetime import datetime, timezone
126
- payload = {
127
- "evento": "CAMA_LISTA",
128
- "cama_id": cama_id,
129
- "paciente_id": paciente_id,
130
- "obra_social_id": obra_social_id,
131
- "numero_afiliado": numero_afiliado,
132
- "timestamp_evento": datetime.now(timezone.utc).isoformat(),
133
- }
134
- return _post(
135
- f"{settings.m7_facturacion_url}/api/v1/webhooks/internacion/cama-lista", payload
136
- ) is not None
137
-
138
-
139
- # ─── M2 Turnos ─────────────────────────────────────────────────────────────
140
-
141
- def notify_resultado_quirofano(
142
- turno_id: str,
143
- reserva_id: int,
144
- cama_id: int,
145
- reserva_urgente_id: int,
146
- motivo: str | None = None,
147
- ) -> bool:
148
- if settings.mock_external_services:
149
- return True
150
- from datetime import datetime, timezone
151
- payload = {
152
- "resultado": "CANCELADA",
153
- "reserva_id": reserva_id,
154
- "cama_id": cama_id,
155
- "motivo_cancelacion": "DESPLAZADA_POR_URGENCIA",
156
- "reserva_urgente_id": reserva_urgente_id,
157
- "motivo": motivo,
158
- "timestamp": datetime.now(timezone.utc).isoformat(),
159
- }
160
- return _post(
161
- f"{settings.m2_turnos_url}/api/v1/turnos/{turno_id}/resultado-quirofano", payload
162
- ) is not None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/services/solicitud_service.py DELETED
@@ -1,352 +0,0 @@
1
- """
2
- Lógica de negocio para Solicitudes de Internación / Traslado.
3
- """
4
- from __future__ import annotations
5
- from datetime import datetime, timezone
6
- from fastapi import HTTPException
7
- from sqlalchemy.orm import Session
8
-
9
- from models.solicitud import Solicitud
10
- from models.cama import Cama
11
- from schemas.solicitud import SolicitudHceWebhook, SolicitudResolucionRequest
12
- from services import external_client
13
-
14
-
15
- _ERR_NOT_FOUND = {"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "Solicitud no encontrada"}
16
-
17
-
18
- def _parse_solicitud_id(solicitud_id: str) -> int:
19
- """Convierte 'SOL-00123' → 123."""
20
- try:
21
- return int(solicitud_id.split("-")[-1])
22
- except (ValueError, IndexError):
23
- raise HTTPException(
24
- status_code=400,
25
- detail={"codigo": "ERROR_VALIDACION", "mensaje": f"ID de solicitud inválido: {solicitud_id}"},
26
- )
27
-
28
-
29
- def _get_solicitud_or_404(db: Session, solicitud_id: str) -> Solicitud:
30
- num_id = _parse_solicitud_id(solicitud_id)
31
- sol = db.query(Solicitud).filter(Solicitud.id == num_id).first()
32
- if not sol:
33
- raise HTTPException(status_code=404, detail=_ERR_NOT_FOUND)
34
- return sol
35
-
36
-
37
- def _get_cama_or_404(db: Session, cama_id: int) -> Cama:
38
- c = db.query(Cama).filter(Cama.id == cama_id).first()
39
- if not c:
40
- raise HTTPException(
41
- status_code=404,
42
- detail={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": f"Cama {cama_id} no encontrada"},
43
- )
44
- return c
45
-
46
-
47
- # ─── Recibir solicitud desde HCE (M1) ─────────────────────────────────────
48
-
49
- def recibir_solicitud(db: Session, data: SolicitudHceWebhook) -> Solicitud:
50
- # Idempotencia
51
- existing = db.query(Solicitud).filter(Solicitud.solicitud_hce_id == data.solicitud_hce_id).first()
52
- if existing:
53
- return existing
54
-
55
- sol = Solicitud(
56
- solicitud_hce_id=data.solicitud_hce_id,
57
- tipo=data.tipo.value,
58
- estado="PENDIENTE",
59
- paciente_id=data.paciente_id,
60
- medico_solicitante_id=data.medico_solicitante_id,
61
- cama_solicitada_id=data.cama_solicitada_id,
62
- origen=data.origen.value if data.origen else None,
63
- turno_id=data.turno_id,
64
- diagnostico_ingreso=data.diagnostico_ingreso,
65
- obra_social_id=data.obra_social_id,
66
- numero_afiliado=data.numero_afiliado,
67
- prioridad=data.prioridad.value if data.prioridad else None,
68
- observaciones=data.observaciones,
69
- hospital_id=data.hospital_id,
70
- cama_origen_id=data.cama_origen_id,
71
- cama_destino_solicitada_id=data.cama_destino_solicitada_id,
72
- motivo_traslado=data.motivo_traslado,
73
- timestamp_solicitud=data.timestamp,
74
- )
75
- db.add(sol)
76
- db.commit()
77
- db.refresh(sol)
78
- return sol
79
-
80
-
81
- # ─── Listar / obtener solicitudes ──────────────────────────────────────────
82
-
83
- def get_solicitudes(
84
- db: Session,
85
- estado: str | None = None,
86
- tipo: str | None = None,
87
- hospital_id: str | None = None,
88
- ) -> list[Solicitud]:
89
- q = db.query(Solicitud)
90
- if estado:
91
- q = q.filter(Solicitud.estado == estado)
92
- else:
93
- q = q.filter(Solicitud.estado == "PENDIENTE")
94
- if tipo:
95
- q = q.filter(Solicitud.tipo == tipo)
96
- if hospital_id:
97
- q = q.filter(Solicitud.hospital_id == hospital_id)
98
- return q.all()
99
-
100
-
101
- def get_solicitud(db: Session, solicitud_id: str) -> Solicitud:
102
- return _get_solicitud_or_404(db, solicitud_id)
103
-
104
-
105
- # ─── Resolver solicitud ────────────────────────────────────────────────────
106
-
107
- def resolver_solicitud(
108
- db: Session,
109
- solicitud_id: str,
110
- data: SolicitudResolucionRequest,
111
- resuelto_por: int,
112
- ) -> Solicitud:
113
- sol = _get_solicitud_or_404(db, solicitud_id)
114
-
115
- if sol.estado != "PENDIENTE":
116
- raise HTTPException(
117
- status_code=409,
118
- detail={
119
- "codigo": "SOLICITUD_YA_RESUELTA",
120
- "mensaje": "La solicitud ya fue resuelta",
121
- "detalle": f"La solicitud {solicitud_id} fue {sol.estado}",
122
- },
123
- )
124
-
125
- accion = data.accion.value
126
-
127
- if accion == "RECHAZAR":
128
- _rechazar(db, sol, data.motivo, resuelto_por)
129
- elif accion in ("APROBAR", "APROBAR_CON_CAMBIO"):
130
- cama_id = data.cama_asignada_id if accion == "APROBAR_CON_CAMBIO" else sol.cama_solicitada_id
131
- if cama_id is None and sol.tipo == "INTERNACION":
132
- raise HTTPException(
133
- status_code=400,
134
- detail={"codigo": "ERROR_VALIDACION", "mensaje": "Se requiere cama_asignada_id"},
135
- )
136
- if sol.tipo == "INTERNACION":
137
- _aprobar_internacion(db, sol, cama_id, data.motivo, resuelto_por, accion)
138
- else:
139
- _aprobar_traslado(db, sol, cama_id, data.motivo, resuelto_por, accion)
140
- else:
141
- raise HTTPException(status_code=400, detail={"codigo": "ERROR_VALIDACION", "mensaje": "Acción inválida"})
142
-
143
- db.commit()
144
- db.refresh(sol)
145
- return sol
146
-
147
-
148
- def _rechazar(db: Session, sol: Solicitud, motivo: str | None, resuelto_por: int):
149
- sol.estado = "RECHAZADA"
150
- sol.accion = "RECHAZAR"
151
- sol.motivo = motivo
152
- sol.resuelto_por = resuelto_por
153
- sol.timestamp_resolucion = datetime.now(timezone.utc)
154
- external_client.notify_movimiento(
155
- "RESOLUCION_SOLICITUD",
156
- sol.paciente_id,
157
- resultado="RECHAZADA",
158
- motivo=motivo,
159
- )
160
-
161
-
162
- def _aprobar_internacion(
163
- db: Session, sol: Solicitud, cama_id: int, motivo: str | None, resuelto_por: int, accion: str
164
- ):
165
- # Validar paciente en M10
166
- paciente = external_client.validate_patient(sol.paciente_id)
167
- if not paciente:
168
- raise HTTPException(
169
- status_code=502,
170
- detail={"codigo": "SERVICIO_EXTERNO_NO_DISPONIBLE", "mensaje": "No se pudo validar el paciente en Core (M10)"},
171
- )
172
-
173
- cama = _get_cama_or_404(db, cama_id)
174
- if cama.estado != "DISPONIBLE":
175
- raise HTTPException(
176
- status_code=409,
177
- detail={"codigo": "CAMA_NO_DISPONIBLE", "mensaje": f"La cama {cama_id} no está disponible"},
178
- )
179
-
180
- # Contraindicaciones
181
- contraindicaciones_paciente = external_client.get_patient_contraindicaciones(sol.paciente_id)
182
- incompatibles = cama.contraindicaciones_incompatibles or []
183
- conflicto = set(contraindicaciones_paciente) & set(incompatibles)
184
- if conflicto:
185
- raise HTTPException(
186
- status_code=422,
187
- detail={
188
- "codigo": "CONTRAINDICACION_DETECTADA",
189
- "mensaje": "El paciente tiene contraindicaciones incompatibles",
190
- "detalle": f"Conflicto en cama {cama_id}: {', '.join(conflicto)}",
191
- },
192
- )
193
-
194
- cama.estado = "OCUPADA"
195
- cama.paciente_id = sol.paciente_id
196
- cama.ultima_actualizacion = datetime.now(timezone.utc)
197
-
198
- sol.estado = "APROBADA"
199
- sol.accion = accion
200
- sol.motivo = motivo
201
- sol.cama_asignada_id = cama_id
202
- sol.resuelto_por = resuelto_por
203
- sol.timestamp_resolucion = datetime.now(timezone.utc)
204
-
205
- external_client.notify_movimiento("INGRESO", sol.paciente_id, cama_id)
206
- external_client.notify_alta_monitoreo(sol.paciente_id)
207
-
208
-
209
- def _aprobar_traslado(
210
- db: Session, sol: Solicitud, cama_destino_id: int | None, motivo: str | None, resuelto_por: int, accion: str
211
- ):
212
- dest_id = cama_destino_id or sol.cama_destino_solicitada_id
213
- if not dest_id:
214
- raise HTTPException(
215
- status_code=400,
216
- detail={"codigo": "ERROR_VALIDACION", "mensaje": "Se requiere cama destino"},
217
- )
218
-
219
- cama_destino = _get_cama_or_404(db, dest_id)
220
- if cama_destino.estado != "DISPONIBLE":
221
- raise HTTPException(
222
- status_code=409,
223
- detail={"codigo": "CAMA_NO_DISPONIBLE", "mensaje": f"La cama destino {dest_id} no está disponible"},
224
- )
225
-
226
- # Contraindicaciones
227
- contraindicaciones_paciente = external_client.get_patient_contraindicaciones(sol.paciente_id)
228
- incompatibles = cama_destino.contraindicaciones_incompatibles or []
229
- conflicto = set(contraindicaciones_paciente) & set(incompatibles)
230
- if conflicto:
231
- raise HTTPException(
232
- status_code=422,
233
- detail={
234
- "codigo": "CONTRAINDICACION_DETECTADA",
235
- "mensaje": "El paciente tiene contraindicaciones incompatibles con la cama destino",
236
- "detalle": f"Conflicto: {', '.join(conflicto)}",
237
- },
238
- )
239
-
240
- # Cama origen → EN_LIMPIEZA
241
- if sol.cama_origen_id:
242
- cama_origen = _get_cama_or_404(db, sol.cama_origen_id)
243
- cama_origen.estado = "EN_LIMPIEZA"
244
- cama_origen.ultimo_movimiento_tipo = "TRASLADO"
245
- cama_origen.ultima_actualizacion = datetime.now(timezone.utc)
246
-
247
- cama_destino.estado = "OCUPADA"
248
- cama_destino.paciente_id = sol.paciente_id
249
- cama_destino.ultima_actualizacion = datetime.now(timezone.utc)
250
-
251
- sol.estado = "APROBADA"
252
- sol.accion = accion
253
- sol.motivo = motivo
254
- sol.cama_asignada_id = dest_id
255
- sol.resuelto_por = resuelto_por
256
- sol.timestamp_resolucion = datetime.now(timezone.utc)
257
-
258
- external_client.notify_movimiento("TRASLADO", sol.paciente_id, dest_id, sol.cama_origen_id)
259
-
260
-
261
- # ─── Alta médica (desde HCE M1) ────────────────────────────────────────────
262
-
263
- def procesar_alta_medica(db: Session, paciente_id: int) -> Cama:
264
- """Busca la cama ocupada por el paciente y la pone EN_LIMPIEZA."""
265
- cama = db.query(Cama).filter(
266
- Cama.paciente_id == paciente_id,
267
- Cama.estado.in_(["OCUPADA", "CODIGO_ROJO"]),
268
- ).first()
269
- if not cama:
270
- raise HTTPException(
271
- status_code=404,
272
- detail={
273
- "codigo": "RECURSO_NO_ENCONTRADO",
274
- "mensaje": "No se encontró cama asignada al paciente",
275
- },
276
- )
277
- cama.estado = "EN_LIMPIEZA"
278
- cama.ultimo_movimiento_tipo = "ALTA"
279
- cama.ultima_actualizacion = datetime.now(timezone.utc)
280
- db.commit()
281
- db.refresh(cama)
282
- external_client.notify_baja_monitoreo(paciente_id)
283
- return cama
284
-
285
-
286
- # ─── Alertas de emergencia (desde M9) ──────────────────────────────────────
287
-
288
- def procesar_alerta_emergencia(db: Session, paciente_id: int) -> Cama:
289
- cama = db.query(Cama).filter(
290
- Cama.paciente_id == paciente_id,
291
- Cama.estado == "OCUPADA",
292
- ).first()
293
- if not cama:
294
- raise HTTPException(
295
- status_code=404,
296
- detail={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "Paciente sin cama asignada"},
297
- )
298
- cama.estado = "CODIGO_ROJO"
299
- cama.ultima_actualizacion = datetime.now(timezone.utc)
300
- db.commit()
301
- db.refresh(cama)
302
- return cama
303
-
304
-
305
- def procesar_alerta_resuelta(db: Session, paciente_id: int) -> Cama:
306
- cama = db.query(Cama).filter(
307
- Cama.paciente_id == paciente_id,
308
- Cama.estado == "CODIGO_ROJO",
309
- ).first()
310
- if not cama:
311
- raise HTTPException(
312
- status_code=404,
313
- detail={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "No se encontró cama en CODIGO_ROJO para el paciente"},
314
- )
315
- cama.estado = "OCUPADA"
316
- cama.ultima_actualizacion = datetime.now(timezone.utc)
317
- db.commit()
318
- db.refresh(cama)
319
- return cama
320
-
321
-
322
- # ─── Cancelar reserva por turno (desde M2) ─────────────────────────────────
323
-
324
- def cancelar_reserva_por_turno(db: Session, turno_id: str, motivo: str) -> "ReservaQuirofano":
325
- from models.reserva import ReservaQuirofano as RQ
326
- reserva = db.query(RQ).filter(
327
- RQ.turno_id == turno_id,
328
- RQ.origen == "PROGRAMADA",
329
- ).first()
330
- if not reserva:
331
- raise HTTPException(
332
- status_code=404,
333
- detail={
334
- "codigo": "RESERVA_NO_ENCONTRADA",
335
- "mensaje": f"No existe reserva activa para el turno {turno_id}",
336
- },
337
- )
338
- if reserva.estado == "CANCELADA":
339
- return reserva # idempotencia
340
- if reserva.estado in ("EN_CURSO", "COMPLETADA"):
341
- raise HTTPException(
342
- status_code=409,
343
- detail={
344
- "codigo": "RESERVA_NO_CANCELABLE",
345
- "mensaje": "La reserva no puede cancelarse en su estado actual",
346
- "detalle": f"Estado: {reserva.estado}",
347
- },
348
- )
349
- reserva.estado = "CANCELADA"
350
- db.commit()
351
- db.refresh(reserva)
352
- return reserva