Mate11 commited on
Commit Β·
58e4c2a
1
Parent(s): cb554b3
Agregar logging detallado en auth, servicios y routers
Browse files- Middleware HTTP en main.py: loguea cada request/response con mΓ©todo, path, cliente, status y tiempo
- auth/sso-exchange: loguea ticket prefix, roles devueltos por Core, motivo del 403, y Γ©xito con rol asignado
- core_auth: loguea URL, status de respuesta, body en errores, y roles parseados
- dependencies: loguea ausencia de token, campos faltantes en JWT, y denegaciones de require_roles con rol/usuario
- cama_service y solicitud_service: logger agregado con logs en operaciones clave (create, update, asignar, resolver)
- routers camas/solicitudes/quirofanos: logger declarado
- app/dependencies.py +8 -1
- app/integrations/core_auth.py +12 -1
- app/main.py +23 -0
- app/routers/auth.py +22 -1
- app/routers/camas.py +3 -0
- app/routers/quirofanos.py +3 -0
- app/routers/solicitudes.py +3 -0
- app/services/cama_service.py +13 -0
- app/services/solicitud_service.py +28 -0
app/dependencies.py
CHANGED
|
@@ -67,6 +67,7 @@ def get_current_user(
|
|
| 67 |
verificaciΓ³n contra el Core ni lookup de roles en cada request.
|
| 68 |
"""
|
| 69 |
if credentials is None:
|
|
|
|
| 70 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401)
|
| 71 |
|
| 72 |
try:
|
|
@@ -75,6 +76,7 @@ def get_current_user(
|
|
| 75 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401)
|
| 76 |
|
| 77 |
if "sub" not in payload or "rol" not in payload:
|
|
|
|
| 78 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401)
|
| 79 |
|
| 80 |
return payload
|
|
@@ -85,7 +87,12 @@ def require_roles(*roles: str):
|
|
| 85 |
Uso: Depends(require_roles("ADMINISTRATIVO", "MEDICO"))
|
| 86 |
"""
|
| 87 |
def checker(user: dict = Depends(get_current_user)) -> dict:
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=_ERROR_403)
|
| 90 |
return user
|
| 91 |
return checker
|
|
|
|
| 67 |
verificaciΓ³n contra el Core ni lookup de roles en cada request.
|
| 68 |
"""
|
| 69 |
if credentials is None:
|
| 70 |
+
logger.warning("Intento de acceso sin token de autenticaciΓ³n")
|
| 71 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401)
|
| 72 |
|
| 73 |
try:
|
|
|
|
| 76 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401)
|
| 77 |
|
| 78 |
if "sub" not in payload or "rol" not in payload:
|
| 79 |
+
logger.warning("Token vΓ‘lido pero sin campos requeridos (sub/rol) β payload keys: %s", list(payload.keys()))
|
| 80 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401)
|
| 81 |
|
| 82 |
return payload
|
|
|
|
| 87 |
Uso: Depends(require_roles("ADMINISTRATIVO", "MEDICO"))
|
| 88 |
"""
|
| 89 |
def checker(user: dict = Depends(get_current_user)) -> dict:
|
| 90 |
+
user_rol = user.get("rol")
|
| 91 |
+
if user_rol not in roles:
|
| 92 |
+
logger.warning(
|
| 93 |
+
"Acceso denegado (403) β user_id=%s rol=%s requiere uno de %s",
|
| 94 |
+
user.get("sub"), user_rol, roles,
|
| 95 |
+
)
|
| 96 |
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=_ERROR_403)
|
| 97 |
return user
|
| 98 |
return checker
|
app/integrations/core_auth.py
CHANGED
|
@@ -44,19 +44,30 @@ def exchange_sso_ticket(ticket: str) -> dict:
|
|
| 44 |
M6, sin necesidad de un lookup aparte.
|
| 45 |
"""
|
| 46 |
url = f"{settings.m10_core_url}/auth/sso-exchange"
|
|
|
|
| 47 |
try:
|
| 48 |
r = httpx.post(url, json={"ticket": ticket}, timeout=settings.http_timeout_seconds)
|
| 49 |
except httpx.HTTPError as e:
|
|
|
|
| 50 |
raise SSOExchangeError("No se pudo contactar al Core para el canje SSO") from e
|
| 51 |
|
|
|
|
|
|
|
| 52 |
if r.status_code == 401:
|
|
|
|
| 53 |
raise SSOTicketInvalid("Ticket invΓ‘lido, ya usado o expirado")
|
| 54 |
if r.status_code == 400:
|
|
|
|
| 55 |
raise SSOTicketInvalid("Falta el ticket en el request")
|
| 56 |
if r.status_code >= 400:
|
|
|
|
| 57 |
raise SSOExchangeError(f"El Core respondiΓ³ {r.status_code} al canjear el ticket SSO")
|
| 58 |
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
|
| 62 |
def request_sso_ticket(core_token: str) -> dict:
|
|
|
|
| 44 |
M6, sin necesidad de un lookup aparte.
|
| 45 |
"""
|
| 46 |
url = f"{settings.m10_core_url}/auth/sso-exchange"
|
| 47 |
+
logger.info("Enviando canje SSO al Core β url=%s", url)
|
| 48 |
try:
|
| 49 |
r = httpx.post(url, json={"ticket": ticket}, timeout=settings.http_timeout_seconds)
|
| 50 |
except httpx.HTTPError as e:
|
| 51 |
+
logger.error("Error de red al contactar Core para canje SSO: %s", e)
|
| 52 |
raise SSOExchangeError("No se pudo contactar al Core para el canje SSO") from e
|
| 53 |
|
| 54 |
+
logger.info("Core respondiΓ³ al canje SSO β status=%d", r.status_code)
|
| 55 |
+
|
| 56 |
if r.status_code == 401:
|
| 57 |
+
logger.warning("Core rechazΓ³ el ticket SSO (401) β body: %s", r.text[:500])
|
| 58 |
raise SSOTicketInvalid("Ticket invΓ‘lido, ya usado o expirado")
|
| 59 |
if r.status_code == 400:
|
| 60 |
+
logger.warning("Core rechazΓ³ el request SSO (400) β body: %s", r.text[:500])
|
| 61 |
raise SSOTicketInvalid("Falta el ticket en el request")
|
| 62 |
if r.status_code >= 400:
|
| 63 |
+
logger.error("Core respondiΓ³ error %d al canjear ticket SSO β body: %s", r.status_code, r.text[:500])
|
| 64 |
raise SSOExchangeError(f"El Core respondiΓ³ {r.status_code} al canjear el ticket SSO")
|
| 65 |
|
| 66 |
+
data = r.json()
|
| 67 |
+
core_user = data.get("user") or {}
|
| 68 |
+
role_names = [role.get("name") for role in (core_user.get("roles") or []) if role.get("name")]
|
| 69 |
+
logger.debug("Respuesta Core SSO β user_id=%s roles=%s", core_user.get("id"), role_names)
|
| 70 |
+
return data
|
| 71 |
|
| 72 |
|
| 73 |
def request_sso_ticket(core_token: str) -> dict:
|
app/main.py
CHANGED
|
@@ -6,6 +6,7 @@ API REST: http://localhost:8006/api/v1
|
|
| 6 |
import asyncio
|
| 7 |
import contextlib
|
| 8 |
import logging
|
|
|
|
| 9 |
from contextlib import asynccontextmanager
|
| 10 |
from fastapi import Depends, FastAPI, Request, status
|
| 11 |
from fastapi.middleware.cors import CORSMiddleware
|
|
@@ -66,6 +67,28 @@ app.add_middleware(
|
|
| 66 |
allow_headers=["*"],
|
| 67 |
)
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
# βββ Prefijo global /api/v1 ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 70 |
|
| 71 |
PREFIX = "/api/v1"
|
|
|
|
| 6 |
import asyncio
|
| 7 |
import contextlib
|
| 8 |
import logging
|
| 9 |
+
import time
|
| 10 |
from contextlib import asynccontextmanager
|
| 11 |
from fastapi import Depends, FastAPI, Request, status
|
| 12 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 67 |
allow_headers=["*"],
|
| 68 |
)
|
| 69 |
|
| 70 |
+
# βββ Middleware de logging βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@app.middleware("http")
|
| 74 |
+
async def log_requests(request: Request, call_next):
|
| 75 |
+
start = time.perf_counter()
|
| 76 |
+
client = request.client.host if request.client else "unknown"
|
| 77 |
+
logger.info(
|
| 78 |
+
"β %s %s cliente=%s",
|
| 79 |
+
request.method, request.url.path, client,
|
| 80 |
+
)
|
| 81 |
+
response = await call_next(request)
|
| 82 |
+
elapsed_ms = (time.perf_counter() - start) * 1000
|
| 83 |
+
level = logging.WARNING if response.status_code >= 400 else logging.INFO
|
| 84 |
+
logger.log(
|
| 85 |
+
level,
|
| 86 |
+
"β %s %s status=%d %.1fms",
|
| 87 |
+
request.method, request.url.path, response.status_code, elapsed_ms,
|
| 88 |
+
)
|
| 89 |
+
return response
|
| 90 |
+
|
| 91 |
+
|
| 92 |
# βββ Prefijo global /api/v1 ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 93 |
|
| 94 |
PREFIX = "/api/v1"
|
app/routers/auth.py
CHANGED
|
@@ -62,27 +62,48 @@ _ERROR_401_CORE_TOKEN = {
|
|
| 62 |
},
|
| 63 |
)
|
| 64 |
def sso_exchange(data: SSOExchangeRequest):
|
|
|
|
|
|
|
|
|
|
| 65 |
if not settings.sso_enabled:
|
|
|
|
| 66 |
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=_ERROR_404)
|
| 67 |
|
| 68 |
try:
|
| 69 |
resp = core_auth.exchange_sso_ticket(data.ticket)
|
| 70 |
except core_auth.SSOTicketInvalid:
|
|
|
|
| 71 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401_TICKET)
|
| 72 |
except core_auth.SSOExchangeError as e:
|
| 73 |
-
logger.warning("
|
| 74 |
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=_ERROR_502)
|
| 75 |
|
| 76 |
core_user = resp.get("user") or {}
|
|
|
|
|
|
|
| 77 |
role_names = [r["name"] for r in (core_user.get("roles") or []) if r.get("name")]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
rol = core_auth.map_core_roles_to_internal(role_names)
|
| 79 |
if rol is None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=_ERROR_403_ROL)
|
| 81 |
|
| 82 |
core_token = resp.get("token")
|
| 83 |
token = create_access_token(
|
| 84 |
sub=str(core_user["id"]), rol=rol, extra={"core_token": core_token} if core_token else None,
|
| 85 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
return SSOExchangeResponse(
|
| 87 |
token=token,
|
| 88 |
user=SSOUser(
|
|
|
|
| 62 |
},
|
| 63 |
)
|
| 64 |
def sso_exchange(data: SSOExchangeRequest):
|
| 65 |
+
ticket_prefix = data.ticket[:8] + "β¦" if data.ticket else "(vacΓo)"
|
| 66 |
+
logger.info("SSO exchange solicitado β ticket: %s", ticket_prefix)
|
| 67 |
+
|
| 68 |
if not settings.sso_enabled:
|
| 69 |
+
logger.warning("SSO exchange rechazado β SSO_ENABLED=false")
|
| 70 |
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=_ERROR_404)
|
| 71 |
|
| 72 |
try:
|
| 73 |
resp = core_auth.exchange_sso_ticket(data.ticket)
|
| 74 |
except core_auth.SSOTicketInvalid:
|
| 75 |
+
logger.warning("SSO exchange fallido β ticket invΓ‘lido/expirado (ticket: %s)", ticket_prefix)
|
| 76 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401_TICKET)
|
| 77 |
except core_auth.SSOExchangeError as e:
|
| 78 |
+
logger.warning("SSO exchange fallido β error de comunicaciΓ³n con Core: %s", e)
|
| 79 |
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=_ERROR_502)
|
| 80 |
|
| 81 |
core_user = resp.get("user") or {}
|
| 82 |
+
user_id = core_user.get("id")
|
| 83 |
+
user_email = core_user.get("email", "(sin email)")
|
| 84 |
role_names = [r["name"] for r in (core_user.get("roles") or []) if r.get("name")]
|
| 85 |
+
logger.info(
|
| 86 |
+
"Core respondiΓ³ OK β user_id=%s email=%s roles_core=%s",
|
| 87 |
+
user_id, user_email, role_names,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
rol = core_auth.map_core_roles_to_internal(role_names)
|
| 91 |
if rol is None:
|
| 92 |
+
logger.warning(
|
| 93 |
+
"SSO exchange denegado (403) β user_id=%s email=%s roles_core=%s "
|
| 94 |
+
"no mapean a ningΓΊn rol de M6. Roles conocidos: %s",
|
| 95 |
+
user_id, user_email, role_names, list(core_auth.CORE_ROLE_TO_INTERNAL.keys()),
|
| 96 |
+
)
|
| 97 |
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=_ERROR_403_ROL)
|
| 98 |
|
| 99 |
core_token = resp.get("token")
|
| 100 |
token = create_access_token(
|
| 101 |
sub=str(core_user["id"]), rol=rol, extra={"core_token": core_token} if core_token else None,
|
| 102 |
)
|
| 103 |
+
logger.info(
|
| 104 |
+
"SSO exchange exitoso β user_id=%s email=%s rol_m6=%s core_token=%s",
|
| 105 |
+
user_id, user_email, rol, "presente" if core_token else "ausente",
|
| 106 |
+
)
|
| 107 |
return SSOExchangeResponse(
|
| 108 |
token=token,
|
| 109 |
user=SSOUser(
|
app/routers/camas.py
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
|
|
| 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
|
|
|
|
|
|
|
| 6 |
from app.schemas.cama import (
|
| 7 |
CamaCreateRequest,
|
| 8 |
CamaUpdateRequest,
|
|
|
|
| 1 |
+
import logging
|
| 2 |
from typing import Optional
|
| 3 |
from fastapi import APIRouter, Depends, Query, status
|
| 4 |
from supabase import Client
|
| 5 |
|
| 6 |
from app.dependencies import get_db, require_roles
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
from app.schemas.cama import (
|
| 10 |
CamaCreateRequest,
|
| 11 |
CamaUpdateRequest,
|
app/routers/quirofanos.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
from datetime import datetime
|
| 2 |
from typing import Optional
|
| 3 |
from fastapi import APIRouter, Depends, Query, status
|
|
@@ -5,6 +6,8 @@ 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,
|
|
|
|
| 1 |
+
import logging
|
| 2 |
from datetime import datetime
|
| 3 |
from typing import Optional
|
| 4 |
from fastapi import APIRouter, Depends, Query, status
|
|
|
|
| 6 |
from supabase import Client
|
| 7 |
|
| 8 |
from app.dependencies import get_db, require_roles
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
from app.schemas.cama import (
|
| 12 |
QuirofanoCreateRequest,
|
| 13 |
QuirofanoUpdateRequest,
|
app/routers/solicitudes.py
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
|
|
| 1 |
from typing import Optional
|
| 2 |
from fastapi import APIRouter, Depends, Query
|
| 3 |
from supabase import Client
|
| 4 |
|
| 5 |
from app.dependencies import get_db, require_roles
|
|
|
|
|
|
|
| 6 |
from app.schemas.solicitud import SolicitudResponse, SolicitudesListResponse, SolicitudResolucionRequest
|
| 7 |
from app.schemas.enums import EstadoSolicitudEnum, TipoSolicitudEnum
|
| 8 |
from app.services import solicitud_service
|
|
|
|
| 1 |
+
import logging
|
| 2 |
from typing import Optional
|
| 3 |
from fastapi import APIRouter, Depends, Query
|
| 4 |
from supabase import Client
|
| 5 |
|
| 6 |
from app.dependencies import get_db, require_roles
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
from app.schemas.solicitud import SolicitudResponse, SolicitudesListResponse, SolicitudResolucionRequest
|
| 10 |
from app.schemas.enums import EstadoSolicitudEnum, TipoSolicitudEnum
|
| 11 |
from app.services import solicitud_service
|
app/services/cama_service.py
CHANGED
|
@@ -2,10 +2,13 @@
|
|
| 2 |
LΓ³gica de negocio para Camas y Reservas de QuirΓ³fano.
|
| 3 |
"""
|
| 4 |
from __future__ import annotations
|
|
|
|
| 5 |
from datetime import datetime, timedelta, timezone
|
| 6 |
from fastapi import HTTPException
|
| 7 |
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 (
|
|
@@ -73,7 +76,9 @@ def get_camas(
|
|
| 73 |
|
| 74 |
|
| 75 |
def create_cama(db: Client, data: CamaCreateRequest, actor: dict | None = None) -> Cama:
|
|
|
|
| 76 |
cama = cama_crud.create(db, data)
|
|
|
|
| 77 |
auditoria_crud.registrar(
|
| 78 |
db,
|
| 79 |
entidad=EntidadAuditoriaEnum.CAMA.value,
|
|
@@ -95,10 +100,12 @@ def get_cama(db: Client, cama_id: int) -> Cama:
|
|
| 95 |
def update_cama(
|
| 96 |
db: Client, cama_id: int, data: CamaUpdateRequest, rol: str, actor: dict | None = None
|
| 97 |
) -> Cama:
|
|
|
|
| 98 |
cama = _get_cama_or_404(db, cama_id)
|
| 99 |
estado_previo = cama.estado
|
| 100 |
|
| 101 |
if rol == "LIMPIEZA" and data.contraindicaciones_incompatibles is not None:
|
|
|
|
| 102 |
raise HTTPException(
|
| 103 |
status_code=403,
|
| 104 |
detail={
|
|
@@ -161,6 +168,7 @@ def update_cama(
|
|
| 161 |
cama = cama_crud.save(db, cama)
|
| 162 |
|
| 163 |
if data.estado is not None and cama.estado != estado_previo:
|
|
|
|
| 164 |
auditoria_crud.registrar(
|
| 165 |
db,
|
| 166 |
entidad=EntidadAuditoriaEnum.CAMA.value,
|
|
@@ -220,9 +228,14 @@ def asignar_cama(
|
|
| 220 |
db: Client, cama_id: int, tipo: str, paciente_id: int, cama_origen_id: int | None,
|
| 221 |
actor: dict | None = None,
|
| 222 |
) -> Cama:
|
|
|
|
| 223 |
cama_destino = _get_cama_or_404(db, cama_id)
|
| 224 |
|
| 225 |
if cama_destino.estado != EstadoCamaEnum.DISPONIBLE.value:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
raise HTTPException(
|
| 227 |
status_code=409,
|
| 228 |
detail={
|
|
|
|
| 2 |
LΓ³gica de negocio para Camas y Reservas de QuirΓ³fano.
|
| 3 |
"""
|
| 4 |
from __future__ import annotations
|
| 5 |
+
import logging
|
| 6 |
from datetime import datetime, timedelta, timezone
|
| 7 |
from fastapi import HTTPException
|
| 8 |
from supabase import Client
|
| 9 |
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
from app.models.cama import Cama
|
| 13 |
from app.models.reserva import ReservaQuirofano
|
| 14 |
from app.schemas.cama import (
|
|
|
|
| 76 |
|
| 77 |
|
| 78 |
def create_cama(db: Client, data: CamaCreateRequest, actor: dict | None = None) -> Cama:
|
| 79 |
+
logger.info("Creando cama numero=%s sector=%s tipo=%s", data.numero, data.sector, data.tipo)
|
| 80 |
cama = cama_crud.create(db, data)
|
| 81 |
+
logger.info("Cama creada β id=%s numero=%s", cama.id, cama.numero)
|
| 82 |
auditoria_crud.registrar(
|
| 83 |
db,
|
| 84 |
entidad=EntidadAuditoriaEnum.CAMA.value,
|
|
|
|
| 100 |
def update_cama(
|
| 101 |
db: Client, cama_id: int, data: CamaUpdateRequest, rol: str, actor: dict | None = None
|
| 102 |
) -> Cama:
|
| 103 |
+
logger.info("Actualizando cama id=%s rol=%s nuevo_estado=%s", cama_id, rol, data.estado)
|
| 104 |
cama = _get_cama_or_404(db, cama_id)
|
| 105 |
estado_previo = cama.estado
|
| 106 |
|
| 107 |
if rol == "LIMPIEZA" and data.contraindicaciones_incompatibles is not None:
|
| 108 |
+
logger.warning("Intento de modificar contraindicaciones por rol LIMPIEZA β cama_id=%s", cama_id)
|
| 109 |
raise HTTPException(
|
| 110 |
status_code=403,
|
| 111 |
detail={
|
|
|
|
| 168 |
cama = cama_crud.save(db, cama)
|
| 169 |
|
| 170 |
if data.estado is not None and cama.estado != estado_previo:
|
| 171 |
+
logger.info("Cama id=%s: %s β %s", cama.id, estado_previo, cama.estado)
|
| 172 |
auditoria_crud.registrar(
|
| 173 |
db,
|
| 174 |
entidad=EntidadAuditoriaEnum.CAMA.value,
|
|
|
|
| 228 |
db: Client, cama_id: int, tipo: str, paciente_id: int, cama_origen_id: int | None,
|
| 229 |
actor: dict | None = None,
|
| 230 |
) -> Cama:
|
| 231 |
+
logger.info("Asignando cama id=%s tipo=%s paciente_id=%s", cama_id, tipo, paciente_id)
|
| 232 |
cama_destino = _get_cama_or_404(db, cama_id)
|
| 233 |
|
| 234 |
if cama_destino.estado != EstadoCamaEnum.DISPONIBLE.value:
|
| 235 |
+
logger.warning(
|
| 236 |
+
"Cama id=%s no disponible para asignaciΓ³n β estado_actual=%s",
|
| 237 |
+
cama_id, cama_destino.estado,
|
| 238 |
+
)
|
| 239 |
raise HTTPException(
|
| 240 |
status_code=409,
|
| 241 |
detail={
|
app/services/solicitud_service.py
CHANGED
|
@@ -2,10 +2,13 @@
|
|
| 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 supabase import Client
|
| 8 |
|
|
|
|
|
|
|
| 9 |
from app.models.solicitud import Solicitud
|
| 10 |
from app.models.cama import Cama
|
| 11 |
from app.models.reserva import ReservaQuirofano
|
|
@@ -73,10 +76,16 @@ def _verificar_contraindicaciones(paciente_id: int, cama: Cama) -> None:
|
|
| 73 |
# βββ Recibir solicitud desde HCE (M1) βββββββββββββββββββββββββββββββββββββ
|
| 74 |
|
| 75 |
def recibir_solicitud(db: Client, data: SolicitudHceWebhook) -> Solicitud:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
existing = solicitud_crud.get_by_hce_id(db, data.solicitud_hce_id)
|
| 77 |
if existing:
|
|
|
|
| 78 |
return existing
|
| 79 |
sol = solicitud_crud.create(db, data)
|
|
|
|
| 80 |
auditoria_crud.registrar(
|
| 81 |
db,
|
| 82 |
entidad=EntidadAuditoriaEnum.SOLICITUD.value,
|
|
@@ -117,9 +126,17 @@ def resolver_solicitud(
|
|
| 117 |
resuelto_por: int,
|
| 118 |
actor: dict | None = None,
|
| 119 |
) -> Solicitud:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
sol = _get_solicitud_or_404(db, solicitud_id)
|
| 121 |
|
| 122 |
if sol.estado != "PENDIENTE":
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
raise HTTPException(
|
| 124 |
status_code=409,
|
| 125 |
detail={
|
|
@@ -130,6 +147,7 @@ def resolver_solicitud(
|
|
| 130 |
)
|
| 131 |
|
| 132 |
accion = data.accion.value
|
|
|
|
| 133 |
|
| 134 |
if accion == "RECHAZAR":
|
| 135 |
_rechazar(db, sol, data.motivo, resuelto_por, actor)
|
|
@@ -153,6 +171,7 @@ def resolver_solicitud(
|
|
| 153 |
def _rechazar(
|
| 154 |
db: Client, sol: Solicitud, motivo: str | None, resuelto_por: int, actor: dict | None = None
|
| 155 |
) -> None:
|
|
|
|
| 156 |
sol.estado = "RECHAZADA"
|
| 157 |
sol.accion = "RECHAZAR"
|
| 158 |
sol.motivo = motivo
|
|
@@ -179,8 +198,13 @@ def _aprobar_internacion(
|
|
| 179 |
db: Client, sol: Solicitud, cama_id: int, motivo: str | None, resuelto_por: int,
|
| 180 |
accion: str, actor: dict | None = None,
|
| 181 |
) -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
paciente = core.validate_patient(sol.paciente_id)
|
| 183 |
if not paciente:
|
|
|
|
| 184 |
raise HTTPException(
|
| 185 |
status_code=502,
|
| 186 |
detail={"codigo": "SERVICIO_EXTERNO_NO_DISPONIBLE", "mensaje": "No se pudo validar el paciente en Core (M10)"},
|
|
@@ -188,6 +212,10 @@ def _aprobar_internacion(
|
|
| 188 |
|
| 189 |
cama = _get_cama_or_404(db, cama_id)
|
| 190 |
if cama.estado != EstadoCamaEnum.DISPONIBLE.value:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
raise HTTPException(
|
| 192 |
status_code=409,
|
| 193 |
detail={"codigo": "CAMA_NO_DISPONIBLE", "mensaje": f"La cama {cama_id} no estΓ‘ disponible"},
|
|
|
|
| 2 |
LΓ³gica de negocio para Solicitudes de InternaciΓ³n / Traslado.
|
| 3 |
"""
|
| 4 |
from __future__ import annotations
|
| 5 |
+
import logging
|
| 6 |
from datetime import datetime, timezone
|
| 7 |
from fastapi import HTTPException
|
| 8 |
from supabase import Client
|
| 9 |
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
from app.models.solicitud import Solicitud
|
| 13 |
from app.models.cama import Cama
|
| 14 |
from app.models.reserva import ReservaQuirofano
|
|
|
|
| 76 |
# βββ Recibir solicitud desde HCE (M1) βββββββββββββββββββββββββββββββββββββ
|
| 77 |
|
| 78 |
def recibir_solicitud(db: Client, data: SolicitudHceWebhook) -> Solicitud:
|
| 79 |
+
logger.info(
|
| 80 |
+
"Recibiendo solicitud HCE β solicitud_hce_id=%s tipo=%s paciente_id=%s",
|
| 81 |
+
data.solicitud_hce_id, data.tipo, data.paciente_id,
|
| 82 |
+
)
|
| 83 |
existing = solicitud_crud.get_by_hce_id(db, data.solicitud_hce_id)
|
| 84 |
if existing:
|
| 85 |
+
logger.info("Solicitud duplicada (idempotente) β solicitud_hce_id=%s id=%s", data.solicitud_hce_id, existing.solicitud_id)
|
| 86 |
return existing
|
| 87 |
sol = solicitud_crud.create(db, data)
|
| 88 |
+
logger.info("Solicitud creada β id=%s tipo=%s paciente_id=%s", sol.solicitud_id, sol.tipo, sol.paciente_id)
|
| 89 |
auditoria_crud.registrar(
|
| 90 |
db,
|
| 91 |
entidad=EntidadAuditoriaEnum.SOLICITUD.value,
|
|
|
|
| 126 |
resuelto_por: int,
|
| 127 |
actor: dict | None = None,
|
| 128 |
) -> Solicitud:
|
| 129 |
+
logger.info(
|
| 130 |
+
"Resolviendo solicitud id=%s accion=%s resuelto_por=%s",
|
| 131 |
+
solicitud_id, data.accion, resuelto_por,
|
| 132 |
+
)
|
| 133 |
sol = _get_solicitud_or_404(db, solicitud_id)
|
| 134 |
|
| 135 |
if sol.estado != "PENDIENTE":
|
| 136 |
+
logger.warning(
|
| 137 |
+
"Solicitud id=%s no resoluble β estado_actual=%s accion_intentada=%s",
|
| 138 |
+
solicitud_id, sol.estado, data.accion,
|
| 139 |
+
)
|
| 140 |
raise HTTPException(
|
| 141 |
status_code=409,
|
| 142 |
detail={
|
|
|
|
| 147 |
)
|
| 148 |
|
| 149 |
accion = data.accion.value
|
| 150 |
+
logger.info("Solicitud id=%s en estado PENDIENTE β procesando accion=%s", solicitud_id, accion)
|
| 151 |
|
| 152 |
if accion == "RECHAZAR":
|
| 153 |
_rechazar(db, sol, data.motivo, resuelto_por, actor)
|
|
|
|
| 171 |
def _rechazar(
|
| 172 |
db: Client, sol: Solicitud, motivo: str | None, resuelto_por: int, actor: dict | None = None
|
| 173 |
) -> None:
|
| 174 |
+
logger.info("Rechazando solicitud id=%s motivo=%s", sol.solicitud_id, motivo)
|
| 175 |
sol.estado = "RECHAZADA"
|
| 176 |
sol.accion = "RECHAZAR"
|
| 177 |
sol.motivo = motivo
|
|
|
|
| 198 |
db: Client, sol: Solicitud, cama_id: int, motivo: str | None, resuelto_por: int,
|
| 199 |
accion: str, actor: dict | None = None,
|
| 200 |
) -> None:
|
| 201 |
+
logger.info(
|
| 202 |
+
"Aprobando internaciΓ³n β solicitud_id=%s paciente_id=%s cama_id=%s",
|
| 203 |
+
sol.solicitud_id, sol.paciente_id, cama_id,
|
| 204 |
+
)
|
| 205 |
paciente = core.validate_patient(sol.paciente_id)
|
| 206 |
if not paciente:
|
| 207 |
+
logger.warning("ValidaciΓ³n de paciente fallida en Core β paciente_id=%s", sol.paciente_id)
|
| 208 |
raise HTTPException(
|
| 209 |
status_code=502,
|
| 210 |
detail={"codigo": "SERVICIO_EXTERNO_NO_DISPONIBLE", "mensaje": "No se pudo validar el paciente en Core (M10)"},
|
|
|
|
| 212 |
|
| 213 |
cama = _get_cama_or_404(db, cama_id)
|
| 214 |
if cama.estado != EstadoCamaEnum.DISPONIBLE.value:
|
| 215 |
+
logger.warning(
|
| 216 |
+
"Cama id=%s no disponible para internaciΓ³n β estado_actual=%s",
|
| 217 |
+
cama_id, cama.estado,
|
| 218 |
+
)
|
| 219 |
raise HTTPException(
|
| 220 |
status_code=409,
|
| 221 |
detail={"codigo": "CAMA_NO_DISPONIBLE", "mensaje": f"La cama {cama_id} no estΓ‘ disponible"},
|