juampisor commited on
Commit
2c5d6e7
·
1 Parent(s): ef45f33

Implementacion de quirofanos. Actualizacion de tests

Browse files
.DS_Store CHANGED
Binary files a/.DS_Store and b/.DS_Store differ
 
.claude/settings.local.json CHANGED
@@ -12,7 +12,11 @@
12
  "Bash(python3 -m py_compile app/main.py app/crud/solicitud.py app/integrations/hce.py app/routers/webhooks.py app/schemas/cama.py app/schemas/enums.py app/services/cama_service.py app/services/solicitud_service.py)",
13
  "Bash(docker exec *)",
14
  "Bash(docker run *)",
15
- "Bash(xargs cat)"
 
 
 
 
16
  ]
17
  }
18
  }
 
12
  "Bash(python3 -m py_compile app/main.py app/crud/solicitud.py app/integrations/hce.py app/routers/webhooks.py app/schemas/cama.py app/schemas/enums.py app/services/cama_service.py app/services/solicitud_service.py)",
13
  "Bash(docker exec *)",
14
  "Bash(docker run *)",
15
+ "Bash(xargs cat)",
16
+ "Bash(python3 *)",
17
+ "Bash(pip3 list *)",
18
+ "Bash(/tmp/m6venv/bin/pip install *)",
19
+ "Bash(pip3 install *)"
20
  ]
21
  }
22
  }
app/.DS_Store ADDED
Binary file (6.15 kB). View file
 
app/crud/cama.py CHANGED
@@ -61,6 +61,7 @@ def save(db: Client, cama: Cama) -> Cama:
61
  updates = {
62
  "estado": cama.estado,
63
  "paciente_id": cama.paciente_id,
 
64
  "contraindicaciones_incompatibles": cama.contraindicaciones_incompatibles,
65
  "ultima_actualizacion": cama.ultima_actualizacion.isoformat() if cama.ultima_actualizacion else None,
66
  "ultimo_movimiento_tipo": cama.ultimo_movimiento_tipo,
@@ -74,11 +75,19 @@ def get_quirofanos(
74
  hospital_id: str | None = None,
75
  specialty_id: int | None = None,
76
  exclude_estados: list[str] | None = None,
 
77
  ) -> list[Cama]:
78
- excluidos = exclude_estados or ["FUERA_DE_SERVICIO", "BAJA_PERMANENTE"]
 
 
 
 
79
  q = db.table(_TABLE).select("*").eq("sector", "QUIROFANO").eq("tipo", "CIRUGIA")
80
- for estado in excluidos:
81
- q = q.neq("estado", estado)
 
 
 
82
  if hospital_id:
83
  q = q.eq("hospital_id", hospital_id)
84
  if specialty_id is not None:
 
61
  updates = {
62
  "estado": cama.estado,
63
  "paciente_id": cama.paciente_id,
64
+ "specialty_id": cama.specialty_id,
65
  "contraindicaciones_incompatibles": cama.contraindicaciones_incompatibles,
66
  "ultima_actualizacion": cama.ultima_actualizacion.isoformat() if cama.ultima_actualizacion else None,
67
  "ultimo_movimiento_tipo": cama.ultimo_movimiento_tipo,
 
75
  hospital_id: str | None = None,
76
  specialty_id: int | None = None,
77
  exclude_estados: list[str] | None = None,
78
+ estado: str | None = None,
79
  ) -> list[Cama]:
80
+ excluidos = (
81
+ ["FUERA_DE_SERVICIO", "BAJA_PERMANENTE"]
82
+ if exclude_estados is None
83
+ else exclude_estados
84
+ )
85
  q = db.table(_TABLE).select("*").eq("sector", "QUIROFANO").eq("tipo", "CIRUGIA")
86
+ if estado:
87
+ q = q.eq("estado", estado)
88
+ else:
89
+ for e in excluidos:
90
+ q = q.neq("estado", e)
91
  if hospital_id:
92
  q = q.eq("hospital_id", hospital_id)
93
  if specialty_id is not None:
app/dependencies.py CHANGED
@@ -58,15 +58,20 @@ def decode_token(token: str) -> dict:
58
 
59
  # ─── Auth FastAPI ───────────────────────────────────────────────────────────
60
 
61
- _security = HTTPBearer()
 
 
 
62
 
63
  _ERROR_401 = {"codigo": "NO_AUTENTICADO", "mensaje": "Token ausente, expirado o malformado"}
64
  _ERROR_403 = {"codigo": "NO_AUTORIZADO", "mensaje": "No tiene permisos para esta operación"}
65
 
66
 
67
  def get_current_user(
68
- credentials: HTTPAuthorizationCredentials = Depends(_security),
69
  ) -> dict:
 
 
70
  try:
71
  payload = decode_token(credentials.credentials)
72
  except ValueError:
 
58
 
59
  # ─── Auth FastAPI ───────────────────────────────────────────────────────────
60
 
61
+ # auto_error=False: sin esto, HTTPBearer responde 403 ante un token ausente.
62
+ # El contrato (§12) exige 401 para "sin token / token inválido", así que
63
+ # manejamos el caso None nosotros y devolvemos 401 de forma consistente.
64
+ _security = HTTPBearer(auto_error=False)
65
 
66
  _ERROR_401 = {"codigo": "NO_AUTENTICADO", "mensaje": "Token ausente, expirado o malformado"}
67
  _ERROR_403 = {"codigo": "NO_AUTORIZADO", "mensaje": "No tiene permisos para esta operación"}
68
 
69
 
70
  def get_current_user(
71
+ credentials: HTTPAuthorizationCredentials | None = Depends(_security),
72
  ) -> dict:
73
+ if credentials is None:
74
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401)
75
  try:
76
  payload = decode_token(credentials.credentials)
77
  except ValueError:
app/main.py CHANGED
@@ -12,7 +12,7 @@ from fastapi.responses import JSONResponse
12
  from app.config import settings
13
  from app.dependencies import create_access_token
14
 
15
- from app.routers import camas, solicitudes, webhooks
16
  from app.routers.webhooks import router_turnos
17
 
18
  logger = logging.getLogger(__name__)
