Merge cambios JP
Browse files- .github/workflows/ci.yml +2 -1
- .gitignore +4 -0
- CLAUDE.md +176 -0
- app/config.py +3 -2
- app/crud/cama.py +60 -49
- app/crud/reserva.py +108 -84
- app/crud/solicitud.py +49 -39
- app/dependencies.py +5 -25
- app/main.py +2 -8
- app/models/cama.py +53 -18
- app/models/reserva.py +58 -40
- app/models/solicitud.py +89 -52
- app/routers/camas.py +12 -12
- app/routers/solicitudes.py +4 -4
- app/routers/webhooks.py +7 -7
- app/services/cama_service.py +20 -23
- app/services/solicitud_service.py +16 -14
- openapi.yaml +0 -0
- requirements.txt +1 -12
- tests/conftest.py +9 -35
.github/workflows/ci.yml
CHANGED
|
@@ -27,7 +27,8 @@ jobs:
|
|
| 27 |
name: Tests (pytest)
|
| 28 |
runs-on: ubuntu-latest
|
| 29 |
env:
|
| 30 |
-
|
|
|
|
| 31 |
JWT_SECRET: ci-test-secret-key-not-used-in-production-32chars
|
| 32 |
ENVIRONMENT: development
|
| 33 |
MOCK_EXTERNAL_SERVICES: "true"
|
|
|
|
| 27 |
name: Tests (pytest)
|
| 28 |
runs-on: ubuntu-latest
|
| 29 |
env:
|
| 30 |
+
SUPABASE_URL: https://mock.supabase.co
|
| 31 |
+
SUPABASE_KEY: mock-key-for-testing-only
|
| 32 |
JWT_SECRET: ci-test-secret-key-not-used-in-production-32chars
|
| 33 |
ENVIRONMENT: development
|
| 34 |
MOCK_EXTERNAL_SERVICES: "true"
|
.gitignore
CHANGED
|
@@ -216,3 +216,7 @@ __marimo__/
|
|
| 216 |
|
| 217 |
# Streamlit
|
| 218 |
.streamlit/secrets.toml
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
# Streamlit
|
| 218 |
.streamlit/secrets.toml
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
.claude/
|
| 222 |
+
.claude-flow/
|
CLAUDE.md
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Ruflo — Claude Code Configuration
|
| 2 |
+
|
| 3 |
+
## Rules
|
| 4 |
+
|
| 5 |
+
- Do what has been asked; nothing more, nothing less
|
| 6 |
+
- NEVER create files unless absolutely necessary — prefer editing existing files
|
| 7 |
+
- NEVER create documentation files unless explicitly requested
|
| 8 |
+
- NEVER save working files or tests to root — use `/src`, `/tests`, `/docs`, `/config`, `/scripts`
|
| 9 |
+
- ALWAYS read a file before editing it
|
| 10 |
+
- NEVER commit secrets, credentials, or .env files
|
| 11 |
+
- NEVER add a `Co-Authored-By` trailer to user commits unless this project's `.claude/settings.json` has `attribution.commit` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. `Co-Authored-By` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author.
|
| 12 |
+
- Keep files under 500 lines
|
| 13 |
+
- Validate input at system boundaries
|
| 14 |
+
|
| 15 |
+
## Agent Comms (SendMessage-First Coordination)
|
| 16 |
+
|
| 17 |
+
Named agents coordinate via `SendMessage`, not polling or shared state.
|
| 18 |
+
|
| 19 |
+
```
|
| 20 |
+
Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer
|
| 21 |
+
(named agents message each other directly)
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
### Spawning a Coordinated Team
|
| 25 |
+
|
| 26 |
+
```javascript
|
| 27 |
+
// ALL agents in ONE message, each knows WHO to message next
|
| 28 |
+
Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.",
|
| 29 |
+
subagent_type: "researcher", name: "researcher", run_in_background: true })
|
| 30 |
+
Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.",
|
| 31 |
+
subagent_type: "system-architect", name: "architect", run_in_background: true })
|
| 32 |
+
Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.",
|
| 33 |
+
subagent_type: "coder", name: "coder", run_in_background: true })
|
| 34 |
+
Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.",
|
| 35 |
+
subagent_type: "tester", name: "tester", run_in_background: true })
|
| 36 |
+
Agent({ prompt: "Wait for 'tester'. Review code quality and security.",
|
| 37 |
+
subagent_type: "reviewer", name: "reviewer", run_in_background: true })
|
| 38 |
+
|
| 39 |
+
// Kick off the pipeline
|
| 40 |
+
SendMessage({ to: "researcher", summary: "Start", message: "[task context]" })
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
### Patterns
|
| 44 |
+
|
| 45 |
+
| Pattern | Flow | Use When |
|
| 46 |
+
|---------|------|----------|
|
| 47 |
+
| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) |
|
| 48 |
+
| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) |
|
| 49 |
+
| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) |
|
| 50 |
+
|
| 51 |
+
### Rules
|
| 52 |
+
|
| 53 |
+
- ALWAYS name agents — `name: "role"` makes them addressable
|
| 54 |
+
- ALWAYS include comms instructions in prompts — who to message, what to send
|
| 55 |
+
- Spawn ALL agents in ONE message with `run_in_background: true`
|
| 56 |
+
- After spawning: STOP, tell user what's running, wait for results
|
| 57 |
+
- NEVER poll status — agents message back or complete automatically
|
| 58 |
+
|
| 59 |
+
## Swarm & Routing
|
| 60 |
+
|
| 61 |
+
### Config
|
| 62 |
+
- **Topology**: hierarchical-mesh (anti-drift)
|
| 63 |
+
- **Max Agents**: 15
|
| 64 |
+
- **Memory**: hybrid
|
| 65 |
+
- **HNSW**: Enabled
|
| 66 |
+
- **Neural**: Enabled
|
| 67 |
+
|
| 68 |
+
```bash
|
| 69 |
+
npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
### Agent Routing
|
| 73 |
+
|
| 74 |
+
| Task | Agents | Topology |
|
| 75 |
+
|------|--------|----------|
|
| 76 |
+
| Bug Fix | researcher, coder, tester | hierarchical |
|
| 77 |
+
| Feature | architect, coder, tester, reviewer | hierarchical |
|
| 78 |
+
| Refactor | architect, coder, reviewer | hierarchical |
|
| 79 |
+
| Performance | perf-engineer, coder | hierarchical |
|
| 80 |
+
| Security | security-architect, auditor | hierarchical |
|
| 81 |
+
|
| 82 |
+
### When to Swarm
|
| 83 |
+
- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance
|
| 84 |
+
- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions
|
| 85 |
+
|
| 86 |
+
### 3-Tier Model Routing
|
| 87 |
+
|
| 88 |
+
| Tier | Handler | Use Cases |
|
| 89 |
+
|------|---------|-----------|
|
| 90 |
+
| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly |
|
| 91 |
+
| 2 | Haiku | Simple tasks, low complexity |
|
| 92 |
+
| 3 | Sonnet/Opus | Architecture, security, complex reasoning |
|
| 93 |
+
|
| 94 |
+
## Memory & Learning
|
| 95 |
+
|
| 96 |
+
### Before Any Task
|
| 97 |
+
```bash
|
| 98 |
+
npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns
|
| 99 |
+
npx @claude-flow/cli@latest hooks route --task "[task description]"
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
### After Success
|
| 103 |
+
```bash
|
| 104 |
+
npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]"
|
| 105 |
+
npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
### MCP Tools (use `ToolSearch("keyword")` to discover)
|
| 109 |
+
|
| 110 |
+
| Category | Key Tools |
|
| 111 |
+
|----------|-----------|
|
| 112 |
+
| **Memory** | `memory_store`, `memory_search`, `memory_search_unified` |
|
| 113 |
+
| **Bridge** | `memory_import_claude`, `memory_bridge_status` |
|
| 114 |
+
| **Swarm** | `swarm_init`, `swarm_status`, `swarm_health` |
|
| 115 |
+
| **Agents** | `agent_spawn`, `agent_list`, `agent_status` |
|
| 116 |
+
| **Hooks** | `hooks_route`, `hooks_post-task`, `hooks_worker-dispatch` |
|
| 117 |
+
| **Security** | `aidefence_scan`, `aidefence_is_safe`, `aidefence_has_pii` |
|
| 118 |
+
| **Hive-Mind** | `hive-mind_init`, `hive-mind_consensus`, `hive-mind_spawn` |
|
| 119 |
+
|
| 120 |
+
### Background Workers
|
| 121 |
+
|
| 122 |
+
| Worker | When |
|
| 123 |
+
|--------|------|
|
| 124 |
+
| `audit` | After security changes |
|
| 125 |
+
| `optimize` | After performance work |
|
| 126 |
+
| `testgaps` | After adding features |
|
| 127 |
+
| `map` | Every 5+ file changes |
|
| 128 |
+
| `document` | After API changes |
|
| 129 |
+
|
| 130 |
+
```bash
|
| 131 |
+
npx @claude-flow/cli@latest hooks worker dispatch --trigger audit
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
## Agents
|
| 135 |
+
|
| 136 |
+
**Core**: `coder`, `reviewer`, `tester`, `planner`, `researcher`
|
| 137 |
+
**Architecture**: `system-architect`, `backend-dev`, `mobile-dev`
|
| 138 |
+
**Security**: `security-architect`, `security-auditor`
|
| 139 |
+
**Performance**: `performance-engineer`, `perf-analyzer`
|
| 140 |
+
**Coordination**: `hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`
|
| 141 |
+
**GitHub**: `pr-manager`, `code-review-swarm`, `issue-tracker`, `release-manager`
|
| 142 |
+
|
| 143 |
+
Any string works as a custom agent type.
|
| 144 |
+
|
| 145 |
+
## Build & Test
|
| 146 |
+
|
| 147 |
+
- ALWAYS run tests after code changes
|
| 148 |
+
- ALWAYS verify build succeeds before committing
|
| 149 |
+
|
| 150 |
+
```bash
|
| 151 |
+
npm run build && npm test
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
## CLI Quick Reference
|
| 155 |
+
|
| 156 |
+
```bash
|
| 157 |
+
npx @claude-flow/cli@latest init --wizard # Setup
|
| 158 |
+
npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm
|
| 159 |
+
npx @claude-flow/cli@latest memory search --query "" # Vector search
|
| 160 |
+
npx @claude-flow/cli@latest hooks route --task "" # Route to agent
|
| 161 |
+
npx @claude-flow/cli@latest doctor --fix # Diagnostics
|
| 162 |
+
npx @claude-flow/cli@latest security scan # Security scan
|
| 163 |
+
npx @claude-flow/cli@latest performance benchmark # Benchmarks
|
| 164 |
+
```
|
| 165 |
+
|
| 166 |
+
26 commands, 140+ subcommands. Use `--help` on any command for details.
|
| 167 |
+
|
| 168 |
+
## Setup
|
| 169 |
+
|
| 170 |
+
```bash
|
| 171 |
+
claude mcp add claude-flow -- npx -y @claude-flow/cli@latest
|
| 172 |
+
npx @claude-flow/cli@latest daemon start
|
| 173 |
+
npx @claude-flow/cli@latest doctor --fix
|
| 174 |
+
```
|
| 175 |
+
|
| 176 |
+
**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash.
|
app/config.py
CHANGED
|
@@ -8,8 +8,9 @@ class Settings(BaseSettings):
|
|
| 8 |
extra="ignore",
|
| 9 |
)
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
|
|
|
| 13 |
|
| 14 |
# JWT — sin default para evitar secretos hardcodeados en código fuente
|
| 15 |
jwt_secret: str
|
|
|
|
| 8 |
extra="ignore",
|
| 9 |
)
|
| 10 |
|
| 11 |
+
# Supabase
|
| 12 |
+
supabase_url: str
|
| 13 |
+
supabase_key: str
|
| 14 |
|
| 15 |
# JWT — sin default para evitar secretos hardcodeados en código fuente
|
| 16 |
jwt_secret: str
|
app/crud/cama.py
CHANGED
|
@@ -3,86 +3,97 @@ Operaciones de acceso a datos para Cama. Sin lógica de negocio ni HTTPException
|
|
| 3 |
"""
|
| 4 |
from __future__ import annotations
|
| 5 |
from datetime import datetime, timezone
|
| 6 |
-
from
|
| 7 |
from app.models.cama import Cama
|
| 8 |
from app.schemas.cama import CamaCreateRequest
|
| 9 |
|
|
|
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
def get_all(
|
| 16 |
-
db:
|
| 17 |
rol: str,
|
| 18 |
piso: int | None = None,
|
| 19 |
sector: str | None = None,
|
| 20 |
estado: str | None = None,
|
| 21 |
hospital_id: str | None = None,
|
| 22 |
) -> list[Cama]:
|
| 23 |
-
q = db.
|
| 24 |
|
| 25 |
if rol == "LIMPIEZA":
|
| 26 |
-
q = q.
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
q = q.filter(Cama.estado == estado)
|
| 30 |
|
| 31 |
if piso is not None:
|
| 32 |
-
q = q.
|
| 33 |
if sector:
|
| 34 |
-
q = q.
|
| 35 |
if hospital_id:
|
| 36 |
-
q = q.
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
def create(db: Session, data: CamaCreateRequest) -> Cama:
|
| 42 |
-
cama = Cama(
|
| 43 |
-
numero=data.numero,
|
| 44 |
-
piso=data.piso,
|
| 45 |
-
sector=data.sector.value,
|
| 46 |
-
tipo=data.tipo.value,
|
| 47 |
-
specialty_id=data.specialty_id,
|
| 48 |
-
hospital_id=data.hospital_id,
|
| 49 |
-
estado="DISPONIBLE",
|
| 50 |
-
contraindicaciones_incompatibles=data.contraindicaciones_incompatibles,
|
| 51 |
-
ultima_actualizacion=datetime.now(timezone.utc),
|
| 52 |
-
)
|
| 53 |
-
db.add(cama)
|
| 54 |
-
db.commit()
|
| 55 |
-
db.refresh(cama)
|
| 56 |
-
return cama
|
| 57 |
|
| 58 |
|
| 59 |
-
def
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
return cama
|
| 63 |
|
| 64 |
|
| 65 |
def get_quirofanos(
|
| 66 |
-
db:
|
| 67 |
hospital_id: str | None = None,
|
| 68 |
specialty_id: int | None = None,
|
| 69 |
exclude_estados: list[str] | None = None,
|
| 70 |
) -> list[Cama]:
|
| 71 |
excluidos = exclude_estados or ["FUERA_DE_SERVICIO", "BAJA_PERMANENTE"]
|
| 72 |
-
q = db.
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
Cama.estado.notin_(excluidos),
|
| 76 |
-
)
|
| 77 |
if hospital_id:
|
| 78 |
-
q = q.
|
| 79 |
if specialty_id is not None:
|
| 80 |
-
q = q.
|
| 81 |
-
|
|
|
|
| 82 |
|
| 83 |
|
| 84 |
-
def get_by_paciente(db:
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
"""
|
| 4 |
from __future__ import annotations
|
| 5 |
from datetime import datetime, timezone
|
| 6 |
+
from supabase import Client
|
| 7 |
from app.models.cama import Cama
|
| 8 |
from app.schemas.cama import CamaCreateRequest
|
| 9 |
|
| 10 |
+
_TABLE = "camas"
|
| 11 |
|
| 12 |
+
|
| 13 |
+
def get_by_id(db: Client, cama_id: int) -> Cama | None:
|
| 14 |
+
resp = db.table(_TABLE).select("*").eq("id", cama_id).execute()
|
| 15 |
+
return Cama.from_dict(resp.data[0]) if resp.data else None
|
| 16 |
|
| 17 |
|
| 18 |
def get_all(
|
| 19 |
+
db: Client,
|
| 20 |
rol: str,
|
| 21 |
piso: int | None = None,
|
| 22 |
sector: str | None = None,
|
| 23 |
estado: str | None = None,
|
| 24 |
hospital_id: str | None = None,
|
| 25 |
) -> list[Cama]:
|
| 26 |
+
q = db.table(_TABLE).select("*").neq("estado", "BAJA_PERMANENTE")
|
| 27 |
|
| 28 |
if rol == "LIMPIEZA":
|
| 29 |
+
q = q.eq("estado", "EN_LIMPIEZA")
|
| 30 |
+
elif estado:
|
| 31 |
+
q = q.eq("estado", estado)
|
|
|
|
| 32 |
|
| 33 |
if piso is not None:
|
| 34 |
+
q = q.eq("piso", piso)
|
| 35 |
if sector:
|
| 36 |
+
q = q.eq("sector", sector)
|
| 37 |
if hospital_id:
|
| 38 |
+
q = q.eq("hospital_id", hospital_id)
|
| 39 |
+
|
| 40 |
+
resp = q.execute()
|
| 41 |
+
return [Cama.from_dict(row) for row in resp.data]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
|
| 44 |
+
def create(db: Client, data: CamaCreateRequest) -> Cama:
|
| 45 |
+
row = {
|
| 46 |
+
"numero": data.numero,
|
| 47 |
+
"piso": data.piso,
|
| 48 |
+
"sector": data.sector.value,
|
| 49 |
+
"tipo": data.tipo.value,
|
| 50 |
+
"specialty_id": data.specialty_id,
|
| 51 |
+
"hospital_id": data.hospital_id,
|
| 52 |
+
"estado": "DISPONIBLE",
|
| 53 |
+
"contraindicaciones_incompatibles": data.contraindicaciones_incompatibles,
|
| 54 |
+
"ultima_actualizacion": datetime.now(timezone.utc).isoformat(),
|
| 55 |
+
}
|
| 56 |
+
resp = db.table(_TABLE).insert(row).execute()
|
| 57 |
+
return Cama.from_dict(resp.data[0])
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
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,
|
| 67 |
+
}
|
| 68 |
+
db.table(_TABLE).update(updates).eq("id", cama.id).execute()
|
| 69 |
return cama
|
| 70 |
|
| 71 |
|
| 72 |
def get_quirofanos(
|
| 73 |
+
db: Client,
|
| 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:
|
| 85 |
+
q = q.eq("specialty_id", specialty_id)
|
| 86 |
+
resp = q.execute()
|
| 87 |
+
return [Cama.from_dict(row) for row in resp.data]
|
| 88 |
|
| 89 |
|
| 90 |
+
def get_by_paciente(db: Client, paciente_id: int, estados: list[str]) -> Cama | None:
|
| 91 |
+
resp = (
|
| 92 |
+
db.table(_TABLE)
|
| 93 |
+
.select("*")
|
| 94 |
+
.eq("paciente_id", paciente_id)
|
| 95 |
+
.in_("estado", estados)
|
| 96 |
+
.limit(1)
|
| 97 |
+
.execute()
|
| 98 |
+
)
|
| 99 |
+
return Cama.from_dict(resp.data[0]) if resp.data else None
|
app/crud/reserva.py
CHANGED
|
@@ -3,123 +3,147 @@ Operaciones de acceso a datos para ReservaQuirofano. Sin lógica de negocio ni H
|
|
| 3 |
"""
|
| 4 |
from __future__ import annotations
|
| 5 |
from datetime import datetime, timezone
|
| 6 |
-
from
|
| 7 |
from app.models.reserva import ReservaQuirofano
|
| 8 |
from app.schemas.reserva import ReservaQuirofanoCreateRequest, CirugiaUrgenteWebhook
|
| 9 |
|
|
|
|
| 10 |
|
| 11 |
-
def get_by_id(db: Session, reserva_id: int) -> ReservaQuirofano | None:
|
| 12 |
-
return db.query(ReservaQuirofano).filter(ReservaQuirofano.id == reserva_id).first()
|
| 13 |
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
|
| 22 |
-
def get_by_turno(db:
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
|
| 29 |
-
def get_by_urgencia_hce_id(db:
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
|
| 35 |
def get_all(
|
| 36 |
-
db:
|
| 37 |
cama_id: int,
|
| 38 |
estado: str | None = None,
|
| 39 |
prioridad: str | None = None,
|
| 40 |
fecha_desde: str | None = None,
|
| 41 |
fecha_hasta: str | None = None,
|
| 42 |
) -> list[ReservaQuirofano]:
|
| 43 |
-
q = db.
|
| 44 |
if estado:
|
| 45 |
-
q = q.
|
| 46 |
else:
|
| 47 |
-
q = q.
|
| 48 |
if prioridad:
|
| 49 |
-
q = q.
|
| 50 |
if fecha_desde:
|
| 51 |
-
q = q.
|
| 52 |
if fecha_hasta:
|
| 53 |
-
q = q.
|
| 54 |
-
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
def get_superpuestas(
|
| 58 |
-
db:
|
| 59 |
cama_id: int,
|
| 60 |
inicio: datetime,
|
| 61 |
fin: datetime,
|
| 62 |
exclude_id: int | None = None,
|
| 63 |
) -> list[ReservaQuirofano]:
|
| 64 |
-
q =
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
| 69 |
)
|
| 70 |
if exclude_id:
|
| 71 |
-
q = q.
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
cama_id=cama_id,
|
| 85 |
-
turno_id=data.turno_id,
|
| 86 |
-
origen="PROGRAMADA",
|
| 87 |
-
estado="RESERVADA",
|
| 88 |
-
prioridad=data.prioridad.value,
|
| 89 |
-
paciente_id=data.paciente_id,
|
| 90 |
-
medico_cirujano_id=data.medico_cirujano_id,
|
| 91 |
-
fecha_hora_inicio=data.fecha_hora_inicio,
|
| 92 |
-
fecha_hora_fin_estimada=data.fecha_hora_fin_estimada,
|
| 93 |
-
observaciones=data.observaciones,
|
| 94 |
-
created_at=datetime.now(timezone.utc),
|
| 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 |
return reserva
|
|
|
|
| 3 |
"""
|
| 4 |
from __future__ import annotations
|
| 5 |
from datetime import datetime, timezone
|
| 6 |
+
from supabase import Client
|
| 7 |
from app.models.reserva import ReservaQuirofano
|
| 8 |
from app.schemas.reserva import ReservaQuirofanoCreateRequest, CirugiaUrgenteWebhook
|
| 9 |
|
| 10 |
+
_TABLE = "reservas_quirofano"
|
| 11 |
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
def get_by_id(db: Client, reserva_id: int) -> ReservaQuirofano | None:
|
| 14 |
+
resp = db.table(_TABLE).select("*").eq("id", reserva_id).execute()
|
| 15 |
+
return ReservaQuirofano.from_dict(resp.data[0]) if resp.data else None
|
| 16 |
|
| 17 |
+
|
| 18 |
+
def get_by_cama_and_id(db: Client, cama_id: int, reserva_id: int) -> ReservaQuirofano | None:
|
| 19 |
+
resp = (
|
| 20 |
+
db.table(_TABLE)
|
| 21 |
+
.select("*")
|
| 22 |
+
.eq("id", reserva_id)
|
| 23 |
+
.eq("cama_id", cama_id)
|
| 24 |
+
.execute()
|
| 25 |
+
)
|
| 26 |
+
return ReservaQuirofano.from_dict(resp.data[0]) if resp.data else None
|
| 27 |
|
| 28 |
|
| 29 |
+
def get_by_turno(db: Client, turno_id: str) -> ReservaQuirofano | None:
|
| 30 |
+
resp = (
|
| 31 |
+
db.table(_TABLE)
|
| 32 |
+
.select("*")
|
| 33 |
+
.eq("turno_id", turno_id)
|
| 34 |
+
.eq("origen", "PROGRAMADA")
|
| 35 |
+
.execute()
|
| 36 |
+
)
|
| 37 |
+
return ReservaQuirofano.from_dict(resp.data[0]) if resp.data else None
|
| 38 |
|
| 39 |
|
| 40 |
+
def get_by_urgencia_hce_id(db: Client, hce_id: str) -> ReservaQuirofano | None:
|
| 41 |
+
resp = (
|
| 42 |
+
db.table(_TABLE)
|
| 43 |
+
.select("*")
|
| 44 |
+
.eq("solicitud_urgencia_hce_id", hce_id)
|
| 45 |
+
.execute()
|
| 46 |
+
)
|
| 47 |
+
return ReservaQuirofano.from_dict(resp.data[0]) if resp.data else None
|
| 48 |
|
| 49 |
|
| 50 |
def get_all(
|
| 51 |
+
db: Client,
|
| 52 |
cama_id: int,
|
| 53 |
estado: str | None = None,
|
| 54 |
prioridad: str | None = None,
|
| 55 |
fecha_desde: str | None = None,
|
| 56 |
fecha_hasta: str | None = None,
|
| 57 |
) -> list[ReservaQuirofano]:
|
| 58 |
+
q = db.table(_TABLE).select("*").eq("cama_id", cama_id)
|
| 59 |
if estado:
|
| 60 |
+
q = q.eq("estado", estado)
|
| 61 |
else:
|
| 62 |
+
q = q.in_("estado", ["RESERVADA", "EN_CURSO"])
|
| 63 |
if prioridad:
|
| 64 |
+
q = q.eq("prioridad", prioridad)
|
| 65 |
if fecha_desde:
|
| 66 |
+
q = q.gte("fecha_hora_inicio", fecha_desde)
|
| 67 |
if fecha_hasta:
|
| 68 |
+
q = q.lte("fecha_hora_fin_estimada", fecha_hasta)
|
| 69 |
+
resp = q.execute()
|
| 70 |
+
return [ReservaQuirofano.from_dict(row) for row in resp.data]
|
| 71 |
|
| 72 |
|
| 73 |
def get_superpuestas(
|
| 74 |
+
db: Client,
|
| 75 |
cama_id: int,
|
| 76 |
inicio: datetime,
|
| 77 |
fin: datetime,
|
| 78 |
exclude_id: int | None = None,
|
| 79 |
) -> list[ReservaQuirofano]:
|
| 80 |
+
q = (
|
| 81 |
+
db.table(_TABLE)
|
| 82 |
+
.select("*")
|
| 83 |
+
.eq("cama_id", cama_id)
|
| 84 |
+
.in_("estado", ["RESERVADA", "EN_CURSO"])
|
| 85 |
+
.lt("fecha_hora_inicio", fin.isoformat())
|
| 86 |
+
.gt("fecha_hora_fin_estimada", inicio.isoformat())
|
| 87 |
)
|
| 88 |
if exclude_id:
|
| 89 |
+
q = q.neq("id", exclude_id)
|
| 90 |
+
resp = q.execute()
|
| 91 |
+
return [ReservaQuirofano.from_dict(row) for row in resp.data]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def get_activa_por_turno(db: Client, turno_id: str) -> ReservaQuirofano | None:
|
| 95 |
+
resp = (
|
| 96 |
+
db.table(_TABLE)
|
| 97 |
+
.select("*")
|
| 98 |
+
.eq("turno_id", turno_id)
|
| 99 |
+
.in_("estado", ["RESERVADA", "EN_CURSO"])
|
| 100 |
+
.limit(1)
|
| 101 |
+
.execute()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
)
|
| 103 |
+
return ReservaQuirofano.from_dict(resp.data[0]) if resp.data else None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def create_programada(db: Client, cama_id: int, data: ReservaQuirofanoCreateRequest) -> ReservaQuirofano:
|
| 107 |
+
row = {
|
| 108 |
+
"cama_id": cama_id,
|
| 109 |
+
"turno_id": data.turno_id,
|
| 110 |
+
"origen": "PROGRAMADA",
|
| 111 |
+
"estado": "RESERVADA",
|
| 112 |
+
"prioridad": data.prioridad.value,
|
| 113 |
+
"paciente_id": data.paciente_id,
|
| 114 |
+
"medico_cirujano_id": data.medico_cirujano_id,
|
| 115 |
+
"fecha_hora_inicio": data.fecha_hora_inicio.isoformat(),
|
| 116 |
+
"fecha_hora_fin_estimada": data.fecha_hora_fin_estimada.isoformat(),
|
| 117 |
+
"observaciones": data.observaciones,
|
| 118 |
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
| 119 |
+
}
|
| 120 |
+
resp = db.table(_TABLE).insert(row).execute()
|
| 121 |
+
return ReservaQuirofano.from_dict(resp.data[0])
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def create_urgente(db: Client, cama_id: int, data: CirugiaUrgenteWebhook) -> ReservaQuirofano:
|
| 125 |
+
row = {
|
| 126 |
+
"cama_id": cama_id,
|
| 127 |
+
"solicitud_urgencia_hce_id": data.solicitud_urgencia_hce_id,
|
| 128 |
+
"origen": "EMERGENCIA",
|
| 129 |
+
"estado": "RESERVADA",
|
| 130 |
+
"prioridad": "URGENTE",
|
| 131 |
+
"paciente_id": data.paciente_id,
|
| 132 |
+
"medico_cirujano_id": data.medico_cirujano_id,
|
| 133 |
+
"fecha_hora_inicio": data.fecha_hora_inicio.isoformat(),
|
| 134 |
+
"fecha_hora_fin_estimada": data.fecha_hora_fin_estimada.isoformat(),
|
| 135 |
+
"observaciones": f"Cirugía urgente solicitada por HCE ({data.solicitud_urgencia_hce_id})",
|
| 136 |
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
| 137 |
+
}
|
| 138 |
+
resp = db.table(_TABLE).insert(row).execute()
|
| 139 |
+
return ReservaQuirofano.from_dict(resp.data[0])
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def save(db: Client, reserva: ReservaQuirofano) -> ReservaQuirofano:
|
| 143 |
+
updates = {
|
| 144 |
+
"estado": reserva.estado,
|
| 145 |
+
"observaciones": reserva.observaciones,
|
| 146 |
+
"desplazada_por_reserva_id": reserva.desplazada_por_reserva_id,
|
| 147 |
+
}
|
| 148 |
+
db.table(_TABLE).update(updates).eq("id", reserva.id).execute()
|
| 149 |
return reserva
|
app/crud/solicitud.py
CHANGED
|
@@ -2,63 +2,73 @@
|
|
| 2 |
Operaciones de acceso a datos para Solicitud. Sin lógica de negocio ni HTTPException.
|
| 3 |
"""
|
| 4 |
from __future__ import annotations
|
| 5 |
-
from
|
| 6 |
from app.models.solicitud import Solicitud
|
| 7 |
from app.schemas.solicitud import SolicitudHceWebhook
|
| 8 |
|
|
|
|
| 9 |
|
| 10 |
-
def get_by_id(db: Session, solicitud_id: int) -> Solicitud | None:
|
| 11 |
-
return db.query(Solicitud).filter(Solicitud.id == solicitud_id).first()
|
| 12 |
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
def get_all(
|
| 19 |
-
db:
|
| 20 |
estado: str | None = None,
|
| 21 |
tipo: str | None = None,
|
| 22 |
hospital_id: str | None = None,
|
| 23 |
) -> list[Solicitud]:
|
| 24 |
-
q = db.
|
| 25 |
if estado:
|
| 26 |
-
q = q.
|
| 27 |
if tipo:
|
| 28 |
-
q = q.
|
| 29 |
if hospital_id:
|
| 30 |
-
q = q.
|
| 31 |
-
|
|
|
|
| 32 |
|
| 33 |
|
| 34 |
-
def create(db:
|
| 35 |
-
|
| 36 |
-
solicitud_hce_id
|
| 37 |
-
tipo
|
| 38 |
-
estado
|
| 39 |
-
paciente_id
|
| 40 |
-
medico_solicitante_id
|
| 41 |
-
cama_solicitada_id
|
| 42 |
-
origen
|
| 43 |
-
turno_id
|
| 44 |
-
diagnostico_ingreso
|
| 45 |
-
obra_social_id
|
| 46 |
-
numero_afiliado
|
| 47 |
-
prioridad
|
| 48 |
-
observaciones
|
| 49 |
-
hospital_id
|
| 50 |
-
cama_origen_id
|
| 51 |
-
cama_destino_solicitada_id
|
| 52 |
-
motivo_traslado
|
| 53 |
-
timestamp_solicitud
|
| 54 |
-
|
| 55 |
-
db.
|
| 56 |
-
|
| 57 |
-
db.refresh(sol)
|
| 58 |
-
return sol
|
| 59 |
|
| 60 |
|
| 61 |
-
def save(db:
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
return solicitud
|
|
|
|
| 2 |
Operaciones de acceso a datos para Solicitud. Sin lógica de negocio ni HTTPException.
|
| 3 |
"""
|
| 4 |
from __future__ import annotations
|
| 5 |
+
from supabase import Client
|
| 6 |
from app.models.solicitud import Solicitud
|
| 7 |
from app.schemas.solicitud import SolicitudHceWebhook
|
| 8 |
|
| 9 |
+
_TABLE = "solicitudes"
|
| 10 |
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
def get_by_id(db: Client, solicitud_id: int) -> Solicitud | None:
|
| 13 |
+
resp = db.table(_TABLE).select("*").eq("id", solicitud_id).execute()
|
| 14 |
+
return Solicitud.from_dict(resp.data[0]) if resp.data else None
|
| 15 |
|
| 16 |
+
|
| 17 |
+
def get_by_hce_id(db: Client, solicitud_hce_id: str) -> Solicitud | None:
|
| 18 |
+
resp = db.table(_TABLE).select("*").eq("solicitud_hce_id", solicitud_hce_id).execute()
|
| 19 |
+
return Solicitud.from_dict(resp.data[0]) if resp.data else None
|
| 20 |
|
| 21 |
|
| 22 |
def get_all(
|
| 23 |
+
db: Client,
|
| 24 |
estado: str | None = None,
|
| 25 |
tipo: str | None = None,
|
| 26 |
hospital_id: str | None = None,
|
| 27 |
) -> list[Solicitud]:
|
| 28 |
+
q = db.table(_TABLE).select("*")
|
| 29 |
if estado:
|
| 30 |
+
q = q.eq("estado", estado)
|
| 31 |
if tipo:
|
| 32 |
+
q = q.eq("tipo", tipo)
|
| 33 |
if hospital_id:
|
| 34 |
+
q = q.eq("hospital_id", hospital_id)
|
| 35 |
+
resp = q.execute()
|
| 36 |
+
return [Solicitud.from_dict(row) for row in resp.data]
|
| 37 |
|
| 38 |
|
| 39 |
+
def create(db: Client, data: SolicitudHceWebhook) -> Solicitud:
|
| 40 |
+
row = {
|
| 41 |
+
"solicitud_hce_id": data.solicitud_hce_id,
|
| 42 |
+
"tipo": data.tipo.value,
|
| 43 |
+
"estado": "PENDIENTE",
|
| 44 |
+
"paciente_id": data.paciente_id,
|
| 45 |
+
"medico_solicitante_id": data.medico_solicitante_id,
|
| 46 |
+
"cama_solicitada_id": data.cama_solicitada_id,
|
| 47 |
+
"origen": data.origen.value if data.origen else None,
|
| 48 |
+
"turno_id": data.turno_id,
|
| 49 |
+
"diagnostico_ingreso": data.diagnostico_ingreso,
|
| 50 |
+
"obra_social_id": data.obra_social_id,
|
| 51 |
+
"numero_afiliado": data.numero_afiliado,
|
| 52 |
+
"prioridad": data.prioridad.value if data.prioridad else None,
|
| 53 |
+
"observaciones": data.observaciones,
|
| 54 |
+
"hospital_id": data.hospital_id,
|
| 55 |
+
"cama_origen_id": data.cama_origen_id,
|
| 56 |
+
"cama_destino_solicitada_id": data.cama_destino_solicitada_id,
|
| 57 |
+
"motivo_traslado": data.motivo_traslado,
|
| 58 |
+
"timestamp_solicitud": data.timestamp.isoformat(),
|
| 59 |
+
}
|
| 60 |
+
resp = db.table(_TABLE).insert(row).execute()
|
| 61 |
+
return Solicitud.from_dict(resp.data[0])
|
|
|
|
|
|
|
| 62 |
|
| 63 |
|
| 64 |
+
def save(db: Client, solicitud: Solicitud) -> Solicitud:
|
| 65 |
+
updates = {
|
| 66 |
+
"estado": solicitud.estado,
|
| 67 |
+
"accion": solicitud.accion,
|
| 68 |
+
"motivo": solicitud.motivo,
|
| 69 |
+
"cama_asignada_id": solicitud.cama_asignada_id,
|
| 70 |
+
"resuelto_por": solicitud.resuelto_por,
|
| 71 |
+
"timestamp_resolucion": solicitud.timestamp_resolucion.isoformat() if solicitud.timestamp_resolucion else None,
|
| 72 |
+
}
|
| 73 |
+
db.table(_TABLE).update(updates).eq("id", solicitud.id).execute()
|
| 74 |
return solicitud
|
app/dependencies.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
Dependencias compartidas de FastAPI: BD, JWT y autenticación.
|
| 3 |
-
Unifica database.py + auth/jwt_handler.py + auth/dependencies.py del proyecto original.
|
| 4 |
"""
|
| 5 |
import logging
|
| 6 |
from datetime import datetime, timedelta, timezone
|
|
@@ -8,8 +7,7 @@ from datetime import datetime, timedelta, timezone
|
|
| 8 |
from fastapi import Depends, HTTPException, status
|
| 9 |
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 10 |
from jose import JWTError, jwt
|
| 11 |
-
from
|
| 12 |
-
from sqlalchemy.orm import sessionmaker, DeclarativeBase
|
| 13 |
|
| 14 |
from app.config import settings
|
| 15 |
|
|
@@ -17,29 +15,11 @@ logger = logging.getLogger(__name__)
|
|
| 17 |
|
| 18 |
# ─── Base de datos ─────────────────────────────────────────────────────────
|
| 19 |
|
| 20 |
-
|
| 21 |
-
settings.database_url,
|
| 22 |
-
pool_pre_ping=True,
|
| 23 |
-
pool_size=5,
|
| 24 |
-
max_overflow=10,
|
| 25 |
-
)
|
| 26 |
|
| 27 |
-
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
pass
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def get_db():
|
| 35 |
-
db = SessionLocal()
|
| 36 |
-
try:
|
| 37 |
-
yield db
|
| 38 |
-
except Exception:
|
| 39 |
-
db.rollback()
|
| 40 |
-
raise
|
| 41 |
-
finally:
|
| 42 |
-
db.close()
|
| 43 |
|
| 44 |
|
| 45 |
# ─── JWT ───────────────────────────────────────────────────────────────────
|
|
|
|
| 1 |
"""
|
| 2 |
+
Dependencias compartidas de FastAPI: BD (Supabase), JWT y autenticación.
|
|
|
|
| 3 |
"""
|
| 4 |
import logging
|
| 5 |
from datetime import datetime, timedelta, timezone
|
|
|
|
| 7 |
from fastapi import Depends, HTTPException, status
|
| 8 |
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 9 |
from jose import JWTError, jwt
|
| 10 |
+
from supabase import create_client, Client
|
|
|
|
| 11 |
|
| 12 |
from app.config import settings
|
| 13 |
|
|
|
|
| 15 |
|
| 16 |
# ─── Base de datos ─────────────────────────────────────────────────────────
|
| 17 |
|
| 18 |
+
_supabase: Client = create_client(settings.supabase_url, settings.supabase_key)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
|
|
|
| 20 |
|
| 21 |
+
def get_db() -> Client:
|
| 22 |
+
return _supabase
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
|
| 25 |
# ─── JWT ───────────────────────────────────────────────────────────────────
|
app/main.py
CHANGED
|
@@ -10,12 +10,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
|
| 10 |
from fastapi.responses import JSONResponse
|
| 11 |
|
| 12 |
from app.config import settings
|
| 13 |
-
from app.dependencies import
|
| 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 |
from app.routers.webhooks import router_turnos
|
|
@@ -33,8 +28,7 @@ logging.basicConfig(
|
|
| 33 |
|
| 34 |
@asynccontextmanager
|
| 35 |
async def lifespan(app: FastAPI):
|
| 36 |
-
|
| 37 |
-
logger.info("Tablas creadas/verificadas correctamente")
|
| 38 |
yield
|
| 39 |
|
| 40 |
|
|
|
|
| 10 |
from fastapi.responses import JSONResponse
|
| 11 |
|
| 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
|
|
|
|
| 28 |
|
| 29 |
@asynccontextmanager
|
| 30 |
async def lifespan(app: FastAPI):
|
| 31 |
+
logger.info("Conectado a Supabase — listo para operar")
|
|
|
|
| 32 |
yield
|
| 33 |
|
| 34 |
|
app/models/cama.py
CHANGED
|
@@ -1,13 +1,14 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
-
from datetime import datetime
|
| 3 |
-
from
|
| 4 |
-
from sqlalchemy.dialects.postgresql import ARRAY
|
| 5 |
-
from sqlalchemy.orm import relationship
|
| 6 |
-
from app.dependencies import Base
|
| 7 |
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
id = Column(Integer, primary_key=True, autoincrement=True)
|
| 13 |
numero = Column(Integer, nullable=False)
|
|
@@ -30,14 +31,48 @@ class Cama(Base):
|
|
| 30 |
# Rastrea tipo del último movimiento para saber si disparar CAMA_LISTA al quedar DISPONIBLE
|
| 31 |
ultimo_movimiento_tipo = Column(String(20), nullable=True)
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
"
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from typing import Optional
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
+
def _parse_dt(v) -> Optional[datetime]:
|
| 7 |
+
if v is None:
|
| 8 |
+
return None
|
| 9 |
+
if isinstance(v, datetime):
|
| 10 |
+
return v
|
| 11 |
+
return datetime.fromisoformat(str(v))
|
| 12 |
|
| 13 |
id = Column(Integer, primary_key=True, autoincrement=True)
|
| 14 |
numero = Column(Integer, nullable=False)
|
|
|
|
| 31 |
# Rastrea tipo del último movimiento para saber si disparar CAMA_LISTA al quedar DISPONIBLE
|
| 32 |
ultimo_movimiento_tipo = Column(String(20), nullable=True)
|
| 33 |
|
| 34 |
+
class Cama:
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
id: Optional[int] = None,
|
| 38 |
+
numero: str = "",
|
| 39 |
+
piso: int = 0,
|
| 40 |
+
sector: str = "",
|
| 41 |
+
tipo: str = "",
|
| 42 |
+
estado: str = "DISPONIBLE",
|
| 43 |
+
specialty_id: Optional[int] = None,
|
| 44 |
+
paciente_id: Optional[int] = None,
|
| 45 |
+
hospital_id: str = "",
|
| 46 |
+
contraindicaciones_incompatibles: Optional[list] = None,
|
| 47 |
+
ultima_actualizacion: Optional[datetime] = None,
|
| 48 |
+
ultimo_movimiento_tipo: Optional[str] = None,
|
| 49 |
+
):
|
| 50 |
+
self.id = id
|
| 51 |
+
self.numero = numero
|
| 52 |
+
self.piso = piso
|
| 53 |
+
self.sector = sector
|
| 54 |
+
self.tipo = tipo
|
| 55 |
+
self.estado = estado
|
| 56 |
+
self.specialty_id = specialty_id
|
| 57 |
+
self.paciente_id = paciente_id
|
| 58 |
+
self.hospital_id = hospital_id
|
| 59 |
+
self.contraindicaciones_incompatibles = contraindicaciones_incompatibles or []
|
| 60 |
+
self.ultima_actualizacion = _parse_dt(ultima_actualizacion)
|
| 61 |
+
self.ultimo_movimiento_tipo = ultimo_movimiento_tipo
|
| 62 |
+
|
| 63 |
+
@classmethod
|
| 64 |
+
def from_dict(cls, d: dict) -> "Cama":
|
| 65 |
+
return cls(
|
| 66 |
+
id=d.get("id"),
|
| 67 |
+
numero=d.get("numero", ""),
|
| 68 |
+
piso=d.get("piso", 0),
|
| 69 |
+
sector=d.get("sector", ""),
|
| 70 |
+
tipo=d.get("tipo", ""),
|
| 71 |
+
estado=d.get("estado", "DISPONIBLE"),
|
| 72 |
+
specialty_id=d.get("specialty_id"),
|
| 73 |
+
paciente_id=d.get("paciente_id"),
|
| 74 |
+
hospital_id=d.get("hospital_id", ""),
|
| 75 |
+
contraindicaciones_incompatibles=d.get("contraindicaciones_incompatibles") or [],
|
| 76 |
+
ultima_actualizacion=d.get("ultima_actualizacion"),
|
| 77 |
+
ultimo_movimiento_tipo=d.get("ultimo_movimiento_tipo"),
|
| 78 |
+
)
|
app/models/reserva.py
CHANGED
|
@@ -1,46 +1,64 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
-
from datetime import datetime
|
| 3 |
-
from
|
| 4 |
-
from sqlalchemy.orm import relationship
|
| 5 |
-
from app.dependencies import Base
|
| 6 |
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
id = Column(Integer, primary_key=True, autoincrement=True)
|
| 12 |
-
cama_id = Column(Integer, ForeignKey("camas.id"), nullable=False)
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 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 |
-
)
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from typing import Optional
|
|
|
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
+
def _parse_dt(v) -> Optional[datetime]:
|
| 7 |
+
if v is None:
|
| 8 |
+
return None
|
| 9 |
+
if isinstance(v, datetime):
|
| 10 |
+
return v
|
| 11 |
+
return datetime.fromisoformat(str(v))
|
| 12 |
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
class ReservaQuirofano:
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
id: Optional[int] = None,
|
| 18 |
+
cama_id: Optional[int] = None,
|
| 19 |
+
turno_id: Optional[str] = None,
|
| 20 |
+
solicitud_urgencia_hce_id: Optional[str] = None,
|
| 21 |
+
origen: str = "",
|
| 22 |
+
estado: str = "RESERVADA",
|
| 23 |
+
prioridad: str = "",
|
| 24 |
+
paciente_id: Optional[int] = None,
|
| 25 |
+
medico_cirujano_id: Optional[int] = None,
|
| 26 |
+
fecha_hora_inicio: Optional[datetime] = None,
|
| 27 |
+
fecha_hora_fin_estimada: Optional[datetime] = None,
|
| 28 |
+
observaciones: Optional[str] = None,
|
| 29 |
+
desplazada_por_reserva_id: Optional[int] = None,
|
| 30 |
+
created_at: Optional[datetime] = None,
|
| 31 |
+
):
|
| 32 |
+
self.id = id
|
| 33 |
+
self.cama_id = cama_id
|
| 34 |
+
self.turno_id = turno_id
|
| 35 |
+
self.solicitud_urgencia_hce_id = solicitud_urgencia_hce_id
|
| 36 |
+
self.origen = origen
|
| 37 |
+
self.estado = estado
|
| 38 |
+
self.prioridad = prioridad
|
| 39 |
+
self.paciente_id = paciente_id
|
| 40 |
+
self.medico_cirujano_id = medico_cirujano_id
|
| 41 |
+
self.fecha_hora_inicio = _parse_dt(fecha_hora_inicio)
|
| 42 |
+
self.fecha_hora_fin_estimada = _parse_dt(fecha_hora_fin_estimada)
|
| 43 |
+
self.observaciones = observaciones
|
| 44 |
+
self.desplazada_por_reserva_id = desplazada_por_reserva_id
|
| 45 |
+
self.created_at = _parse_dt(created_at)
|
| 46 |
|
| 47 |
+
@classmethod
|
| 48 |
+
def from_dict(cls, d: dict) -> "ReservaQuirofano":
|
| 49 |
+
return cls(
|
| 50 |
+
id=d.get("id"),
|
| 51 |
+
cama_id=d.get("cama_id"),
|
| 52 |
+
turno_id=d.get("turno_id"),
|
| 53 |
+
solicitud_urgencia_hce_id=d.get("solicitud_urgencia_hce_id"),
|
| 54 |
+
origen=d.get("origen", ""),
|
| 55 |
+
estado=d.get("estado", "RESERVADA"),
|
| 56 |
+
prioridad=d.get("prioridad", ""),
|
| 57 |
+
paciente_id=d.get("paciente_id"),
|
| 58 |
+
medico_cirujano_id=d.get("medico_cirujano_id"),
|
| 59 |
+
fecha_hora_inicio=d.get("fecha_hora_inicio"),
|
| 60 |
+
fecha_hora_fin_estimada=d.get("fecha_hora_fin_estimada"),
|
| 61 |
+
observaciones=d.get("observaciones"),
|
| 62 |
+
desplazada_por_reserva_id=d.get("desplazada_por_reserva_id"),
|
| 63 |
+
created_at=d.get("created_at"),
|
| 64 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/models/solicitud.py
CHANGED
|
@@ -1,61 +1,98 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
-
from
|
| 3 |
-
from
|
| 4 |
-
from app.dependencies import Base
|
| 5 |
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 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 |
@property
|
| 60 |
def solicitud_id(self) -> str:
|
| 61 |
return f"SOL-{self.id:05d}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from typing import Optional
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
+
def _parse_dt(v) -> Optional[datetime]:
|
| 7 |
+
if v is None:
|
| 8 |
+
return None
|
| 9 |
+
if isinstance(v, datetime):
|
| 10 |
+
return v
|
| 11 |
+
return datetime.fromisoformat(str(v))
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
class Solicitud:
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
id: Optional[int] = None,
|
| 18 |
+
solicitud_hce_id: str = "",
|
| 19 |
+
tipo: str = "",
|
| 20 |
+
estado: str = "PENDIENTE",
|
| 21 |
+
paciente_id: Optional[int] = None,
|
| 22 |
+
medico_solicitante_id: Optional[int] = None,
|
| 23 |
+
cama_solicitada_id: Optional[int] = None,
|
| 24 |
+
cama_asignada_id: Optional[int] = None,
|
| 25 |
+
origen: Optional[str] = None,
|
| 26 |
+
turno_id: Optional[str] = None,
|
| 27 |
+
diagnostico_ingreso: Optional[str] = None,
|
| 28 |
+
obra_social_id: Optional[str] = None,
|
| 29 |
+
numero_afiliado: Optional[str] = None,
|
| 30 |
+
prioridad: Optional[str] = None,
|
| 31 |
+
observaciones: Optional[str] = None,
|
| 32 |
+
hospital_id: Optional[str] = None,
|
| 33 |
+
cama_origen_id: Optional[int] = None,
|
| 34 |
+
cama_destino_solicitada_id: Optional[int] = None,
|
| 35 |
+
motivo_traslado: Optional[str] = None,
|
| 36 |
+
accion: Optional[str] = None,
|
| 37 |
+
motivo: Optional[str] = None,
|
| 38 |
+
resuelto_por: Optional[int] = None,
|
| 39 |
+
timestamp_solicitud: Optional[datetime] = None,
|
| 40 |
+
timestamp_resolucion: Optional[datetime] = None,
|
| 41 |
+
):
|
| 42 |
+
self.id = id
|
| 43 |
+
self.solicitud_hce_id = solicitud_hce_id
|
| 44 |
+
self.tipo = tipo
|
| 45 |
+
self.estado = estado
|
| 46 |
+
self.paciente_id = paciente_id
|
| 47 |
+
self.medico_solicitante_id = medico_solicitante_id
|
| 48 |
+
self.cama_solicitada_id = cama_solicitada_id
|
| 49 |
+
self.cama_asignada_id = cama_asignada_id
|
| 50 |
+
self.origen = origen
|
| 51 |
+
self.turno_id = turno_id
|
| 52 |
+
self.diagnostico_ingreso = diagnostico_ingreso
|
| 53 |
+
self.obra_social_id = obra_social_id
|
| 54 |
+
self.numero_afiliado = numero_afiliado
|
| 55 |
+
self.prioridad = prioridad
|
| 56 |
+
self.observaciones = observaciones
|
| 57 |
+
self.hospital_id = hospital_id
|
| 58 |
+
self.cama_origen_id = cama_origen_id
|
| 59 |
+
self.cama_destino_solicitada_id = cama_destino_solicitada_id
|
| 60 |
+
self.motivo_traslado = motivo_traslado
|
| 61 |
+
self.accion = accion
|
| 62 |
+
self.motivo = motivo
|
| 63 |
+
self.resuelto_por = resuelto_por
|
| 64 |
+
self.timestamp_solicitud = _parse_dt(timestamp_solicitud)
|
| 65 |
+
self.timestamp_resolucion = _parse_dt(timestamp_resolucion)
|
| 66 |
|
| 67 |
@property
|
| 68 |
def solicitud_id(self) -> str:
|
| 69 |
return f"SOL-{self.id:05d}"
|
| 70 |
+
|
| 71 |
+
@classmethod
|
| 72 |
+
def from_dict(cls, d: dict) -> "Solicitud":
|
| 73 |
+
return cls(
|
| 74 |
+
id=d.get("id"),
|
| 75 |
+
solicitud_hce_id=d.get("solicitud_hce_id", ""),
|
| 76 |
+
tipo=d.get("tipo", ""),
|
| 77 |
+
estado=d.get("estado", "PENDIENTE"),
|
| 78 |
+
paciente_id=d.get("paciente_id"),
|
| 79 |
+
medico_solicitante_id=d.get("medico_solicitante_id"),
|
| 80 |
+
cama_solicitada_id=d.get("cama_solicitada_id"),
|
| 81 |
+
cama_asignada_id=d.get("cama_asignada_id"),
|
| 82 |
+
origen=d.get("origen"),
|
| 83 |
+
turno_id=d.get("turno_id"),
|
| 84 |
+
diagnostico_ingreso=d.get("diagnostico_ingreso"),
|
| 85 |
+
obra_social_id=d.get("obra_social_id"),
|
| 86 |
+
numero_afiliado=d.get("numero_afiliado"),
|
| 87 |
+
prioridad=d.get("prioridad"),
|
| 88 |
+
observaciones=d.get("observaciones"),
|
| 89 |
+
hospital_id=d.get("hospital_id"),
|
| 90 |
+
cama_origen_id=d.get("cama_origen_id"),
|
| 91 |
+
cama_destino_solicitada_id=d.get("cama_destino_solicitada_id"),
|
| 92 |
+
motivo_traslado=d.get("motivo_traslado"),
|
| 93 |
+
accion=d.get("accion"),
|
| 94 |
+
motivo=d.get("motivo"),
|
| 95 |
+
resuelto_por=d.get("resuelto_por"),
|
| 96 |
+
timestamp_solicitud=d.get("timestamp_solicitud"),
|
| 97 |
+
timestamp_resolucion=d.get("timestamp_resolucion"),
|
| 98 |
+
)
|
app/routers/camas.py
CHANGED
|
@@ -2,7 +2,7 @@ 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
|
| 6 |
|
| 7 |
from app.dependencies import get_db, require_roles
|
| 8 |
from app.schemas.cama import (
|
|
@@ -37,7 +37,7 @@ def get_disponibilidad(
|
|
| 37 |
hasta: datetime = Query(...),
|
| 38 |
hospital_id: Optional[str] = Query(None),
|
| 39 |
specialty_id: Optional[int] = Query(None),
|
| 40 |
-
db:
|
| 41 |
user: dict = Depends(require_roles("ADMINISTRATIVO", "MEDICO")),
|
| 42 |
):
|
| 43 |
quirofanos = cama_service.get_disponibilidad_quirofanos(db, desde, hasta, hospital_id, specialty_id)
|
|
@@ -74,7 +74,7 @@ def get_camas(
|
|
| 74 |
sector: Optional[str] = Query(None),
|
| 75 |
estado: Optional[EstadoCamaEnum] = Query(None),
|
| 76 |
hospital_id: Optional[str] = Query(None),
|
| 77 |
-
db:
|
| 78 |
user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO", "LIMPIEZA")),
|
| 79 |
):
|
| 80 |
camas = cama_service.get_camas(db, user["rol"], piso, sector, estado.value if estado else None, hospital_id)
|
|
@@ -100,7 +100,7 @@ def get_camas(
|
|
| 100 |
)
|
| 101 |
def crear_cama(
|
| 102 |
data: CamaCreateRequest,
|
| 103 |
-
db:
|
| 104 |
user: dict = Depends(require_roles("ADMINISTRATIVO")),
|
| 105 |
):
|
| 106 |
cama = cama_service.create_cama(db, data)
|
|
@@ -115,7 +115,7 @@ def crear_cama(
|
|
| 115 |
)
|
| 116 |
def get_cama(
|
| 117 |
cama_id: int,
|
| 118 |
-
db:
|
| 119 |
user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
|
| 120 |
):
|
| 121 |
cama = cama_service.get_cama(db, cama_id)
|
|
@@ -131,7 +131,7 @@ def get_cama(
|
|
| 131 |
def update_cama(
|
| 132 |
cama_id: int,
|
| 133 |
data: CamaUpdateRequest,
|
| 134 |
-
db:
|
| 135 |
user: dict = Depends(require_roles("ADMINISTRATIVO", "LIMPIEZA")),
|
| 136 |
):
|
| 137 |
cama = cama_service.update_cama(db, cama_id, data, user["rol"])
|
|
@@ -146,7 +146,7 @@ def update_cama(
|
|
| 146 |
)
|
| 147 |
def delete_cama(
|
| 148 |
cama_id: int,
|
| 149 |
-
db:
|
| 150 |
user: dict = Depends(require_roles("ADMINISTRATIVO")),
|
| 151 |
):
|
| 152 |
cama = cama_service.delete_cama(db, cama_id)
|
|
@@ -164,7 +164,7 @@ def delete_cama(
|
|
| 164 |
def asignar_cama(
|
| 165 |
cama_id: int,
|
| 166 |
data: AsignacionCamaRequest,
|
| 167 |
-
db:
|
| 168 |
user: dict = Depends(require_roles("ADMINISTRATIVO")),
|
| 169 |
):
|
| 170 |
cama = cama_service.asignar_cama(db, cama_id, data.tipo, data.paciente_id, data.cama_origen_id)
|
|
@@ -192,7 +192,7 @@ def get_reservas(
|
|
| 192 |
prioridad: Optional[str] = Query(None),
|
| 193 |
fecha_desde: Optional[datetime] = Query(None),
|
| 194 |
fecha_hasta: Optional[datetime] = Query(None),
|
| 195 |
-
db:
|
| 196 |
user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
|
| 197 |
):
|
| 198 |
reservas = cama_service.get_reservas(
|
|
@@ -215,7 +215,7 @@ def get_reservas(
|
|
| 215 |
def crear_reserva(
|
| 216 |
cama_id: int,
|
| 217 |
data: ReservaQuirofanoCreateRequest,
|
| 218 |
-
db:
|
| 219 |
user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
|
| 220 |
):
|
| 221 |
reserva, created = cama_service.create_reserva(db, cama_id, data)
|
|
@@ -233,7 +233,7 @@ def crear_reserva(
|
|
| 233 |
def get_reserva(
|
| 234 |
cama_id: int,
|
| 235 |
reserva_id: int,
|
| 236 |
-
db:
|
| 237 |
user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
|
| 238 |
):
|
| 239 |
reserva = cama_service.get_reserva(db, cama_id, reserva_id)
|
|
@@ -250,7 +250,7 @@ def update_reserva(
|
|
| 250 |
cama_id: int,
|
| 251 |
reserva_id: int,
|
| 252 |
data: ReservaEstadoUpdateRequest,
|
| 253 |
-
db:
|
| 254 |
user: dict = Depends(require_roles("ADMINISTRATIVO")),
|
| 255 |
):
|
| 256 |
reserva = cama_service.update_reserva_estado(db, cama_id, reserva_id, data)
|
|
|
|
| 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 (
|
|
|
|
| 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)
|
|
|
|
| 74 |
sector: Optional[str] = Query(None),
|
| 75 |
estado: Optional[EstadoCamaEnum] = Query(None),
|
| 76 |
hospital_id: Optional[str] = Query(None),
|
| 77 |
+
db: Client = Depends(get_db),
|
| 78 |
user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO", "LIMPIEZA")),
|
| 79 |
):
|
| 80 |
camas = cama_service.get_camas(db, user["rol"], piso, sector, estado.value if estado else None, hospital_id)
|
|
|
|
| 100 |
)
|
| 101 |
def crear_cama(
|
| 102 |
data: CamaCreateRequest,
|
| 103 |
+
db: Client = Depends(get_db),
|
| 104 |
user: dict = Depends(require_roles("ADMINISTRATIVO")),
|
| 105 |
):
|
| 106 |
cama = cama_service.create_cama(db, data)
|
|
|
|
| 115 |
)
|
| 116 |
def get_cama(
|
| 117 |
cama_id: int,
|
| 118 |
+
db: Client = Depends(get_db),
|
| 119 |
user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
|
| 120 |
):
|
| 121 |
cama = cama_service.get_cama(db, cama_id)
|
|
|
|
| 131 |
def update_cama(
|
| 132 |
cama_id: int,
|
| 133 |
data: CamaUpdateRequest,
|
| 134 |
+
db: Client = Depends(get_db),
|
| 135 |
user: dict = Depends(require_roles("ADMINISTRATIVO", "LIMPIEZA")),
|
| 136 |
):
|
| 137 |
cama = cama_service.update_cama(db, cama_id, data, user["rol"])
|
|
|
|
| 146 |
)
|
| 147 |
def delete_cama(
|
| 148 |
cama_id: int,
|
| 149 |
+
db: Client = Depends(get_db),
|
| 150 |
user: dict = Depends(require_roles("ADMINISTRATIVO")),
|
| 151 |
):
|
| 152 |
cama = cama_service.delete_cama(db, cama_id)
|
|
|
|
| 164 |
def asignar_cama(
|
| 165 |
cama_id: int,
|
| 166 |
data: AsignacionCamaRequest,
|
| 167 |
+
db: Client = Depends(get_db),
|
| 168 |
user: dict = Depends(require_roles("ADMINISTRATIVO")),
|
| 169 |
):
|
| 170 |
cama = cama_service.asignar_cama(db, cama_id, data.tipo, data.paciente_id, data.cama_origen_id)
|
|
|
|
| 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(
|
|
|
|
| 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)
|
|
|
|
| 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)
|
|
|
|
| 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)
|
app/routers/solicitudes.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
from typing import Optional
|
| 2 |
from fastapi import APIRouter, Depends, Query
|
| 3 |
-
from
|
| 4 |
|
| 5 |
from app.dependencies import get_db, require_roles
|
| 6 |
from app.schemas.solicitud import SolicitudResponse, SolicitudesListResponse, SolicitudResolucionRequest
|
|
@@ -20,7 +20,7 @@ def get_solicitudes(
|
|
| 20 |
estado: Optional[EstadoSolicitudEnum] = Query(None),
|
| 21 |
tipo: Optional[TipoSolicitudEnum] = Query(None),
|
| 22 |
hospital_id: Optional[str] = Query(None),
|
| 23 |
-
db:
|
| 24 |
user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
|
| 25 |
):
|
| 26 |
solicitudes = solicitud_service.get_solicitudes(
|
|
@@ -44,7 +44,7 @@ def get_solicitudes(
|
|
| 44 |
)
|
| 45 |
def get_solicitud(
|
| 46 |
solicitud_id: str,
|
| 47 |
-
db:
|
| 48 |
user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
|
| 49 |
):
|
| 50 |
sol = solicitud_service.get_solicitud(db, solicitud_id)
|
|
@@ -67,7 +67,7 @@ def get_solicitud(
|
|
| 67 |
def resolver_solicitud(
|
| 68 |
solicitud_id: str,
|
| 69 |
data: SolicitudResolucionRequest,
|
| 70 |
-
db:
|
| 71 |
user: dict = Depends(require_roles("ADMINISTRATIVO")),
|
| 72 |
):
|
| 73 |
sol = solicitud_service.resolver_solicitud(
|
|
|
|
| 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
|
|
|
|
| 20 |
estado: Optional[EstadoSolicitudEnum] = Query(None),
|
| 21 |
tipo: Optional[TipoSolicitudEnum] = Query(None),
|
| 22 |
hospital_id: Optional[str] = Query(None),
|
| 23 |
+
db: Client = Depends(get_db),
|
| 24 |
user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
|
| 25 |
):
|
| 26 |
solicitudes = solicitud_service.get_solicitudes(
|
|
|
|
| 44 |
)
|
| 45 |
def get_solicitud(
|
| 46 |
solicitud_id: str,
|
| 47 |
+
db: Client = Depends(get_db),
|
| 48 |
user: dict = Depends(require_roles("MEDICO", "ADMINISTRATIVO")),
|
| 49 |
):
|
| 50 |
sol = solicitud_service.get_solicitud(db, solicitud_id)
|
|
|
|
| 67 |
def resolver_solicitud(
|
| 68 |
solicitud_id: str,
|
| 69 |
data: SolicitudResolucionRequest,
|
| 70 |
+
db: Client = Depends(get_db),
|
| 71 |
user: dict = Depends(require_roles("ADMINISTRATIVO")),
|
| 72 |
):
|
| 73 |
sol = solicitud_service.resolver_solicitud(
|
app/routers/webhooks.py
CHANGED
|
@@ -3,7 +3,7 @@ Webhooks entrantes: recibe llamadas de M1 (HCE), M2 (Turnos) y M9 (Monitoreo).
|
|
| 3 |
"""
|
| 4 |
from fastapi import APIRouter, Depends, status
|
| 5 |
from fastapi.responses import JSONResponse
|
| 6 |
-
from
|
| 7 |
|
| 8 |
from app.dependencies import get_db, get_current_user
|
| 9 |
from app.schemas.solicitud import (
|
|
@@ -36,7 +36,7 @@ router_turnos = APIRouter(tags=["Webhooks Entrantes"])
|
|
| 36 |
)
|
| 37 |
def recibir_solicitud(
|
| 38 |
data: SolicitudHceWebhook,
|
| 39 |
-
db:
|
| 40 |
user: dict = Depends(get_current_user),
|
| 41 |
):
|
| 42 |
sol = solicitud_service.recibir_solicitud(db, data)
|
|
@@ -55,7 +55,7 @@ def recibir_solicitud(
|
|
| 55 |
)
|
| 56 |
def recibir_alta_medica(
|
| 57 |
data: AltaMedicaWebhook,
|
| 58 |
-
db:
|
| 59 |
user: dict = Depends(get_current_user),
|
| 60 |
):
|
| 61 |
cama = solicitud_service.procesar_alta_medica(db, data.paciente_id)
|
|
@@ -77,7 +77,7 @@ def recibir_alta_medica(
|
|
| 77 |
)
|
| 78 |
def recibir_cirugia_urgente(
|
| 79 |
data: CirugiaUrgenteWebhook,
|
| 80 |
-
db:
|
| 81 |
user: dict = Depends(get_current_user),
|
| 82 |
):
|
| 83 |
reserva_urgente, reserva_desplazada = cama_service.crear_reserva_urgente(db, data)
|
|
@@ -117,7 +117,7 @@ def recibir_cirugia_urgente(
|
|
| 117 |
def cancelar_reserva_quirofano(
|
| 118 |
turno_id: str,
|
| 119 |
data: CancelacionQuirofanoRequest,
|
| 120 |
-
db:
|
| 121 |
user: dict = Depends(get_current_user),
|
| 122 |
):
|
| 123 |
reserva = solicitud_service.cancelar_reserva_por_turno(db, turno_id, data.motivo)
|
|
@@ -140,7 +140,7 @@ def cancelar_reserva_quirofano(
|
|
| 140 |
)
|
| 141 |
def recibir_alerta_emergencia(
|
| 142 |
data: AlertaEmergenciaRequest,
|
| 143 |
-
db:
|
| 144 |
user: dict = Depends(get_current_user),
|
| 145 |
):
|
| 146 |
cama = solicitud_service.procesar_alerta_emergencia(db, data.paciente_id)
|
|
@@ -159,7 +159,7 @@ def recibir_alerta_emergencia(
|
|
| 159 |
)
|
| 160 |
def recibir_alerta_resuelta(
|
| 161 |
data: AlertaResueltaRequest,
|
| 162 |
-
db:
|
| 163 |
user: dict = Depends(get_current_user),
|
| 164 |
):
|
| 165 |
cama = solicitud_service.procesar_alerta_resuelta(db, data.paciente_id)
|
|
|
|
| 3 |
"""
|
| 4 |
from fastapi import APIRouter, Depends, status
|
| 5 |
from fastapi.responses import JSONResponse
|
| 6 |
+
from supabase import Client
|
| 7 |
|
| 8 |
from app.dependencies import get_db, get_current_user
|
| 9 |
from app.schemas.solicitud import (
|
|
|
|
| 36 |
)
|
| 37 |
def recibir_solicitud(
|
| 38 |
data: SolicitudHceWebhook,
|
| 39 |
+
db: Client = Depends(get_db),
|
| 40 |
user: dict = Depends(get_current_user),
|
| 41 |
):
|
| 42 |
sol = solicitud_service.recibir_solicitud(db, data)
|
|
|
|
| 55 |
)
|
| 56 |
def recibir_alta_medica(
|
| 57 |
data: AltaMedicaWebhook,
|
| 58 |
+
db: Client = Depends(get_db),
|
| 59 |
user: dict = Depends(get_current_user),
|
| 60 |
):
|
| 61 |
cama = solicitud_service.procesar_alta_medica(db, data.paciente_id)
|
|
|
|
| 77 |
)
|
| 78 |
def recibir_cirugia_urgente(
|
| 79 |
data: CirugiaUrgenteWebhook,
|
| 80 |
+
db: Client = Depends(get_db),
|
| 81 |
user: dict = Depends(get_current_user),
|
| 82 |
):
|
| 83 |
reserva_urgente, reserva_desplazada = cama_service.crear_reserva_urgente(db, data)
|
|
|
|
| 117 |
def cancelar_reserva_quirofano(
|
| 118 |
turno_id: str,
|
| 119 |
data: CancelacionQuirofanoRequest,
|
| 120 |
+
db: Client = Depends(get_db),
|
| 121 |
user: dict = Depends(get_current_user),
|
| 122 |
):
|
| 123 |
reserva = solicitud_service.cancelar_reserva_por_turno(db, turno_id, data.motivo)
|
|
|
|
| 140 |
)
|
| 141 |
def recibir_alerta_emergencia(
|
| 142 |
data: AlertaEmergenciaRequest,
|
| 143 |
+
db: Client = Depends(get_db),
|
| 144 |
user: dict = Depends(get_current_user),
|
| 145 |
):
|
| 146 |
cama = solicitud_service.procesar_alerta_emergencia(db, data.paciente_id)
|
|
|
|
| 159 |
)
|
| 160 |
def recibir_alerta_resuelta(
|
| 161 |
data: AlertaResueltaRequest,
|
| 162 |
+
db: Client = Depends(get_db),
|
| 163 |
user: dict = Depends(get_current_user),
|
| 164 |
):
|
| 165 |
cama = solicitud_service.procesar_alerta_resuelta(db, data.paciente_id)
|
app/services/cama_service.py
CHANGED
|
@@ -4,7 +4,7 @@ Lógica de negocio para Camas y Reservas de Quirófano.
|
|
| 4 |
from __future__ import annotations
|
| 5 |
from datetime import datetime, timezone
|
| 6 |
from fastapi import HTTPException
|
| 7 |
-
from
|
| 8 |
|
| 9 |
from app.models.cama import Cama
|
| 10 |
from app.models.reserva import ReservaQuirofano
|
|
@@ -32,7 +32,7 @@ _ERR_RESERVA_NOT_FOUND = {"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "Reserva
|
|
| 32 |
|
| 33 |
# ─── Helpers ───────────────────────────────────────────────────────────────
|
| 34 |
|
| 35 |
-
def _get_cama_or_404(db:
|
| 36 |
cama = cama_crud.get_by_id(db, cama_id)
|
| 37 |
if not cama:
|
| 38 |
raise HTTPException(status_code=404, detail=_ERR_CAMA_NOT_FOUND)
|
|
@@ -60,7 +60,7 @@ def _verificar_contraindicaciones(paciente_id: int, cama: Cama) -> None:
|
|
| 60 |
# ─── Camas ─────────────────────────────────────────────────────────────────
|
| 61 |
|
| 62 |
def get_camas(
|
| 63 |
-
db:
|
| 64 |
rol: str,
|
| 65 |
piso: int | None = None,
|
| 66 |
sector: str | None = None,
|
|
@@ -70,15 +70,15 @@ def get_camas(
|
|
| 70 |
return cama_crud.get_all(db, rol, piso, sector, estado, hospital_id)
|
| 71 |
|
| 72 |
|
| 73 |
-
def create_cama(db:
|
| 74 |
return cama_crud.create(db, data)
|
| 75 |
|
| 76 |
|
| 77 |
-
def get_cama(db:
|
| 78 |
return _get_cama_or_404(db, cama_id)
|
| 79 |
|
| 80 |
|
| 81 |
-
def update_cama(db:
|
| 82 |
cama = _get_cama_or_404(db, cama_id)
|
| 83 |
|
| 84 |
if data.estado is not None:
|
|
@@ -130,7 +130,7 @@ def update_cama(db: Session, cama_id: int, data: CamaUpdateRequest, rol: str) ->
|
|
| 130 |
return cama_crud.save(db, cama)
|
| 131 |
|
| 132 |
|
| 133 |
-
def delete_cama(db:
|
| 134 |
cama = _get_cama_or_404(db, cama_id)
|
| 135 |
if cama.estado in (
|
| 136 |
EstadoCamaEnum.OCUPADA.value,
|
|
@@ -155,7 +155,7 @@ def delete_cama(db: Session, cama_id: int) -> Cama:
|
|
| 155 |
return cama_crud.save(db, cama)
|
| 156 |
|
| 157 |
|
| 158 |
-
def asignar_cama(db:
|
| 159 |
cama_destino = _get_cama_or_404(db, cama_id)
|
| 160 |
|
| 161 |
if cama_destino.estado != EstadoCamaEnum.DISPONIBLE.value:
|
|
@@ -180,6 +180,7 @@ def asignar_cama(db: Session, cama_id: int, tipo: str, paciente_id: int, cama_or
|
|
| 180 |
cama_origen.estado = EstadoCamaEnum.EN_LIMPIEZA.value
|
| 181 |
cama_origen.ultimo_movimiento_tipo = "TRASLADO"
|
| 182 |
cama_origen.ultima_actualizacion = datetime.now(timezone.utc)
|
|
|
|
| 183 |
hce.notify_movimiento("TRASLADO", paciente_id, cama_id, cama_origen_id)
|
| 184 |
monitoreo.notify_baja(paciente_id)
|
| 185 |
monitoreo.notify_alta(paciente_id)
|
|
@@ -196,7 +197,7 @@ def asignar_cama(db: Session, cama_id: int, tipo: str, paciente_id: int, cama_or
|
|
| 196 |
# ─── Reservas de Quirófano ─────────────────────────────────────────────────
|
| 197 |
|
| 198 |
def get_reservas(
|
| 199 |
-
db:
|
| 200 |
cama_id: int,
|
| 201 |
estado: str | None = None,
|
| 202 |
prioridad: str | None = None,
|
|
@@ -213,7 +214,7 @@ def get_reservas(
|
|
| 213 |
|
| 214 |
|
| 215 |
def create_reserva(
|
| 216 |
-
db:
|
| 217 |
) -> tuple[ReservaQuirofano, bool]:
|
| 218 |
"""Retorna (reserva, created). created=False si ya existía (idempotencia)."""
|
| 219 |
cama = _get_cama_or_404(db, cama_id)
|
|
@@ -253,7 +254,7 @@ def create_reserva(
|
|
| 253 |
return reserva_crud.create_programada(db, cama_id, data), True
|
| 254 |
|
| 255 |
|
| 256 |
-
def get_reserva(db:
|
| 257 |
_get_cama_or_404(db, cama_id)
|
| 258 |
r = reserva_crud.get_by_cama_and_id(db, cama_id, reserva_id)
|
| 259 |
if not r:
|
|
@@ -262,7 +263,7 @@ def get_reserva(db: Session, cama_id: int, reserva_id: int) -> ReservaQuirofano:
|
|
| 262 |
|
| 263 |
|
| 264 |
def update_reserva_estado(
|
| 265 |
-
db:
|
| 266 |
) -> ReservaQuirofano:
|
| 267 |
reserva = get_reserva(db, cama_id, reserva_id)
|
| 268 |
cama = _get_cama_or_404(db, cama_id)
|
|
@@ -294,11 +295,12 @@ def update_reserva_estado(
|
|
| 294 |
cama.ultimo_movimiento_tipo = "ALTA"
|
| 295 |
|
| 296 |
cama.ultima_actualizacion = datetime.now(timezone.utc)
|
|
|
|
| 297 |
return reserva_crud.save(db, reserva)
|
| 298 |
|
| 299 |
|
| 300 |
def get_disponibilidad_quirofanos(
|
| 301 |
-
db:
|
| 302 |
desde: datetime,
|
| 303 |
hasta: datetime,
|
| 304 |
hospital_id: str | None = None,
|
|
@@ -321,7 +323,7 @@ def get_disponibilidad_quirofanos(
|
|
| 321 |
|
| 322 |
|
| 323 |
def crear_reserva_urgente(
|
| 324 |
-
db:
|
| 325 |
) -> tuple[ReservaQuirofano, ReservaQuirofano | None]:
|
| 326 |
"""
|
| 327 |
Crea una reserva urgente (EMERGENCIA, prioridad URGENTE).
|
|
@@ -346,9 +348,7 @@ def crear_reserva_urgente(
|
|
| 346 |
break
|
| 347 |
|
| 348 |
if cama_libre:
|
| 349 |
-
reserva = reserva_crud.
|
| 350 |
-
db.commit()
|
| 351 |
-
db.refresh(reserva)
|
| 352 |
return reserva, None
|
| 353 |
|
| 354 |
candidata = _find_desplazable(db, quirofanos, data.fecha_hora_inicio, data.fecha_hora_fin_estimada)
|
|
@@ -363,7 +363,6 @@ def crear_reserva_urgente(
|
|
| 363 |
|
| 364 |
candidata_cama_id = candidata.cama_id
|
| 365 |
candidata.estado = EstadoReservaEnum.CANCELADA.value
|
| 366 |
-
candidata.desplazada_por_reserva_id = None
|
| 367 |
|
| 368 |
if candidata.turno_id:
|
| 369 |
turnos.notify_resultado_quirofano(
|
|
@@ -374,17 +373,15 @@ def crear_reserva_urgente(
|
|
| 374 |
motivo=getattr(data, "diagnostico", None),
|
| 375 |
)
|
| 376 |
|
| 377 |
-
reserva_urgente = reserva_crud.
|
| 378 |
candidata.desplazada_por_reserva_id = reserva_urgente.id
|
| 379 |
-
|
| 380 |
-
db.refresh(reserva_urgente)
|
| 381 |
-
db.refresh(candidata)
|
| 382 |
|
| 383 |
return reserva_urgente, candidata
|
| 384 |
|
| 385 |
|
| 386 |
def _find_desplazable(
|
| 387 |
-
db:
|
| 388 |
) -> ReservaQuirofano | None:
|
| 389 |
candidata = None
|
| 390 |
for q in quirofanos:
|
|
|
|
| 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.cama import Cama
|
| 10 |
from app.models.reserva import ReservaQuirofano
|
|
|
|
| 32 |
|
| 33 |
# ─── Helpers ───────────────────────────────────────────────────────────────
|
| 34 |
|
| 35 |
+
def _get_cama_or_404(db: Client, cama_id: int) -> Cama:
|
| 36 |
cama = cama_crud.get_by_id(db, cama_id)
|
| 37 |
if not cama:
|
| 38 |
raise HTTPException(status_code=404, detail=_ERR_CAMA_NOT_FOUND)
|
|
|
|
| 60 |
# ─── Camas ─────────────────────────────────────────────────────────────────
|
| 61 |
|
| 62 |
def get_camas(
|
| 63 |
+
db: Client,
|
| 64 |
rol: str,
|
| 65 |
piso: int | None = None,
|
| 66 |
sector: str | None = None,
|
|
|
|
| 70 |
return cama_crud.get_all(db, rol, piso, sector, estado, hospital_id)
|
| 71 |
|
| 72 |
|
| 73 |
+
def create_cama(db: Client, data: CamaCreateRequest) -> Cama:
|
| 74 |
return cama_crud.create(db, data)
|
| 75 |
|
| 76 |
|
| 77 |
+
def get_cama(db: Client, cama_id: int) -> Cama:
|
| 78 |
return _get_cama_or_404(db, cama_id)
|
| 79 |
|
| 80 |
|
| 81 |
+
def update_cama(db: Client, cama_id: int, data: CamaUpdateRequest, rol: str) -> Cama:
|
| 82 |
cama = _get_cama_or_404(db, cama_id)
|
| 83 |
|
| 84 |
if data.estado is not None:
|
|
|
|
| 130 |
return cama_crud.save(db, cama)
|
| 131 |
|
| 132 |
|
| 133 |
+
def delete_cama(db: Client, cama_id: int) -> Cama:
|
| 134 |
cama = _get_cama_or_404(db, cama_id)
|
| 135 |
if cama.estado in (
|
| 136 |
EstadoCamaEnum.OCUPADA.value,
|
|
|
|
| 155 |
return cama_crud.save(db, cama)
|
| 156 |
|
| 157 |
|
| 158 |
+
def asignar_cama(db: Client, cama_id: int, tipo: str, paciente_id: int, cama_origen_id: int | None) -> Cama:
|
| 159 |
cama_destino = _get_cama_or_404(db, cama_id)
|
| 160 |
|
| 161 |
if cama_destino.estado != EstadoCamaEnum.DISPONIBLE.value:
|
|
|
|
| 180 |
cama_origen.estado = EstadoCamaEnum.EN_LIMPIEZA.value
|
| 181 |
cama_origen.ultimo_movimiento_tipo = "TRASLADO"
|
| 182 |
cama_origen.ultima_actualizacion = datetime.now(timezone.utc)
|
| 183 |
+
cama_crud.save(db, cama_origen)
|
| 184 |
hce.notify_movimiento("TRASLADO", paciente_id, cama_id, cama_origen_id)
|
| 185 |
monitoreo.notify_baja(paciente_id)
|
| 186 |
monitoreo.notify_alta(paciente_id)
|
|
|
|
| 197 |
# ─── Reservas de Quirófano ─────────────────────────────────────────────────
|
| 198 |
|
| 199 |
def get_reservas(
|
| 200 |
+
db: Client,
|
| 201 |
cama_id: int,
|
| 202 |
estado: str | None = None,
|
| 203 |
prioridad: str | None = None,
|
|
|
|
| 214 |
|
| 215 |
|
| 216 |
def create_reserva(
|
| 217 |
+
db: Client, cama_id: int, data: ReservaQuirofanoCreateRequest
|
| 218 |
) -> tuple[ReservaQuirofano, bool]:
|
| 219 |
"""Retorna (reserva, created). created=False si ya existía (idempotencia)."""
|
| 220 |
cama = _get_cama_or_404(db, cama_id)
|
|
|
|
| 254 |
return reserva_crud.create_programada(db, cama_id, data), True
|
| 255 |
|
| 256 |
|
| 257 |
+
def get_reserva(db: Client, cama_id: int, reserva_id: int) -> ReservaQuirofano:
|
| 258 |
_get_cama_or_404(db, cama_id)
|
| 259 |
r = reserva_crud.get_by_cama_and_id(db, cama_id, reserva_id)
|
| 260 |
if not r:
|
|
|
|
| 263 |
|
| 264 |
|
| 265 |
def update_reserva_estado(
|
| 266 |
+
db: Client, cama_id: int, reserva_id: int, data: ReservaEstadoUpdateRequest
|
| 267 |
) -> ReservaQuirofano:
|
| 268 |
reserva = get_reserva(db, cama_id, reserva_id)
|
| 269 |
cama = _get_cama_or_404(db, cama_id)
|
|
|
|
| 295 |
cama.ultimo_movimiento_tipo = "ALTA"
|
| 296 |
|
| 297 |
cama.ultima_actualizacion = datetime.now(timezone.utc)
|
| 298 |
+
cama_crud.save(db, cama)
|
| 299 |
return reserva_crud.save(db, reserva)
|
| 300 |
|
| 301 |
|
| 302 |
def get_disponibilidad_quirofanos(
|
| 303 |
+
db: Client,
|
| 304 |
desde: datetime,
|
| 305 |
hasta: datetime,
|
| 306 |
hospital_id: str | None = None,
|
|
|
|
| 323 |
|
| 324 |
|
| 325 |
def crear_reserva_urgente(
|
| 326 |
+
db: Client, data: CirugiaUrgenteWebhook
|
| 327 |
) -> tuple[ReservaQuirofano, ReservaQuirofano | None]:
|
| 328 |
"""
|
| 329 |
Crea una reserva urgente (EMERGENCIA, prioridad URGENTE).
|
|
|
|
| 348 |
break
|
| 349 |
|
| 350 |
if cama_libre:
|
| 351 |
+
reserva = reserva_crud.create_urgente(db, cama_libre.id, data)
|
|
|
|
|
|
|
| 352 |
return reserva, None
|
| 353 |
|
| 354 |
candidata = _find_desplazable(db, quirofanos, data.fecha_hora_inicio, data.fecha_hora_fin_estimada)
|
|
|
|
| 363 |
|
| 364 |
candidata_cama_id = candidata.cama_id
|
| 365 |
candidata.estado = EstadoReservaEnum.CANCELADA.value
|
|
|
|
| 366 |
|
| 367 |
if candidata.turno_id:
|
| 368 |
turnos.notify_resultado_quirofano(
|
|
|
|
| 373 |
motivo=getattr(data, "diagnostico", None),
|
| 374 |
)
|
| 375 |
|
| 376 |
+
reserva_urgente = reserva_crud.create_urgente(db, candidata_cama_id, data)
|
| 377 |
candidata.desplazada_por_reserva_id = reserva_urgente.id
|
| 378 |
+
reserva_crud.save(db, candidata)
|
|
|
|
|
|
|
| 379 |
|
| 380 |
return reserva_urgente, candidata
|
| 381 |
|
| 382 |
|
| 383 |
def _find_desplazable(
|
| 384 |
+
db: Client, quirofanos: list[Cama], inicio: datetime, fin: datetime
|
| 385 |
) -> ReservaQuirofano | None:
|
| 386 |
candidata = None
|
| 387 |
for q in quirofanos:
|
app/services/solicitud_service.py
CHANGED
|
@@ -4,7 +4,7 @@ Lógica de negocio para Solicitudes de Internación / Traslado.
|
|
| 4 |
from __future__ import annotations
|
| 5 |
from datetime import datetime, timezone
|
| 6 |
from fastapi import HTTPException
|
| 7 |
-
from
|
| 8 |
|
| 9 |
from app.models.solicitud import Solicitud
|
| 10 |
from app.models.cama import Cama
|
|
@@ -32,7 +32,7 @@ def _parse_solicitud_id(solicitud_id: str) -> int:
|
|
| 32 |
)
|
| 33 |
|
| 34 |
|
| 35 |
-
def _get_solicitud_or_404(db:
|
| 36 |
num_id = _parse_solicitud_id(solicitud_id)
|
| 37 |
sol = solicitud_crud.get_by_id(db, num_id)
|
| 38 |
if not sol:
|
|
@@ -40,7 +40,7 @@ def _get_solicitud_or_404(db: Session, solicitud_id: str) -> Solicitud:
|
|
| 40 |
return sol
|
| 41 |
|
| 42 |
|
| 43 |
-
def _get_cama_or_404(db:
|
| 44 |
c = cama_crud.get_by_id(db, cama_id)
|
| 45 |
if not c:
|
| 46 |
raise HTTPException(
|
|
@@ -66,7 +66,7 @@ def _verificar_contraindicaciones(paciente_id: int, cama: Cama) -> None:
|
|
| 66 |
|
| 67 |
# ─── Recibir solicitud desde HCE (M1) ─────────────────────────────────────
|
| 68 |
|
| 69 |
-
def recibir_solicitud(db:
|
| 70 |
existing = solicitud_crud.get_by_hce_id(db, data.solicitud_hce_id)
|
| 71 |
if existing:
|
| 72 |
return existing
|
|
@@ -76,7 +76,7 @@ def recibir_solicitud(db: Session, data: SolicitudHceWebhook) -> Solicitud:
|
|
| 76 |
# ─── Listar / obtener solicitudes ──────────────────────────────────────────
|
| 77 |
|
| 78 |
def get_solicitudes(
|
| 79 |
-
db:
|
| 80 |
estado: str | None = None,
|
| 81 |
tipo: str | None = None,
|
| 82 |
hospital_id: str | None = None,
|
|
@@ -84,14 +84,14 @@ def get_solicitudes(
|
|
| 84 |
return solicitud_crud.get_all(db, estado, tipo, hospital_id)
|
| 85 |
|
| 86 |
|
| 87 |
-
def get_solicitud(db:
|
| 88 |
return _get_solicitud_or_404(db, solicitud_id)
|
| 89 |
|
| 90 |
|
| 91 |
# ─── Resolver solicitud ────────────────────────────────────────────────────
|
| 92 |
|
| 93 |
def resolver_solicitud(
|
| 94 |
-
db:
|
| 95 |
solicitud_id: str,
|
| 96 |
data: SolicitudResolucionRequest,
|
| 97 |
resuelto_por: int,
|
|
@@ -139,7 +139,7 @@ def _rechazar(sol: Solicitud, motivo: str | None, resuelto_por: int) -> None:
|
|
| 139 |
|
| 140 |
|
| 141 |
def _aprobar_internacion(
|
| 142 |
-
db:
|
| 143 |
) -> None:
|
| 144 |
paciente = core.validate_patient(sol.paciente_id)
|
| 145 |
if not paciente:
|
|
@@ -160,6 +160,7 @@ def _aprobar_internacion(
|
|
| 160 |
cama.estado = EstadoCamaEnum.OCUPADA.value
|
| 161 |
cama.paciente_id = sol.paciente_id
|
| 162 |
cama.ultima_actualizacion = datetime.now(timezone.utc)
|
|
|
|
| 163 |
|
| 164 |
sol.estado = "APROBADA"
|
| 165 |
sol.accion = accion
|
|
@@ -174,7 +175,7 @@ def _aprobar_internacion(
|
|
| 174 |
|
| 175 |
|
| 176 |
def _aprobar_traslado(
|
| 177 |
-
db:
|
| 178 |
) -> None:
|
| 179 |
dest_id = cama_destino_id or sol.cama_destino_solicitada_id
|
| 180 |
if not dest_id:
|
|
@@ -197,10 +198,12 @@ def _aprobar_traslado(
|
|
| 197 |
cama_origen.estado = EstadoCamaEnum.EN_LIMPIEZA.value
|
| 198 |
cama_origen.ultimo_movimiento_tipo = "TRASLADO"
|
| 199 |
cama_origen.ultima_actualizacion = datetime.now(timezone.utc)
|
|
|
|
| 200 |
|
| 201 |
cama_destino.estado = EstadoCamaEnum.OCUPADA.value
|
| 202 |
cama_destino.paciente_id = sol.paciente_id
|
| 203 |
cama_destino.ultima_actualizacion = datetime.now(timezone.utc)
|
|
|
|
| 204 |
|
| 205 |
sol.estado = "APROBADA"
|
| 206 |
sol.accion = accion
|
|
@@ -217,7 +220,7 @@ def _aprobar_traslado(
|
|
| 217 |
|
| 218 |
# ─── Alta médica (desde HCE M1) ────────────────────────────────────────────
|
| 219 |
|
| 220 |
-
def procesar_alta_medica(db:
|
| 221 |
cama = cama_crud.get_by_paciente(db, paciente_id, ["OCUPADA", "CODIGO_ROJO"])
|
| 222 |
if not cama:
|
| 223 |
raise HTTPException(
|
|
@@ -234,7 +237,7 @@ def procesar_alta_medica(db: Session, paciente_id: int) -> Cama:
|
|
| 234 |
|
| 235 |
# ─── Alertas de emergencia (desde M9) ──────────────────────────────────────
|
| 236 |
|
| 237 |
-
def procesar_alerta_emergencia(db:
|
| 238 |
cama = cama_crud.get_by_paciente(db, paciente_id, ["OCUPADA"])
|
| 239 |
if not cama:
|
| 240 |
raise HTTPException(
|
|
@@ -244,12 +247,11 @@ def procesar_alerta_emergencia(db: Session, paciente_id: int) -> Cama:
|
|
| 244 |
cama.estado = EstadoCamaEnum.CODIGO_ROJO.value
|
| 245 |
cama.ultima_actualizacion = datetime.now(timezone.utc)
|
| 246 |
cama_crud.save(db, cama)
|
| 247 |
-
# episodio_id se resolverá cuando se implemente la entidad Episodio
|
| 248 |
hce.notify_evento_episodio(0, "CODIGO_ROJO", f"Alerta de emergencia detectada para paciente {paciente_id}")
|
| 249 |
return cama
|
| 250 |
|
| 251 |
|
| 252 |
-
def procesar_alerta_resuelta(db:
|
| 253 |
cama = cama_crud.get_by_paciente(db, paciente_id, ["CODIGO_ROJO"])
|
| 254 |
if not cama:
|
| 255 |
raise HTTPException(
|
|
@@ -263,7 +265,7 @@ def procesar_alerta_resuelta(db: Session, paciente_id: int) -> Cama:
|
|
| 263 |
|
| 264 |
# ─── Cancelar reserva por turno (desde M2) ─────────────────────────────────
|
| 265 |
|
| 266 |
-
def cancelar_reserva_por_turno(db:
|
| 267 |
reserva = reserva_crud.get_by_turno(db, turno_id)
|
| 268 |
if not reserva:
|
| 269 |
raise HTTPException(
|
|
|
|
| 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
|
|
|
|
| 32 |
)
|
| 33 |
|
| 34 |
|
| 35 |
+
def _get_solicitud_or_404(db: Client, solicitud_id: str) -> Solicitud:
|
| 36 |
num_id = _parse_solicitud_id(solicitud_id)
|
| 37 |
sol = solicitud_crud.get_by_id(db, num_id)
|
| 38 |
if not sol:
|
|
|
|
| 40 |
return sol
|
| 41 |
|
| 42 |
|
| 43 |
+
def _get_cama_or_404(db: Client, cama_id: int) -> Cama:
|
| 44 |
c = cama_crud.get_by_id(db, cama_id)
|
| 45 |
if not c:
|
| 46 |
raise HTTPException(
|
|
|
|
| 66 |
|
| 67 |
# ─── Recibir solicitud desde HCE (M1) ─────────────────────────────────────
|
| 68 |
|
| 69 |
+
def recibir_solicitud(db: Client, data: SolicitudHceWebhook) -> Solicitud:
|
| 70 |
existing = solicitud_crud.get_by_hce_id(db, data.solicitud_hce_id)
|
| 71 |
if existing:
|
| 72 |
return existing
|
|
|
|
| 76 |
# ─── Listar / obtener solicitudes ──────────────────────────────────────────
|
| 77 |
|
| 78 |
def get_solicitudes(
|
| 79 |
+
db: Client,
|
| 80 |
estado: str | None = None,
|
| 81 |
tipo: str | None = None,
|
| 82 |
hospital_id: str | None = None,
|
|
|
|
| 84 |
return solicitud_crud.get_all(db, estado, tipo, hospital_id)
|
| 85 |
|
| 86 |
|
| 87 |
+
def get_solicitud(db: Client, solicitud_id: str) -> Solicitud:
|
| 88 |
return _get_solicitud_or_404(db, solicitud_id)
|
| 89 |
|
| 90 |
|
| 91 |
# ─── Resolver solicitud ────────────────────────────────────────────────────
|
| 92 |
|
| 93 |
def resolver_solicitud(
|
| 94 |
+
db: Client,
|
| 95 |
solicitud_id: str,
|
| 96 |
data: SolicitudResolucionRequest,
|
| 97 |
resuelto_por: int,
|
|
|
|
| 139 |
|
| 140 |
|
| 141 |
def _aprobar_internacion(
|
| 142 |
+
db: Client, sol: Solicitud, cama_id: int, motivo: str | None, resuelto_por: int, accion: str
|
| 143 |
) -> None:
|
| 144 |
paciente = core.validate_patient(sol.paciente_id)
|
| 145 |
if not paciente:
|
|
|
|
| 160 |
cama.estado = EstadoCamaEnum.OCUPADA.value
|
| 161 |
cama.paciente_id = sol.paciente_id
|
| 162 |
cama.ultima_actualizacion = datetime.now(timezone.utc)
|
| 163 |
+
cama_crud.save(db, cama)
|
| 164 |
|
| 165 |
sol.estado = "APROBADA"
|
| 166 |
sol.accion = accion
|
|
|
|
| 175 |
|
| 176 |
|
| 177 |
def _aprobar_traslado(
|
| 178 |
+
db: Client, sol: Solicitud, cama_destino_id: int | None, motivo: str | None, resuelto_por: int, accion: str
|
| 179 |
) -> None:
|
| 180 |
dest_id = cama_destino_id or sol.cama_destino_solicitada_id
|
| 181 |
if not dest_id:
|
|
|
|
| 198 |
cama_origen.estado = EstadoCamaEnum.EN_LIMPIEZA.value
|
| 199 |
cama_origen.ultimo_movimiento_tipo = "TRASLADO"
|
| 200 |
cama_origen.ultima_actualizacion = datetime.now(timezone.utc)
|
| 201 |
+
cama_crud.save(db, cama_origen)
|
| 202 |
|
| 203 |
cama_destino.estado = EstadoCamaEnum.OCUPADA.value
|
| 204 |
cama_destino.paciente_id = sol.paciente_id
|
| 205 |
cama_destino.ultima_actualizacion = datetime.now(timezone.utc)
|
| 206 |
+
cama_crud.save(db, cama_destino)
|
| 207 |
|
| 208 |
sol.estado = "APROBADA"
|
| 209 |
sol.accion = accion
|
|
|
|
| 220 |
|
| 221 |
# ─── Alta médica (desde HCE M1) ────────────────────────────────────────────
|
| 222 |
|
| 223 |
+
def procesar_alta_medica(db: Client, paciente_id: int) -> Cama:
|
| 224 |
cama = cama_crud.get_by_paciente(db, paciente_id, ["OCUPADA", "CODIGO_ROJO"])
|
| 225 |
if not cama:
|
| 226 |
raise HTTPException(
|
|
|
|
| 237 |
|
| 238 |
# ─── Alertas de emergencia (desde M9) ──────────────────────────────────────
|
| 239 |
|
| 240 |
+
def procesar_alerta_emergencia(db: Client, paciente_id: int) -> Cama:
|
| 241 |
cama = cama_crud.get_by_paciente(db, paciente_id, ["OCUPADA"])
|
| 242 |
if not cama:
|
| 243 |
raise HTTPException(
|
|
|
|
| 247 |
cama.estado = EstadoCamaEnum.CODIGO_ROJO.value
|
| 248 |
cama.ultima_actualizacion = datetime.now(timezone.utc)
|
| 249 |
cama_crud.save(db, cama)
|
|
|
|
| 250 |
hce.notify_evento_episodio(0, "CODIGO_ROJO", f"Alerta de emergencia detectada para paciente {paciente_id}")
|
| 251 |
return cama
|
| 252 |
|
| 253 |
|
| 254 |
+
def procesar_alerta_resuelta(db: Client, paciente_id: int) -> Cama:
|
| 255 |
cama = cama_crud.get_by_paciente(db, paciente_id, ["CODIGO_ROJO"])
|
| 256 |
if not cama:
|
| 257 |
raise HTTPException(
|
|
|
|
| 265 |
|
| 266 |
# ─── Cancelar reserva por turno (desde M2) ─────────────────────────────────
|
| 267 |
|
| 268 |
+
def cancelar_reserva_por_turno(db: Client, turno_id: str, motivo: str) -> ReservaQuirofano:
|
| 269 |
reserva = reserva_crud.get_by_turno(db, turno_id)
|
| 270 |
if not reserva:
|
| 271 |
raise HTTPException(
|
openapi.yaml
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
requirements.txt
CHANGED
|
@@ -1,20 +1,9 @@
|
|
| 1 |
# Dependencias de producción — Módulo 6: Internación y Gestión de Camas
|
| 2 |
-
# Actualizar con: pip-compile requirements.in (pendiente adoptar pip-tools o Poetry)
|
| 3 |
|
| 4 |
fastapi==0.115.0
|
| 5 |
uvicorn[standard]==0.31.0
|
| 6 |
-
|
| 7 |
-
psycopg2-binary==2.9.10
|
| 8 |
pydantic==2.9.2
|
| 9 |
pydantic-settings==2.5.2
|
| 10 |
python-jose[cryptography]==3.3.0
|
| 11 |
httpx==0.27.2
|
| 12 |
-
# python-multipart — comentado: no hay endpoints con Form/File actualmente
|
| 13 |
-
# python-multipart==0.0.12
|
| 14 |
-
|
| 15 |
-
# ─── Dependencias de desarrollo (mover a requirements-dev.txt) ─────────────
|
| 16 |
-
# pytest
|
| 17 |
-
# pytest-asyncio
|
| 18 |
-
# httpx (ya declarado arriba, útil como AsyncClient en tests)
|
| 19 |
-
# ruff
|
| 20 |
-
# mypy
|
|
|
|
| 1 |
# Dependencias de producción — Módulo 6: Internación y Gestión de Camas
|
|
|
|
| 2 |
|
| 3 |
fastapi==0.115.0
|
| 4 |
uvicorn[standard]==0.31.0
|
| 5 |
+
supabase>=2.0.0,<3.0.0
|
|
|
|
| 6 |
pydantic==2.9.2
|
| 7 |
pydantic-settings==2.5.2
|
| 8 |
python-jose[cryptography]==3.3.0
|
| 9 |
httpx==0.27.2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tests/conftest.py
CHANGED
|
@@ -2,51 +2,25 @@
|
|
| 2 |
Fixtures compartidas para los tests de Módulo 6.
|
| 3 |
"""
|
| 4 |
import pytest
|
|
|
|
| 5 |
from fastapi.testclient import TestClient
|
| 6 |
-
from sqlalchemy import create_engine
|
| 7 |
-
from sqlalchemy.orm import sessionmaker
|
| 8 |
|
| 9 |
from app.main import app
|
| 10 |
-
from app.dependencies import
|
| 11 |
-
|
| 12 |
-
# BD en memoria para tests
|
| 13 |
-
SQLALCHEMY_TEST_URL = "sqlite:///:memory:"
|
| 14 |
-
|
| 15 |
-
engine_test = create_engine(SQLALCHEMY_TEST_URL, connect_args={"check_same_thread": False})
|
| 16 |
-
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine_test)
|
| 17 |
|
| 18 |
|
| 19 |
def override_get_db():
|
| 20 |
-
|
| 21 |
-
try:
|
| 22 |
-
yield db
|
| 23 |
-
except Exception:
|
| 24 |
-
db.rollback()
|
| 25 |
-
raise
|
| 26 |
-
finally:
|
| 27 |
-
db.close()
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
@pytest.fixture(scope="session", autouse=True)
|
| 31 |
-
def setup_db():
|
| 32 |
-
Base.metadata.create_all(bind=engine_test)
|
| 33 |
-
yield
|
| 34 |
-
Base.metadata.drop_all(bind=engine_test)
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
@pytest.fixture
|
| 38 |
-
def db():
|
| 39 |
-
session = TestingSessionLocal()
|
| 40 |
-
try:
|
| 41 |
-
yield session
|
| 42 |
-
finally:
|
| 43 |
-
session.rollback()
|
| 44 |
-
session.close()
|
| 45 |
|
| 46 |
|
| 47 |
@pytest.fixture
|
| 48 |
-
def client(
|
| 49 |
app.dependency_overrides[get_db] = override_get_db
|
| 50 |
with TestClient(app) as c:
|
| 51 |
yield c
|
| 52 |
app.dependency_overrides.clear()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
Fixtures compartidas para los tests de Módulo 6.
|
| 3 |
"""
|
| 4 |
import pytest
|
| 5 |
+
from unittest.mock import MagicMock
|
| 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 TestClient(app) as c:
|
| 20 |
yield c
|
| 21 |
app.dependency_overrides.clear()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.fixture
|
| 25 |
+
def db():
|
| 26 |
+
return MagicMock()
|