File size: 7,186 Bytes
5f12c93
 
 
 
 
9223feb
5f12c93
 
 
9223feb
5f12c93
 
9223feb
 
 
5f12c93
9223feb
 
 
 
 
 
 
 
 
 
5f12c93
 
f485d1b
9223feb
 
 
 
 
 
 
 
5f12c93
 
9223feb
 
 
 
 
 
 
 
5f12c93
 
 
9223feb
5f12c93
 
 
 
 
 
9223feb
5f12c93
9223feb
5f12c93
9223feb
5f12c93
9223feb
5f12c93
9223feb
5f12c93
9223feb
 
 
5f12c93
 
 
9223feb
5f12c93
 
 
 
 
9223feb
 
 
 
 
 
 
5f12c93
 
9223feb
 
 
 
 
0ea0860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cd3cff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f485d1b
9223feb
 
 
 
 
 
 
5f12c93
9223feb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ea0860
 
 
 
 
 
 
9223feb
 
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""
Operaciones de acceso a datos para ReservaQuirofano. Sin lógica de negocio ni HTTPException.
"""
from __future__ import annotations
from datetime import datetime, timezone
from supabase import Client
from app.models.reserva import ReservaQuirofano
from app.schemas.reserva import ReservaQuirofanoCreateRequest, CirugiaUrgenteWebhook

_TABLE = "reservas_quirofano"


def get_by_id(db: Client, reserva_id: int) -> ReservaQuirofano | None:
    resp = db.table(_TABLE).select("*").eq("id", reserva_id).execute()
    return ReservaQuirofano.from_dict(resp.data[0]) if resp.data else None


def get_by_cama_and_id(db: Client, cama_id: int, reserva_id: int) -> ReservaQuirofano | None:
    resp = (
        db.table(_TABLE)
        .select("*")
        .eq("id", reserva_id)
        .eq("cama_id", cama_id)
        .execute()
    )
    return ReservaQuirofano.from_dict(resp.data[0]) if resp.data else None


def get_by_turno(db: Client, turno_id: int) -> ReservaQuirofano | None:
    resp = (
        db.table(_TABLE)
        .select("*")
        .eq("turno_id", turno_id)
        .eq("origen", "PROGRAMADA")
        .execute()
    )
    return ReservaQuirofano.from_dict(resp.data[0]) if resp.data else None


def get_by_urgencia_hce_id(db: Client, hce_id: str) -> ReservaQuirofano | None:
    resp = (
        db.table(_TABLE)
        .select("*")
        .eq("solicitud_urgencia_hce_id", hce_id)
        .execute()
    )
    return ReservaQuirofano.from_dict(resp.data[0]) if resp.data else None


def get_all(
    db: Client,
    cama_id: int,
    estado: str | None = None,
    prioridad: str | None = None,
    fecha_desde: str | None = None,
    fecha_hasta: str | None = None,
) -> list[ReservaQuirofano]:
    q = db.table(_TABLE).select("*").eq("cama_id", cama_id)
    if estado:
        q = q.eq("estado", estado)
    else:
        q = q.in_("estado", ["RESERVADA", "EN_CURSO"])
    if prioridad:
        q = q.eq("prioridad", prioridad)
    if fecha_desde:
        q = q.gte("fecha_hora_inicio", fecha_desde)
    if fecha_hasta:
        q = q.lte("fecha_hora_fin_estimada", fecha_hasta)
    resp = q.execute()
    return [ReservaQuirofano.from_dict(row) for row in resp.data]


def get_superpuestas(
    db: Client,
    cama_id: int,
    inicio: datetime,
    fin: datetime,
    exclude_id: int | None = None,
) -> list[ReservaQuirofano]:
    q = (
        db.table(_TABLE)
        .select("*")
        .eq("cama_id", cama_id)
        .in_("estado", ["RESERVADA", "EN_CURSO"])
        .lt("fecha_hora_inicio", fin.isoformat())
        .gt("fecha_hora_fin_estimada", inicio.isoformat())
    )
    if exclude_id:
        q = q.neq("id", exclude_id)
    resp = q.execute()
    return [ReservaQuirofano.from_dict(row) for row in resp.data]


def get_futuras(db: Client, cama_id: int, desde: datetime) -> list[ReservaQuirofano]:
    """Reservas activas (RESERVADA/EN_CURSO) del quirófano que todavía no terminaron
    en `desde`, ordenadas por inicio. Base para calcular el inicio más temprano factible
    de una cirugía urgente (algoritmo ASAP, ver cama_service.crear_reserva_urgente)."""
    resp = (
        db.table(_TABLE)
        .select("*")
        .eq("cama_id", cama_id)
        .in_("estado", ["RESERVADA", "EN_CURSO"])
        .gt("fecha_hora_fin_estimada", desde.isoformat())
        .order("fecha_hora_inicio")
        .execute()
    )
    return [ReservaQuirofano.from_dict(row) for row in resp.data]


def get_pendientes_de_inicio(db: Client, ahora: datetime) -> list[ReservaQuirofano]:
    """Reservas `RESERVADA` cuyo horario de inicio ya llegó — candidatas a pasar a
    `EN_CURSO` automáticamente. Una reserva `CANCELADA` nunca aparece acá: el filtro por
    estado ya resuelve "si no se canceló, arranca sola" sin lógica adicional."""
    resp = (
        db.table(_TABLE)
        .select("*")
        .eq("estado", "RESERVADA")
        .lte("fecha_hora_inicio", ahora.isoformat())
        .execute()
    )
    return [ReservaQuirofano.from_dict(row) for row in resp.data]


def get_pendientes_de_fin(db: Client, ahora: datetime) -> list[ReservaQuirofano]:
    """Reservas `EN_CURSO` cuyo horario de fin estimado ya llegó — candidatas a pasar a
    `COMPLETADA` automáticamente."""
    resp = (
        db.table(_TABLE)
        .select("*")
        .eq("estado", "EN_CURSO")
        .lte("fecha_hora_fin_estimada", ahora.isoformat())
        .execute()
    )
    return [ReservaQuirofano.from_dict(row) for row in resp.data]


def get_activa_por_turno(db: Client, turno_id: int) -> ReservaQuirofano | None:
    resp = (
        db.table(_TABLE)
        .select("*")
        .eq("turno_id", turno_id)
        .in_("estado", ["RESERVADA", "EN_CURSO"])
        .limit(1)
        .execute()
    )
    return ReservaQuirofano.from_dict(resp.data[0]) if resp.data else None


def create_programada(db: Client, cama_id: int, data: ReservaQuirofanoCreateRequest) -> ReservaQuirofano:
    row = {
        "cama_id": cama_id,
        "turno_id": data.turno_id,
        "origen": "PROGRAMADA",
        "estado": "RESERVADA",
        "prioridad": data.prioridad.value,
        "paciente_id": data.paciente_id,
        "medico_cirujano_id": data.medico_cirujano_id,
        "fecha_hora_inicio": data.fecha_hora_inicio.isoformat(),
        "fecha_hora_fin_estimada": data.fecha_hora_fin_estimada.isoformat(),
        "observaciones": data.observaciones,
        "created_at": datetime.now(timezone.utc).isoformat(),
    }
    resp = db.table(_TABLE).insert(row).execute()
    return ReservaQuirofano.from_dict(resp.data[0])


def create_urgente(db: Client, cama_id: int, data: CirugiaUrgenteWebhook) -> ReservaQuirofano:
    row = {
        "cama_id": cama_id,
        "solicitud_urgencia_hce_id": data.solicitud_urgencia_hce_id,
        "origen": "EMERGENCIA",
        "estado": "RESERVADA",
        "prioridad": "URGENTE",
        "paciente_id": data.paciente_id,
        "medico_cirujano_id": data.medico_cirujano_id,
        "fecha_hora_inicio": data.fecha_hora_inicio.isoformat(),
        "fecha_hora_fin_estimada": data.fecha_hora_fin_estimada.isoformat(),
        "observaciones": f"Cirugía urgente solicitada por HCE ({data.solicitud_urgencia_hce_id})",
        "created_at": datetime.now(timezone.utc).isoformat(),
    }
    resp = db.table(_TABLE).insert(row).execute()
    return ReservaQuirofano.from_dict(resp.data[0])


def save(db: Client, reserva: ReservaQuirofano) -> ReservaQuirofano:
    updates = {
        "estado": reserva.estado,
        "observaciones": reserva.observaciones,
        "desplazada_por_reserva_id": reserva.desplazada_por_reserva_id,
        # fecha_hora_inicio/fin también se persisten: una reserva reprogramada por
        # una urgencia (cama_service.reprogramar) cambia su ventana horaria y eso
        # tiene que quedar en la DB de M6, no solo notificarse a M2.
        "fecha_hora_inicio": reserva.fecha_hora_inicio.isoformat() if reserva.fecha_hora_inicio else None,
        "fecha_hora_fin_estimada": (
            reserva.fecha_hora_fin_estimada.isoformat() if reserva.fecha_hora_fin_estimada else None
        ),
    }
    db.table(_TABLE).update(updates).eq("id", reserva.id).execute()
    return reserva