File size: 4,385 Bytes
5f12c93 31c8dd6 5f12c93 74ec534 5f12c93 74ec534 5f12c93 f6c0922 244663c 5f12c93 31c8dd6 5f12c93 9223feb 5f12c93 569fa5c 5f12c93 2c5d6e7 5f12c93 244663c f6c0922 5f12c93 74ec534 5f12c93 31c8dd6 5f12c93 0313d17 5f12c93 31c8dd6 5f12c93 31c8dd6 5f12c93 31c8dd6 5f12c93 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | """
Health Grid - Módulo 6: Internación y Gestión de Camas
API REST: http://localhost:8006/api/v1
"""
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from app.config import settings
from app.dependencies import create_access_token
from app.routers import camas, quirofanos, solicitudes, webhooks, auditoria
from app.routers.webhooks import router_turnos
logger = logging.getLogger(__name__)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
# ─── Startup / Shutdown ────────────────────────────────────────────────────
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Conectado a Supabase — listo para operar")
yield
# ─── App ───────────────────────────────────────────────────────────────────
app = FastAPI(
title="Health Grid – Módulo 6: Internación y Gestión de Camas",
description="API REST para gestión de camas hospitalarias y solicitudes de internación.",
version="4.0.0",
lifespan=lifespan,
docs_url="/api/v1/docs",
redoc_url="/api/v1/redoc",
openapi_url="/api/v1/openapi.json",
)
# Cometario pra tests
app.add_middleware(
CORSMiddleware,
allow_origins=settings.allowed_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ─── Prefijo global /api/v1 ────────────────────────────────────────────────
PREFIX = "/api/v1"
app.include_router(camas.router, prefix=PREFIX)
app.include_router(quirofanos.router, prefix=PREFIX)
app.include_router(solicitudes.router, prefix=PREFIX)
app.include_router(webhooks.router, prefix=PREFIX)
app.include_router(router_turnos, prefix=PREFIX)
app.include_router(auditoria.router, prefix=PREFIX)
# ─── Endpoint de auth local (mock de M10 — solo para desarrollo) ───────────
@app.get(
f"{PREFIX}/auth/token",
tags=["Auth (dev)"],
summary="Obtener JWT de desarrollo",
include_in_schema=True,
)
def get_dev_token(usuario: str, password: str):
"""
Solo habilitado si ENVIRONMENT=development.
Genera un JWT de prueba. Roles válidos: ADMINISTRATIVO | MEDICO | LIMPIEZA
"""
if settings.environment != "development":
return JSONResponse(
status_code=404,
content={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "Not Found"},
)
roles_validos = {"ADMINISTRATIVO", "MEDICO", "LIMPIEZA"}
rol = usuario.upper()
if rol not in roles_validos:
return JSONResponse(
status_code=status.HTTP_401_UNAUTHORIZED,
content={
"codigo": "NO_AUTENTICADO",
"mensaje": f"Rol inválido. Usar: {roles_validos}",
},
)
token = create_access_token(sub="1", rol=rol)
return {"access_token": token, "token_type": "bearer", "rol": rol}
# ─── Health check ──────────────────────────────────────────────────────────
@app.get("/health", tags=["Health"])
def health():
return {"status": "ok", "module": "M6 - Internación "}
# ─── Manejadores de errores globales ───────────────────────────────────────
@app.exception_handler(404)
async def not_found_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=404,
content={
"codigo": "RECURSO_NO_ENCONTRADO",
"mensaje": "El recurso solicitado no existe",
},
)
@app.exception_handler(405)
async def method_not_allowed_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=405,
content={
"codigo": "METODO_NO_PERMITIDO",
"mensaje": "Método HTTP no permitido",
},
)
|