@@ -57,6 +57,7 @@ app.add_middleware(
57
  PREFIX = "/api/v1"
58
 
59
  app.include_router(camas.router, prefix=PREFIX)
 
60
  app.include_router(solicitudes.router, prefix=PREFIX)
61
  app.include_router(webhooks.router, prefix=PREFIX)
62
  app.include_router(router_turnos, prefix=PREFIX)
 
12
  from app.config import settings
13
  from app.dependencies import create_access_token
14
 
15
+ from app.routers import camas, quirofanos, solicitudes, webhooks
16
  from app.routers.webhooks import router_turnos
17
 
18
  logger = logging.getLogger(__name__)
 
57
  PREFIX = "/api/v1"
58
 
59
  app.include_router(camas.router, prefix=PREFIX)
60
+ app.include_router(quirofanos.router, prefix=PREFIX)
61
  app.include_router(solicitudes.router, prefix=PREFIX)
62
  app.include_router(webhooks.router, prefix=PREFIX)
63
  app.include_router(router_turnos, prefix=PREFIX)
app/routers/camas.py CHANGED
@@ -1,7 +1,5 @@
1
- from datetime import datetime
2
  from typing import Optional
3
  from fastapi import APIRouter, Depends, Query, status
4
- from fastapi.responses import JSONResponse
5
  from supabase import Client
6
 
7
  from app.dependencies import get_db, require_roles
@@ -13,54 +11,12 @@ from app.schemas.cama import (
13
  AsignacionCamaRequest,
14
  AsignacionCamaResponse,
15
  )
16
- from app.schemas.reserva import (
17
- ReservaQuirofanoCreateRequest,
18
- ReservaEstadoUpdateRequest,
19
- ReservaQuirofanoResponse,
20
- ReservasListResponse,
21
- )
22
  from app.schemas.enums import EstadoCamaEnum
23
  from app.services import cama_service
24
 
25
  router = APIRouter(prefix="/camas", tags=["Camas"])
26
 
27
 
28
- # ─── Disponibilidad (debe ir ANTES de /{cama_id}) ─────────────────────────
29
-
30
- @router.get(
31
- "/disponibilidad",
32
- summary="Consultar disponibilidad de quirófanos",
33
- responses={401: {"description": "No autenticado"}, 403: {"description": "Sin permisos"}},
34
- )
35
- def get_disponibilidad(
36
- desde: datetime = Query(...),
37
- hasta: datetime = Query(...),
38
- hospital_id: Optional[str] = Query(None),
39
- specialty_id: Optional[int] = Query(None),
40
- db: Client = Depends(get_db),
41
- user: dict = Depends(require_roles("ADMINISTRATIVO", "MEDICO")),
42
- ):
43
- quirofanos = cama_service.get_disponibilidad_quirofanos(db, desde, hasta, hospital_id, specialty_id)
44
- result = []
45
- for q in quirofanos:
46
- reservas_resp = [ReservaQuirofanoResponse.model_validate(r) for r in q["reservas_en_rango"]]
47
- result.append({
48
- "cama_id": q["cama_id"],
49
- "numero": q["numero"],
50
- "piso": q["piso"],
51
- "hospital_id": q["hospital_id"],
52
- "estado": q["estado"],
53
- "specialty_id": q["specialty_id"],
54
- "reservas_en_rango": [r.model_dump() for r in reservas_resp],
55
- })
56
- return {
57
- "desde": desde.isoformat(),
58
- "hasta": hasta.isoformat(),
59
- "total_quirofanos": len(result),
60
- "quirofanos": result,
61
- }
62
-
63
-
64
  # ─── CRUD Camas ────────────────────────────────────────────────────────────
65
 
66
  @router.get(
@@ -176,82 +132,3 @@ def asignar_cama(
176
  cama_origen_id=data.cama_origen_id,
177
  timestamp=cama.ultima_actualizacion,
178
  )
179
-
180
-
181
- # ─── Reservas de Quirófano ─────────────────────────────────────────────────
182
-
183
- @router.get(
184
- "/{cama_id}/reservas",
185
- response_model=ReservasListResponse,
186
- summary="Listar reservas de un quirófano",
187
- responses={401: {"description": "No autenticado"}, 403: {"description": "Sin permisos"}, 404: {"description": "Cama no encontrada"}, 409: {"description": "La cama no es un quirófano"}},
188
- )
189
- def get_reservas(
190
- cama_id: int,
191
- estado: Optional[str] = Query(None),
192
- prioridad: Optional[str] = Query(None),
193
- fecha_desde: Optional[datetime] = Query(None),
194
- fecha_hasta: Optional[datetime] = Query(None),
195
- db: Client = Depends(get_db),
196
- user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
197
- ):
198
- reservas = cama_service.get_reservas(
199
- db, cama_id, estado, prioridad,
200
- fecha_desde.isoformat() if fecha_desde else None,
201
- fecha_hasta.isoformat() if fecha_hasta else None,
202
- )
203
- return ReservasListResponse(
204
- total=len(reservas),
205
- reservas=[ReservaQuirofanoResponse.model_validate(r) for r in reservas],
206
- )
207
-
208
-
209
- @router.post(
210
- "/{cama_id}/reservas",
211
- response_model=ReservaQuirofanoResponse,
212
- summary="Crear reserva de quirófano programada",
213
- responses={401: {"description": "No autenticado"}, 403: {"description": "Sin permisos"}, 404: {"description": "Cama no encontrada"}, 409: {"description": "Conflicto de horario o estado"}, 422: {"description": "Prioridad URGENTE no permitida"}},
214
- )
215
- def crear_reserva(
216
- cama_id: int,
217
- data: ReservaQuirofanoCreateRequest,
218
- db: Client = Depends(get_db),
219
- user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
220
- ):
221
- reserva, created = cama_service.create_reserva(db, cama_id, data)
222
- resp = ReservaQuirofanoResponse.model_validate(reserva)
223
- http_status = status.HTTP_201_CREATED if created else status.HTTP_200_OK
224
- return JSONResponse(content=resp.model_dump(mode="json"), status_code=http_status)
225
-
226
-
227
- @router.get(
228
- "/{cama_id}/reservas/{reserva_id}",
229
- response_model=ReservaQuirofanoResponse,
230
- summary="Obtener detalle de una reserva de quirófano",
231
- responses={401: {"description": "No autenticado"}, 403: {"description": "Sin permisos"}, 404: {"description": "Reserva no encontrada"}},
232
- )
233
- def get_reserva(
234
- cama_id: int,
235
- reserva_id: int,
236
- db: Client = Depends(get_db),
237
- user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
238
- ):
239
- reserva = cama_service.get_reserva(db, cama_id, reserva_id)
240
- return ReservaQuirofanoResponse.model_validate(reserva)
241
-
242
-
243
- @router.patch(
244
- "/{cama_id}/reservas/{reserva_id}",
245
- response_model=ReservaQuirofanoResponse,
246
- summary="Actualizar estado de una reserva de quirófano",
247
- responses={401: {"description": "No autenticado"}, 403: {"description": "Sin permisos"}, 404: {"description": "Reserva no encontrada"}, 409: {"description": "Transición de estado inválida"}},
248
- )
249
- def update_reserva(
250
- cama_id: int,
251
- reserva_id: int,
252
- data: ReservaEstadoUpdateRequest,
253
- db: Client = Depends(get_db),
254
- user: dict = Depends(require_roles("ADMINISTRATIVO")),
255
- ):
256
- reserva = cama_service.update_reserva_estado(db, cama_id, reserva_id, data)
257
- return ReservaQuirofanoResponse.model_validate(reserva)
 
 
1
  from typing import Optional
2
  from fastapi import APIRouter, Depends, Query, status
 
3
  from supabase import Client
4
 
5
  from app.dependencies import get_db, require_roles
 
11
  AsignacionCamaRequest,
12
  AsignacionCamaResponse,
13
  )
 
 
 
 
 
 
14
  from app.schemas.enums import EstadoCamaEnum
15
  from app.services import cama_service
16
 
17
  router = APIRouter(prefix="/camas", tags=["Camas"])
18
 
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  # ─── CRUD Camas ────────────────────────────────────────────────────────────
21
 
22
  @router.get(
 
132
  cama_origen_id=data.cama_origen_id,
133
  timestamp=cama.ultima_actualizacion,
134
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/routers/quirofanos.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from typing import Optional
3
+ from fastapi import APIRouter, Depends, Query, status
4
+ from fastapi.responses import JSONResponse
5
+ from supabase import Client
6
+
7
+ from app.dependencies import get_db, require_roles
8
+ from app.schemas.cama import (
9
+ QuirofanoCreateRequest,
10
+ QuirofanoUpdateRequest,
11
+ QuirofanoResponse,
12
+ QuirofanosListResponse,
13
+ )
14
+ from app.schemas.reserva import (
15
+ ReservaQuirofanoCreateRequest,
16
+ ReservaEstadoUpdateRequest,
17
+ ReservaQuirofanoResponse,
18
+ ReservasListResponse,
19
+ )
20
+ from app.schemas.enums import EstadoCamaEnum, PrioridadQuirofanoEnum
21
+ from app.services import cama_service
22
+
23
+ router = APIRouter(prefix="/quirofanos", tags=["Quirófanos"])
24
+
25
+
26
+ # ─── Disponibilidad (debe ir ANTES de /{quirofano_id}) ─────────────────────
27
+
28
+ @router.get(
29
+ "/disponibilidad",
30
+ summary="Consultar disponibilidad de quirófanos en un rango horario",
31
+ responses={401: {"description": "No autenticado"}, 403: {"description": "Sin permisos"}},
32
+ )
33
+ def get_disponibilidad(
34
+ desde: datetime = Query(...),
35
+ hasta: datetime = Query(...),
36
+ hospital_id: Optional[str] = Query(None),
37
+ specialty_id: Optional[int] = Query(None),
38
+ db: Client = Depends(get_db),
39
+ user: dict = Depends(require_roles("ADMINISTRATIVO", "MEDICO")),
40
+ ):
41
+ quirofanos = cama_service.get_disponibilidad_quirofanos(db, desde, hasta, hospital_id, specialty_id)
42
+ result = []
43
+ for q in quirofanos:
44
+ reservas_resp = [ReservaQuirofanoResponse.model_validate(r) for r in q["reservas_en_rango"]]
45
+ result.append({
46
+ "cama_id": q["cama_id"],
47
+ "numero": q["numero"],
48
+ "piso": q["piso"],
49
+ "hospital_id": q["hospital_id"],
50
+ "estado": q["estado"],
51
+ "specialty_id": q["specialty_id"],
52
+ "reservas_en_rango": [r.model_dump(mode="json") for r in reservas_resp],
53
+ })
54
+ return {
55
+ "desde": desde.isoformat(),
56
+ "hasta": hasta.isoformat(),
57
+ "total_quirofanos": len(result),
58
+ "quirofanos": result,
59
+ }
60
+
61
+
62
+ # ─── CRUD Quirófanos ───────────────────────────────────────────────────────
63
+
64
+ @router.get(
65
+ "",
66
+ response_model=QuirofanosListResponse,
67
+ summary="Listar quirófanos",
68
+ responses={401: {"description": "No autenticado"}, 403: {"description": "Sin permisos"}},
69
+ )
70
+ def get_quirofanos(
71
+ hospital_id: Optional[str] = Query(None),
72
+ estado: Optional[EstadoCamaEnum] = Query(None),
73
+ specialty_id: Optional[int] = Query(None),
74
+ db: Client = Depends(get_db),
75
+ user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
76
+ ):
77
+ quirofanos = cama_service.get_quirofanos_list(
78
+ db, hospital_id, estado.value if estado else None, specialty_id
79
+ )
80
+ resp = [QuirofanoResponse.model_validate(q) for q in quirofanos]
81
+ return QuirofanosListResponse(total=len(resp), quirofanos=resp)
82
+
83
+
84
+ @router.post(
85
+ "",
86
+ response_model=QuirofanoResponse,
87
+ status_code=status.HTTP_201_CREATED,
88
+ summary="Dar de alta un quirófano",
89
+ responses={400: {"description": "Payload inválido"}, 401: {"description": "No autenticado"}, 403: {"description": "Sin permisos"}},
90
+ )
91
+ def crear_quirofano(
92
+ data: QuirofanoCreateRequest,
93
+ db: Client = Depends(get_db),
94
+ user: dict = Depends(require_roles("ADMINISTRATIVO")),
95
+ ):
96
+ quirofano = cama_service.create_quirofano(db, data)
97
+ return QuirofanoResponse.model_validate(quirofano)
98
+
99
+
100
+ @router.get(
101
+ "/{quirofano_id}",
102
+ response_model=QuirofanoResponse,
103
+ summary="Obtener quirófano por ID",
104
+ responses={401: {"description": "No autenticado"}, 404: {"description": "Quirófano no encontrado"}},
105
+ )
106
+ def get_quirofano(
107
+ quirofano_id: int,
108
+ db: Client = Depends(get_db),
109
+ user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
110
+ ):
111
+ quirofano = cama_service.get_quirofano(db, quirofano_id)
112
+ return QuirofanoResponse.model_validate(quirofano)
113
+
114
+
115
+ @router.patch(
116
+ "/{quirofano_id}",
117
+ response_model=QuirofanoResponse,
118
+ summary="Actualizar quirófano",
119
+ responses={400: {"description": "Payload inválido"}, 401: {"description": "No autenticado"}, 403: {"description": "Sin permisos"}, 404: {"description": "Quirófano no encontrado"}, 409: {"description": "Conflicto de estado"}},
120
+ )
121
+ def update_quirofano(
122
+ quirofano_id: int,
123
+ data: QuirofanoUpdateRequest,
124
+ db: Client = Depends(get_db),
125
+ user: dict = Depends(require_roles("ADMINISTRATIVO")),
126
+ ):
127
+ quirofano = cama_service.update_quirofano(db, quirofano_id, data)
128
+ return QuirofanoResponse.model_validate(quirofano)
129
+
130
+
131
+ # ─── Reservas de Quirófano ─────────────────────────────────────────────────
132
+
133
+ @router.get(
134
+ "/{quirofano_id}/reservas",
135
+ response_model=ReservasListResponse,
136
+ summary="Listar reservas de un quirófano",
137
+ responses={401: {"description": "No autenticado"}, 403: {"description": "Sin permisos"}, 404: {"description": "Quirófano no encontrado"}, 409: {"description": "La cama no es un quirófano"}},
138
+ )
139
+ def get_reservas(
140
+ quirofano_id: int,
141
+ estado: Optional[str] = Query(None),
142
+ prioridad: Optional[PrioridadQuirofanoEnum] = Query(None),
143
+ fecha_desde: Optional[datetime] = Query(None),
144
+ fecha_hasta: Optional[datetime] = Query(None),
145
+ db: Client = Depends(get_db),
146
+ user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
147
+ ):
148
+ reservas = cama_service.get_reservas(
149
+ db, quirofano_id, estado, prioridad.value if prioridad else None,
150
+ fecha_desde.isoformat() if fecha_desde else None,
151
+ fecha_hasta.isoformat() if fecha_hasta else None,
152
+ )
153
+ return ReservasListResponse(
154
+ total=len(reservas),
155
+ reservas=[ReservaQuirofanoResponse.model_validate(r) for r in reservas],
156
+ )
157
+
158
+
159
+ @router.post(
160
+ "/{quirofano_id}/reservas",
161
+ response_model=ReservaQuirofanoResponse,
162
+ summary="Recibir solicitud de cirugía programada",
163
+ responses={401: {"description": "No autenticado"}, 403: {"description": "Sin permisos"}, 404: {"description": "Quirófano no encontrado"}, 409: {"description": "Conflicto de horario o estado"}, 422: {"description": "Prioridad URGENTE no permitida"}},
164
+ )
165
+ def crear_reserva(
166
+ quirofano_id: int,
167
+ data: ReservaQuirofanoCreateRequest,
168
+ db: Client = Depends(get_db),
169
+ user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
170
+ ):
171
+ reserva, created = cama_service.create_reserva(db, quirofano_id, data)
172
+ resp = ReservaQuirofanoResponse.model_validate(reserva)
173
+ http_status = status.HTTP_201_CREATED if created else status.HTTP_200_OK
174
+ return JSONResponse(content=resp.model_dump(mode="json"), status_code=http_status)
175
+
176
+
177
+ @router.get(
178
+ "/{quirofano_id}/reservas/{reserva_id}",
179
+ response_model=ReservaQuirofanoResponse,
180
+ summary="Obtener detalle de una reserva",
181
+ responses={401: {"description": "No autenticado"}, 403: {"description": "Sin permisos"}, 404: {"description": "Reserva no encontrada"}},
182
+ )
183
+ def get_reserva(
184
+ quirofano_id: int,
185
+ reserva_id: int,
186
+ db: Client = Depends(get_db),
187
+ user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
188
+ ):
189
+ reserva = cama_service.get_reserva(db, quirofano_id, reserva_id)
190
+ return ReservaQuirofanoResponse.model_validate(reserva)
191
+
192
+
193
+ @router.patch(
194
+ "/{quirofano_id}/reservas/{reserva_id}",
195
+ response_model=ReservaQuirofanoResponse,
196
+ summary="Actualizar estado de una reserva de quirófano",
197
+ responses={401: {"description": "No autenticado"}, 403: {"description": "Sin permisos"}, 404: {"description": "Reserva no encontrada"}, 409: {"description": "Transición de estado inválida"}},
198
+ )
199
+ def update_reserva(
200
+ quirofano_id: int,
201
+ reserva_id: int,
202
+ data: ReservaEstadoUpdateRequest,
203
+ db: Client = Depends(get_db),
204
+ user: dict = Depends(require_roles("ADMINISTRATIVO")),
205
+ ):
206
+ reserva = cama_service.update_reserva_estado(db, quirofano_id, reserva_id, data)
207
+ return ReservaQuirofanoResponse.model_validate(reserva)
app/schemas/cama.py CHANGED
@@ -76,3 +76,47 @@ class DisponibilidadQuirofanosResponse(BaseModel):
76
  hasta: str
77
  total_quirofanos: int
78
  quirofanos: list[dict]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  hasta: str
77
  total_quirofanos: int
78
  quirofanos: list[dict]
79
+
80
+
81
+ # ─── Quirófanos (especialización de Cama: sector=QUIROFANO, tipo=CIRUGIA) ───
82
+
83
+ class QuirofanoCreateRequest(BaseModel):
84
+ numero: int
85
+ piso: int
86
+ specialty_id: int
87
+ hospital_id: str = Field(..., min_length=1, max_length=50)
88
+ contraindicaciones_incompatibles: list[str] = []
89
+
90
+ @field_validator("hospital_id", mode="before")
91
+ @classmethod
92
+ def strip_and_require(cls, v: str) -> str:
93
+ if not isinstance(v, str):
94
+ return v
95
+ v = v.strip()
96
+ if not v:
97
+ raise ValueError("El campo no puede estar vacío o contener solo espacios")
98
+ return v
99
+
100
+
101
+ class QuirofanoUpdateRequest(BaseModel):
102
+ specialty_id: Optional[int] = None
103
+ contraindicaciones_incompatibles: Optional[list[str]] = None
104
+ estado: Optional[EstadoCamaEnum] = None
105
+
106
+
107
+ class QuirofanoResponse(BaseModel):
108
+ model_config = ConfigDict(from_attributes=True)
109
+
110
+ id: int
111
+ numero: int
112
+ piso: int
113
+ specialty_id: Optional[int] = None
114
+ estado: EstadoCamaEnum
115
+ hospital_id: str
116
+ contraindicaciones_incompatibles: list[str]
117
+ ultima_actualizacion: datetime
118
+
119
+
120
+ class QuirofanosListResponse(BaseModel):
121
+ total: int
122
+ quirofanos: list[QuirofanoResponse]
app/services/cama_service.py CHANGED
@@ -8,13 +8,18 @@ from supabase import Client
8
 
9
  from app.models.cama import Cama
10
  from app.models.reserva import ReservaQuirofano
11
- from app.schemas.cama import CamaCreateRequest, CamaUpdateRequest
 
 
 
 
 
12
  from app.schemas.reserva import (
13
  ReservaQuirofanoCreateRequest,
14
  ReservaEstadoUpdateRequest,
15
  CirugiaUrgenteWebhook,
16
  )
17
- from app.schemas.enums import EstadoCamaEnum, EstadoReservaEnum
18
  from app.crud import cama as cama_crud
19
  from app.crud import reserva as reserva_crud
20
  from app.integrations import hce, monitoreo, facturacion, turnos
@@ -194,6 +199,83 @@ def asignar_cama(db: Client, cama_id: int, tipo: str, paciente_id: int, cama_ori
194
  return cama_crud.save(db, cama_destino)
195
 
196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  # ─── Reservas de Quirófano ─────────────────────────────────────────────────
198
 
199
  def get_reservas(
 
8
 
9
  from app.models.cama import Cama
10
  from app.models.reserva import ReservaQuirofano
11
+ from app.schemas.cama import (
12
+ CamaCreateRequest,
13
+ CamaUpdateRequest,
14
+ QuirofanoCreateRequest,
15
+ QuirofanoUpdateRequest,
16
+ )
17
  from app.schemas.reserva import (
18
  ReservaQuirofanoCreateRequest,
19
  ReservaEstadoUpdateRequest,
20
  CirugiaUrgenteWebhook,
21
  )
22
+ from app.schemas.enums import EstadoCamaEnum, EstadoReservaEnum, SectorEnum, TipoCamaEnum
23
  from app.crud import cama as cama_crud
24
  from app.crud import reserva as reserva_crud
25
  from app.integrations import hce, monitoreo, facturacion, turnos
 
199
  return cama_crud.save(db, cama_destino)
200
 
201
 
202
+ # ─── Quirófanos (entidad) ──────────────────────────────────────────────────
203
+
204
+ _ERR_QUIROFANO_NOT_FOUND = {
205
+ "codigo": "RECURSO_NO_ENCONTRADO",
206
+ "mensaje": "Quirófano no encontrado",
207
+ }
208
+
209
+
210
+ def _get_quirofano_or_404(db: Client, quirofano_id: int) -> Cama:
211
+ cama = _get_cama_or_404(db, quirofano_id)
212
+ if not _is_quirofano(cama):
213
+ raise HTTPException(status_code=404, detail=_ERR_QUIROFANO_NOT_FOUND)
214
+ return cama
215
+
216
+
217
+ def get_quirofanos_list(
218
+ db: Client,
219
+ hospital_id: str | None = None,
220
+ estado: str | None = None,
221
+ specialty_id: int | None = None,
222
+ ) -> list[Cama]:
223
+ return cama_crud.get_quirofanos(
224
+ db, hospital_id, specialty_id,
225
+ exclude_estados=[EstadoCamaEnum.BAJA_PERMANENTE.value], estado=estado,
226
+ )
227
+
228
+
229
+ def create_quirofano(db: Client, data: QuirofanoCreateRequest) -> Cama:
230
+ cama_req = CamaCreateRequest(
231
+ numero=data.numero,
232
+ piso=data.piso,
233
+ sector=SectorEnum.QUIROFANO,
234
+ tipo=TipoCamaEnum.CIRUGIA,
235
+ specialty_id=data.specialty_id,
236
+ hospital_id=data.hospital_id,
237
+ contraindicaciones_incompatibles=data.contraindicaciones_incompatibles,
238
+ )
239
+ return cama_crud.create(db, cama_req)
240
+
241
+
242
+ def get_quirofano(db: Client, quirofano_id: int) -> Cama:
243
+ return _get_quirofano_or_404(db, quirofano_id)
244
+
245
+
246
+ def update_quirofano(
247
+ db: Client, quirofano_id: int, data: QuirofanoUpdateRequest
248
+ ) -> Cama:
249
+ cama = _get_quirofano_or_404(db, quirofano_id)
250
+
251
+ if data.estado is not None:
252
+ nuevo_estado = data.estado.value
253
+ if nuevo_estado in (
254
+ EstadoCamaEnum.OCUPADA.value,
255
+ EstadoCamaEnum.CODIGO_ROJO.value,
256
+ EstadoCamaEnum.EN_LIMPIEZA.value,
257
+ ):
258
+ raise HTTPException(
259
+ status_code=409,
260
+ detail={
261
+ "codigo": "CONFLICTO_ESTADO",
262
+ "mensaje": f"El estado {nuevo_estado} solo se asigna automáticamente",
263
+ },
264
+ )
265
+ cama.estado = nuevo_estado
266
+ if nuevo_estado == EstadoCamaEnum.DISPONIBLE.value and cama.paciente_id:
267
+ cama.paciente_id = None
268
+ cama.ultimo_movimiento_tipo = None
269
+
270
+ if data.specialty_id is not None:
271
+ cama.specialty_id = data.specialty_id
272
+ if data.contraindicaciones_incompatibles is not None:
273
+ cama.contraindicaciones_incompatibles = data.contraindicaciones_incompatibles
274
+
275
+ cama.ultima_actualizacion = datetime.now(timezone.utc)
276
+ return cama_crud.save(db, cama)
277
+
278
+
279
  # ─── Reservas de Quirófano ─────────────────────────────────────────────────
280
 
281
  def get_reservas(
documentation/M6_DISEÑO.md CHANGED
@@ -346,6 +346,8 @@ Autenticación por JWT centralizada en Core (M10). Un middleware en FastAPI vali
346
 
347
  11. **`Cama.numero` tipo corregido.** Era `string` en el modelo y schema. Corregido a **`integer`** para reflejar que el número de cama es siempre un valor numérico.
348
 
 
 
349
  ### 14.2 Pendientes
350
 
351
  1. **`security` global vacío.** El spec declara el esquema `BearerAuth` pero deja `security` vacío a nivel raíz. Falta declarar **`security: [{ BearerAuth: [] }]`** para que la protección sea explícita en el contrato.
 
346
 
347
  11. **`Cama.numero` tipo corregido.** Era `string` en el modelo y schema. Corregido a **`integer`** para reflejar que el número de cama es siempre un valor numérico.
348
 
349
+ 12. **`numero` de quirófano unificado a `integer`.** `QuirofanoCreateRequest.numero` y `QuirofanoResponse.numero` declaraban `string` (ej. `"Q01"`), inconsistente con que el quirófano comparte la tabla `camas`, donde `numero` es `integer` (corrección #11). No puede ser de los dos tipos a la vez. Se unifica a **`integer`** en ambos schemas y en el bloque `quirofanos[].numero` de la respuesta de `GET /quirofanos/disponibilidad`. Consecuencia asumida: los números de quirófano son numéricos (no admiten códigos alfanuméricos tipo `"Q01"`); si en el futuro se necesitan alfanuméricos, hay que migrar la columna `camas.numero` a `string` y revertir #11, lo que también afecta a las camas comunes.
350
+
351
  ### 14.2 Pendientes
352
 
353
  1. **`security` global vacío.** El spec declara el esquema `BearerAuth` pero deja `security` vacío a nivel raíz. Falta declarar **`security: [{ BearerAuth: [] }]`** para que la protección sea explícita en el contrato.
documentation/M6_openapi.json CHANGED
@@ -1749,8 +1749,8 @@
1749
  "example": 501
1750
  },
1751
  "numero": {
1752
- "type": "string",
1753
- "example": "501"
1754
  },
1755
  "piso": {
1756
  "type": "integer",
@@ -5990,8 +5990,8 @@
5990
  ],
5991
  "properties": {
5992
  "numero": {
5993
- "type": "string",
5994
- "example": "Q01"
5995
  },
5996
  "piso": {
5997
  "type": "integer",
@@ -6023,8 +6023,8 @@
6023
  "example": 501
6024
  },
6025
  "numero": {
6026
- "type": "string",
6027
- "example": "Q01"
6028
  },
6029
  "piso": {
6030
  "type": "integer",
@@ -6210,4 +6210,4 @@
6210
  },
6211
  "servers": [],
6212
  "security": []
6213
- }
 
1749
  "example": 501
1750
  },
1751
  "numero": {
1752
+ "type": "integer",
1753
+ "example": 501
1754
  },
1755
  "piso": {
1756
  "type": "integer",
 
5990
  ],
5991
  "properties": {
5992
  "numero": {
5993
+ "type": "integer",
5994
+ "example": 501
5995
  },
5996
  "piso": {
5997
  "type": "integer",
 
6023
  "example": 501
6024
  },
6025
  "numero": {
6026
+ "type": "integer",
6027
+ "example": 501
6028
  },
6029
  "piso": {
6030
  "type": "integer",
 
6210
  },
6211
  "servers": [],
6212
  "security": []
6213
+ }
tests/conftest.py CHANGED
@@ -1,27 +1,46 @@
1
  """
2
  Fixtures compartidas para los tests de Módulo 6.
 
 
 
 
3
  """
4
  import pytest
5
- from unittest.mock import MagicMock, patch
6
  from fastapi.testclient import TestClient
7
 
8
  from app.main import app
9
- from app.dependencies import get_db
10
 
11
 
12
- def override_get_db():
 
13
  return MagicMock()
14
 
15
 
16
  @pytest.fixture
17
- def client():
18
- app.dependency_overrides[get_db] = override_get_db
19
- with patch("app.main.Base.metadata.create_all"):
20
- with TestClient(app) as c:
21
- yield c
22
  app.dependency_overrides.clear()
23
 
24
 
 
 
 
 
 
25
  @pytest.fixture
26
- def db():
27
- return MagicMock()
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
  Fixtures compartidas para los tests de Módulo 6.
3
+
4
+ La base se reemplaza por un MagicMock (los tests mockean la capa CRUD, no la DB
5
+ real). La autenticación usa tokens JWT reales generados con la misma clave que
6
+ valida la app, así se ejercita el flujo de seguridad de verdad.
7
  """
8
  import pytest
9
+ from unittest.mock import MagicMock
10
  from fastapi.testclient import TestClient
11
 
12
  from app.main import app
13
+ from app.dependencies import get_db, create_access_token
14
 
15
 
16
+ @pytest.fixture
17
+ def db():
18
  return MagicMock()
19
 
20
 
21
  @pytest.fixture
22
+ def client(db):
23
+ app.dependency_overrides[get_db] = lambda: db
24
+ with TestClient(app) as c:
25
+ yield c
 
26
  app.dependency_overrides.clear()
27
 
28
 
29
+ def _headers(rol: str) -> dict:
30
+ token = create_access_token(sub="1", rol=rol)
31
+ return {"Authorization": f"Bearer {token}"}
32
+
33
+
34
  @pytest.fixture
35
+ def admin_headers() -> dict:
36
+ return _headers("ADMINISTRATIVO")
37
+
38
+
39
+ @pytest.fixture
40
+ def medico_headers() -> dict:
41
+ return _headers("MEDICO")
42
+
43
+
44
+ @pytest.fixture
45
+ def limpieza_headers() -> dict:
46
+ return _headers("LIMPIEZA")
tests/factories.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Factories de objetos de dominio para los tests.
3
+
4
+ Devuelven `SimpleNamespace` con todos los atributos que leen los response models
5
+ (via `from_attributes=True`) y la capa de servicios. Permiten mockear el CRUD sin
6
+ tocar la base ni instanciar modelos SQLAlchemy con sesión.
7
+ """
8
+ from __future__ import annotations
9
+ from datetime import datetime, timezone
10
+ from types import SimpleNamespace
11
+
12
+ _NOW = datetime(2025, 1, 18, 10, 30, tzinfo=timezone.utc)
13
+
14
+
15
+ def make_cama(**overrides) -> SimpleNamespace:
16
+ data = {
17
+ "id": 101,
18
+ "numero": 101,
19
+ "piso": 1,
20
+ "sector": "SALA_COMUN",
21
+ "tipo": "ESTANDAR",
22
+ "specialty_id": None,
23
+ "estado": "DISPONIBLE",
24
+ "paciente_id": None,
25
+ "hospital_id": "HOSP-001",
26
+ "contraindicaciones_incompatibles": [],
27
+ "ultima_actualizacion": _NOW,
28
+ "ultimo_movimiento_tipo": None,
29
+ }
30
+ data.update(overrides)
31
+ return SimpleNamespace(**data)
32
+
33
+
34
+ def make_quirofano(**overrides) -> SimpleNamespace:
35
+ base = {
36
+ "id": 501,
37
+ "numero": 501,
38
+ "piso": 5,
39
+ "sector": "QUIROFANO",
40
+ "tipo": "CIRUGIA",
41
+ "specialty_id": 43,
42
+ }
43
+ base.update(overrides)
44
+ return make_cama(**base)
45
+
46
+
47
+ def make_reserva(**overrides) -> SimpleNamespace:
48
+ data = {
49
+ "id": 1,
50
+ "cama_id": 501,
51
+ "turno_id": "TURNO-001",
52
+ "origen": "PROGRAMADA",
53
+ "estado": "RESERVADA",
54
+ "prioridad": "MEDIA",
55
+ "paciente_id": 7,
56
+ "medico_cirujano_id": 22,
57
+ "fecha_hora_inicio": _NOW,
58
+ "fecha_hora_fin_estimada": datetime(2025, 1, 18, 12, 30, tzinfo=timezone.utc),
59
+ "observaciones": None,
60
+ "desplazada_por_reserva_id": None,
61
+ "created_at": _NOW,
62
+ }
63
+ data.update(overrides)
64
+ return SimpleNamespace(**data)
65
+
66
+
67
+ def make_solicitud(**overrides) -> SimpleNamespace:
68
+ data = {
69
+ "solicitud_id": "SOL-00001",
70
+ "solicitud_hce_id": "HCE-SOL-001",
71
+ "tipo": "INTERNACION",
72
+ "estado": "PENDIENTE",
73
+ "paciente_id": 7,
74
+ "medico_solicitante_id": 10,
75
+ "cama_solicitada_id": 101,
76
+ "cama_asignada_id": None,
77
+ "origen": "GUARDIA",
78
+ "turno_id": None,
79
+ "diagnostico_ingreso": None,
80
+ "obra_social_id": None,
81
+ "numero_afiliado": None,
82
+ "prioridad": "MEDIA",
83
+ "cama_origen_id": None,
84
+ "cama_destino_solicitada_id": None,
85
+ "motivo_traslado": None,
86
+ "accion": None,
87
+ "motivo": None,
88
+ "resuelto_por": None,
89
+ "observaciones": None,
90
+ "timestamp_solicitud": _NOW,
91
+ "timestamp_resolucion": None,
92
+ }
93
+ data.update(overrides)
94
+ return SimpleNamespace(**data)
tests/test_camas.py CHANGED
@@ -1,28 +1,89 @@
1
  """
2
- Tests de integración para el router de camas.
 
 
 
3
  """
4
- import pytest
5
  from fastapi.testclient import TestClient
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- @pytest.mark.skip(reason="Requiere configurar token de test")
9
- def test_get_camas_sin_auth(client: TestClient):
10
- response = client.get("/api/v1/camas")
11
- assert response.status_code == 401
12
 
 
13
 
14
- @pytest.mark.skip(reason="Requiere configurar token de test")
15
- def test_crear_cama(client: TestClient):
16
  payload = {
17
- "numero": 101,
18
- "piso": 1,
19
- "sector": "SALA_COMUN",
20
- "tipo": "ESTANDAR",
21
- "hospital_id": "HG-001",
22
  "contraindicaciones_incompatibles": [],
23
  }
24
- response = client.post("/api/v1/camas", json=payload)
25
- assert response.status_code == 201
26
- data = response.json()
27
- assert data["numero"] == "101"
28
  assert data["estado"] == "DISPONIBLE"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ Tests del router de Camas.
3
+
4
+ Mockean la capa CRUD para ejercitar routing + auth/roles + reglas de negocio +
5
+ serialización, sin DB real.
6
  """
 
7
  from fastapi.testclient import TestClient
8
 
9
+ from tests.factories import make_cama
10
+
11
+ PREFIX = "/api/v1/camas"
12
+
13
+
14
+ # ─── Auth / roles ──────────────────────────────────────────────────────────
15
+
16
+ def test_get_camas_sin_token_401(client: TestClient):
17
+ assert client.get(PREFIX).status_code == 401
18
+
19
+
20
+ def test_crear_cama_rol_no_admin_403(client: TestClient, medico_headers):
21
+ payload = {
22
+ "numero": 101, "piso": 1, "sector": "SALA_COMUN",
23
+ "tipo": "ESTANDAR", "hospital_id": "HOSP-001",
24
+ }
25
+ resp = client.post(PREFIX, json=payload, headers=medico_headers)
26
+ assert resp.status_code == 403
27
+
28
+
29
+ # ─── Listado (mapa) ────────────────────────────────────────────────────────
30
+
31
+ def test_get_camas_ok(client: TestClient, medico_headers, monkeypatch):
32
+ monkeypatch.setattr(
33
+ "app.crud.cama.get_all",
34
+ lambda *a, **k: [make_cama(estado="DISPONIBLE"), make_cama(id=102, estado="OCUPADA")],
35
+ )
36
+ resp = client.get(PREFIX, headers=medico_headers)
37
+ assert resp.status_code == 200
38
+ data = resp.json()
39
+ assert data["total"] == 2
40
+ assert data["disponibles"] == 1
41
+ assert data["ocupadas"] == 1
42
 
 
 
 
 
43
 
44
+ # ─── Alta ──────────────────────────────────────────────────────────────────
45
 
46
+ def test_crear_cama_ok(client: TestClient, admin_headers, monkeypatch):
47
+ monkeypatch.setattr("app.crud.cama.create", lambda db, data: make_cama(numero=data.numero))
48
  payload = {
49
+ "numero": 101, "piso": 1, "sector": "SALA_COMUN",
50
+ "tipo": "ESTANDAR", "hospital_id": "HOSP-001",
 
 
 
51
  "contraindicaciones_incompatibles": [],
52
  }
53
+ resp = client.post(PREFIX, json=payload, headers=admin_headers)
54
+ assert resp.status_code == 201
55
+ data = resp.json()
56
+ assert data["numero"] == 101 # integer, no "101"
57
  assert data["estado"] == "DISPONIBLE"
58
+
59
+
60
+ def test_crear_cama_hospital_id_vacio_422(client: TestClient, admin_headers):
61
+ payload = {
62
+ "numero": 101, "piso": 1, "sector": "SALA_COMUN",
63
+ "tipo": "ESTANDAR", "hospital_id": " ",
64
+ }
65
+ resp = client.post(PREFIX, json=payload, headers=admin_headers)
66
+ assert resp.status_code == 422
67
+
68
+
69
+ # ─── Asignación / baja: reglas de estado ───────────────────────────────────
70
+
71
+ def test_asignar_cama_ocupada_409(client: TestClient, admin_headers, monkeypatch):
72
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_cama(estado="OCUPADA"))
73
+ payload = {"tipo": "INGRESO", "paciente_id": 7}
74
+ resp = client.post(f"{PREFIX}/101/asignar", json=payload, headers=admin_headers)
75
+ assert resp.status_code == 409
76
+
77
+
78
+ def test_delete_cama_en_uso_409(client: TestClient, admin_headers, monkeypatch):
79
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_cama(estado="OCUPADA"))
80
+ resp = client.delete(f"{PREFIX}/101", headers=admin_headers)
81
+ assert resp.status_code == 409
82
+
83
+
84
+ def test_delete_cama_ok(client: TestClient, admin_headers, monkeypatch):
85
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_cama(estado="DISPONIBLE"))
86
+ monkeypatch.setattr("app.crud.cama.save", lambda db, cama: cama)
87
+ resp = client.delete(f"{PREFIX}/101", headers=admin_headers)
88
+ assert resp.status_code == 200
89
+ assert resp.json()["estado"] == "BAJA_PERMANENTE"
tests/test_quirofanos.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests del router de Quirófanos.
3
+
4
+ Mockean la capa CRUD (`app.crud.cama` / `app.crud.reserva`) para ejercitar
5
+ routing + auth/roles + reglas de negocio de servicios + serialización, sin DB real.
6
+ """
7
+ from fastapi.testclient import TestClient
8
+
9
+ from tests.factories import make_cama, make_quirofano, make_reserva
10
+
11
+ PREFIX = "/api/v1/quirofanos"
12
+
13
+
14
+ def _reserva_payload(**overrides) -> dict:
15
+ payload = {
16
+ "turno_id": "TURNO-001",
17
+ "paciente_id": 7,
18
+ "medico_cirujano_id": 22,
19
+ "fecha_hora_inicio": "2025-01-18T08:00:00Z",
20
+ "fecha_hora_fin_estimada": "2025-01-18T10:00:00Z",
21
+ "prioridad": "MEDIA",
22
+ }
23
+ payload.update(overrides)
24
+ return payload
25
+
26
+
27
+ # ─── Auth / roles ──────────────────────────────────────────────────────────
28
+
29
+ def test_listar_quirofanos_sin_token_401(client: TestClient):
30
+ assert client.get(PREFIX).status_code == 401
31
+
32
+
33
+ def test_crear_quirofano_rol_no_admin_403(client: TestClient, medico_headers):
34
+ payload = {"numero": 501, "piso": 5, "specialty_id": 43, "hospital_id": "HOSP-001"}
35
+ resp = client.post(PREFIX, json=payload, headers=medico_headers)
36
+ assert resp.status_code == 403
37
+
38
+
39
+ # ─── Listado ───────────────────────────────────────────────────────────────
40
+
41
+ def test_listar_quirofanos_ok(client: TestClient, medico_headers, monkeypatch):
42
+ monkeypatch.setattr("app.crud.cama.get_quirofanos", lambda *a, **k: [make_quirofano()])
43
+ resp = client.get(PREFIX, headers=medico_headers)
44
+ assert resp.status_code == 200
45
+ data = resp.json()
46
+ assert data["total"] == 1
47
+ q = data["quirofanos"][0]
48
+ assert q["id"] == 501
49
+ assert q["numero"] == 501 # integer (decisión changelog #12)
50
+ assert q["specialty_id"] == 43
51
+
52
+
53
+ # ─── Alta ──────────────────────────────────────────────────────────────────
54
+
55
+ def test_crear_quirofano_setea_sector_y_tipo_internos(client: TestClient, admin_headers, monkeypatch):
56
+ capturado = {}
57
+
58
+ def fake_create(db, cama_req):
59
+ capturado["req"] = cama_req
60
+ return make_quirofano(numero=cama_req.numero, piso=cama_req.piso, specialty_id=cama_req.specialty_id)
61
+
62
+ monkeypatch.setattr("app.crud.cama.create", fake_create)
63
+ payload = {"numero": 777, "piso": 5, "specialty_id": 43, "hospital_id": "HOSP-001"}
64
+ resp = client.post(PREFIX, json=payload, headers=admin_headers)
65
+
66
+ assert resp.status_code == 201
67
+ data = resp.json()
68
+ assert data["numero"] == 777
69
+ assert data["estado"] == "DISPONIBLE"
70
+ # El cliente no manda sector/tipo: el servicio los fija
71
+ assert capturado["req"].sector.value == "QUIROFANO"
72
+ assert capturado["req"].tipo.value == "CIRUGIA"
73
+
74
+
75
+ # ─── Detalle ───────────────────────────────────────────────────────────────
76
+
77
+ def test_get_quirofano_ok(client: TestClient, medico_headers, monkeypatch):
78
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_quirofano())
79
+ resp = client.get(f"{PREFIX}/501", headers=medico_headers)
80
+ assert resp.status_code == 200
81
+ assert resp.json()["id"] == 501
82
+
83
+
84
+ def test_get_quirofano_404_si_no_existe(client: TestClient, medico_headers, monkeypatch):
85
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: None)
86
+ resp = client.get(f"{PREFIX}/999", headers=medico_headers)
87
+ assert resp.status_code == 404
88
+
89
+
90
+ def test_get_quirofano_404_si_es_cama_comun(client: TestClient, medico_headers, monkeypatch):
91
+ # Existe la fila pero no es un quirófano → no es recurso /quirofanos
92
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_cama())
93
+ resp = client.get(f"{PREFIX}/101", headers=medico_headers)
94
+ assert resp.status_code == 404
95
+
96
+
97
+ # ─── Update ────────────────────────────────────────────────────────────────
98
+
99
+ def test_patch_quirofano_actualiza_specialty(client: TestClient, admin_headers, monkeypatch):
100
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_quirofano(specialty_id=43))
101
+ monkeypatch.setattr("app.crud.cama.save", lambda db, cama: cama)
102
+ resp = client.patch(f"{PREFIX}/501", json={"specialty_id": 99}, headers=admin_headers)
103
+ assert resp.status_code == 200
104
+ assert resp.json()["specialty_id"] == 99
105
+
106
+
107
+ def test_patch_quirofano_estado_automatico_409(client: TestClient, admin_headers, monkeypatch):
108
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_quirofano())
109
+ monkeypatch.setattr("app.crud.cama.save", lambda db, cama: cama)
110
+ # OCUPADA solo se asigna automáticamente, no por PATCH manual
111
+ resp = client.patch(f"{PREFIX}/501", json={"estado": "OCUPADA"}, headers=admin_headers)
112
+ assert resp.status_code == 409
113
+
114
+
115
+ # ─── Reservas ──────────────────────────────────────────────────────────────
116
+
117
+ def test_crear_reserva_en_cama_no_quirofano_409(client: TestClient, medico_headers, monkeypatch):
118
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_cama()) # SALA_COMUN
119
+ resp = client.post(f"{PREFIX}/101/reservas", json=_reserva_payload(), headers=medico_headers)
120
+ assert resp.status_code == 409
121
+
122
+
123
+ def test_crear_reserva_urgente_rechazada_422(client: TestClient, medico_headers, monkeypatch):
124
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_quirofano())
125
+ resp = client.post(
126
+ f"{PREFIX}/501/reservas",
127
+ json=_reserva_payload(prioridad="URGENTE"),
128
+ headers=medico_headers,
129
+ )
130
+ assert resp.status_code == 422
131
+
132
+
133
+ def test_crear_reserva_fechas_invertidas_422(client: TestClient, medico_headers, monkeypatch):
134
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_quirofano())
135
+ resp = client.post(
136
+ f"{PREFIX}/501/reservas",
137
+ json=_reserva_payload(
138
+ fecha_hora_inicio="2025-01-18T10:00:00Z",
139
+ fecha_hora_fin_estimada="2025-01-18T08:00:00Z",
140
+ ),
141
+ headers=medico_headers,
142
+ )
143
+ assert resp.status_code == 422
144
+
145
+
146
+ def test_crear_reserva_ok_201(client: TestClient, medico_headers, monkeypatch):
147
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_quirofano())
148
+ monkeypatch.setattr("app.crud.reserva.get_activa_por_turno", lambda db, turno: None)
149
+ monkeypatch.setattr("app.crud.reserva.get_superpuestas", lambda *a, **k: [])
150
+ monkeypatch.setattr("app.crud.reserva.create_programada", lambda db, cid, data: make_reserva())
151
+ resp = client.post(f"{PREFIX}/501/reservas", json=_reserva_payload(), headers=medico_headers)
152
+ assert resp.status_code == 201
153
+ assert resp.json()["estado"] == "RESERVADA"
154
+
155
+
156
+ def test_crear_reserva_superpuesta_409(client: TestClient, medico_headers, monkeypatch):
157
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_quirofano())
158
+ monkeypatch.setattr("app.crud.reserva.get_activa_por_turno", lambda db, turno: None)
159
+ monkeypatch.setattr("app.crud.reserva.get_superpuestas", lambda *a, **k: [make_reserva()])
160
+ resp = client.post(f"{PREFIX}/501/reservas", json=_reserva_payload(), headers=medico_headers)
161
+ assert resp.status_code == 409
162
+
163
+
164
+ def test_get_reserva_404(client: TestClient, medico_headers, monkeypatch):
165
+ monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_quirofano())
166
+ monkeypatch.setattr("app.crud.reserva.get_by_cama_and_id", lambda db, cid, rid: None)
167
+ resp = client.get(f"{PREFIX}/501/reservas/999", headers=medico_headers)
168
+ assert resp.status_code == 404
169
+
170
+
171
+ # ─── Disponibilidad ────────────────────────────────────────────────────────
172
+
173
+ def test_disponibilidad_sin_fechas_422(client: TestClient, medico_headers):
174
+ resp = client.get(f"{PREFIX}/disponibilidad", headers=medico_headers)
175
+ assert resp.status_code == 422
176
+
177
+
178
+ def test_disponibilidad_ok(client: TestClient, medico_headers, monkeypatch):
179
+ monkeypatch.setattr("app.crud.cama.get_quirofanos", lambda *a, **k: [make_quirofano()])
180
+ monkeypatch.setattr("app.crud.reserva.get_superpuestas", lambda *a, **k: [])
181
+ resp = client.get(
182
+ f"{PREFIX}/disponibilidad",
183
+ params={"desde": "2025-01-18T08:00:00Z", "hasta": "2025-01-18T18:00:00Z"},
184
+ headers=medico_headers,
185
+ )
186
+ assert resp.status_code == 200
187
+ data = resp.json()
188
+ assert data["total_quirofanos"] == 1
189
+ assert data["quirofanos"][0]["cama_id"] == 501
tests/test_solicitudes.py CHANGED
@@ -1,27 +1,92 @@
1
  """
2
- Tests de integración para el router de solicitudes.
 
 
 
 
3
  """
4
- import pytest
5
  from fastapi.testclient import TestClient
6
 
 
7
 
8
- @pytest.mark.skip(reason="Requiere configurar token de test")
9
- def test_get_solicitudes_sin_auth(client: TestClient):
10
- response = client.get("/api/v1/solicitudes")
11
- assert response.status_code == 401
12
 
13
 
14
- @pytest.mark.skip(reason="Requiere configurar token de test")
15
- def test_recibir_solicitud_webhook(client: TestClient):
16
- from datetime import datetime, timezone
17
  payload = {
18
  "tipo": "INTERNACION",
19
- "solicitud_hce_id": "HCE-001",
20
- "paciente_id": 1,
21
  "medico_solicitante_id": 10,
 
22
  "timestamp": datetime.now(timezone.utc).isoformat(),
23
  }
24
- response = client.post("/api/v1/webhooks/hce/solicitud", json=payload)
25
- assert response.status_code == 200
26
- data = response.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  assert data["estado"] == "PENDIENTE"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ Tests del router de Solicitudes y del webhook entrante de HCE (M1).
3
+
4
+ Mockean la capa CRUD. Se evitan deliberadamente los flujos de aprobación que
5
+ disparan llamadas a módulos externos (Core/HCE/Monitoreo); esos se cubren con
6
+ tests dedicados que mockean la capa de integraciones.
7
  """
8
+ from datetime import datetime, timezone
9
  from fastapi.testclient import TestClient
10
 
11
+ from tests.factories import make_solicitud
12
 
13
+ PREFIX = "/api/v1/solicitudes"
 
 
 
14
 
15
 
16
+ def _webhook_payload(**overrides) -> dict:
 
 
17
  payload = {
18
  "tipo": "INTERNACION",
19
+ "solicitud_hce_id": "HCE-SOL-001",
20
+ "paciente_id": 7,
21
  "medico_solicitante_id": 10,
22
+ "cama_solicitada_id": 101,
23
  "timestamp": datetime.now(timezone.utc).isoformat(),
24
  }
25
+ payload.update(overrides)
26
+ return payload
27
+
28
+
29
+ # ─── Auth / roles ──────────────────────────────────────────────────────────
30
+
31
+ def test_get_solicitudes_sin_token_401(client: TestClient):
32
+ assert client.get(PREFIX).status_code == 401
33
+
34
+
35
+ def test_resolver_solicitud_rol_no_admin_403(client: TestClient, medico_headers):
36
+ resp = client.patch(f"{PREFIX}/SOL-00001", json={"accion": "RECHAZAR"}, headers=medico_headers)
37
+ assert resp.status_code == 403
38
+
39
+
40
+ # ─── Listado / detalle ─────────────────────────────────────────────────────
41
+
42
+ def test_get_solicitudes_ok(client: TestClient, medico_headers, monkeypatch):
43
+ monkeypatch.setattr("app.crud.solicitud.get_all", lambda *a, **k: [make_solicitud()])
44
+ resp = client.get(PREFIX, headers=medico_headers)
45
+ assert resp.status_code == 200
46
+ data = resp.json()
47
+ assert data["total"] == 1
48
+ assert data["solicitudes"][0]["id"] == "SOL-00001"
49
+ assert data["solicitudes"][0]["estado"] == "PENDIENTE"
50
+
51
+
52
+ def test_get_solicitud_404(client: TestClient, medico_headers, monkeypatch):
53
+ monkeypatch.setattr("app.crud.solicitud.get_by_id", lambda db, num: None)
54
+ resp = client.get(f"{PREFIX}/SOL-99999", headers=medico_headers)
55
+ assert resp.status_code == 404
56
+
57
+
58
+ # ─── Resolución ────────────────────────────────────────────────────────────
59
+
60
+ def test_resolver_solicitud_ya_resuelta_409(client: TestClient, admin_headers, monkeypatch):
61
+ monkeypatch.setattr("app.crud.solicitud.get_by_id", lambda db, num: make_solicitud(estado="APROBADA"))
62
+ resp = client.patch(f"{PREFIX}/SOL-00001", json={"accion": "RECHAZAR"}, headers=admin_headers)
63
+ assert resp.status_code == 409
64
+
65
+
66
+ # ─── Webhook entrante (M1 HCE) ─────────────────────────────────────────────
67
+
68
+ def test_recibir_solicitud_webhook_ok(client: TestClient, admin_headers, monkeypatch):
69
+ monkeypatch.setattr("app.crud.solicitud.get_by_hce_id", lambda db, hce_id: None)
70
+ monkeypatch.setattr("app.crud.solicitud.create", lambda db, data: make_solicitud())
71
+ resp = client.post("/api/v1/webhooks/hce/solicitud", json=_webhook_payload(), headers=admin_headers)
72
+ assert resp.status_code == 200
73
+ data = resp.json()
74
  assert data["estado"] == "PENDIENTE"
75
+ assert data["solicitud_id"] == "SOL-00001"
76
+
77
+
78
+ def test_recibir_solicitud_webhook_idempotente(client: TestClient, admin_headers, monkeypatch):
79
+ """Reintento de M1 con el mismo solicitud_hce_id no crea una solicitud nueva."""
80
+ existente = make_solicitud()
81
+ called = {"create": False}
82
+
83
+ def fail_create(db, data):
84
+ called["create"] = True
85
+ return make_solicitud(solicitud_id="SOL-99999")
86
+
87
+ monkeypatch.setattr("app.crud.solicitud.get_by_hce_id", lambda db, hce_id: existente)
88
+ monkeypatch.setattr("app.crud.solicitud.create", fail_create)
89
+ resp = client.post("/api/v1/webhooks/hce/solicitud", json=_webhook_payload(), headers=admin_headers)
90
+ assert resp.status_code == 200
91
+ assert resp.json()["solicitud_id"] == "SOL-00001"
92
+ assert called["create"] is False