File size: 13,735 Bytes
9f05894
 
 
 
 
 
 
8defa71
 
9f05894
 
8defa71
9f05894
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a440d33
 
 
9f05894
a440d33
9f05894
 
 
 
 
 
 
 
 
 
 
 
 
 
a440d33
9f05894
 
a440d33
9f05894
a440d33
9f05894
 
5ffed1d
 
9f05894
 
 
 
 
 
 
 
 
 
 
 
 
efe5cdf
9f05894
 
 
efe5cdf
5ffed1d
9f05894
 
5ffed1d
 
9f05894
 
 
 
 
 
 
 
 
 
 
 
 
efe5cdf
9f05894
 
 
efe5cdf
5ffed1d
9f05894
 
efe5cdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a440d33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8defa71
 
9f05894
a440d33
9f05894
 
 
 
 
 
8defa71
 
 
0e75654
8defa71
 
 
 
 
 
 
 
0e75654
bff144c
0e75654
8defa71
4a2396c
8defa71
 
 
 
 
 
a440d33
8defa71
 
 
9f05894
 
8defa71
 
 
 
9f05894
 
8defa71
 
 
 
 
 
 
 
 
0e75654
9f05894
 
8defa71
 
 
 
4a2396c
 
8defa71
 
bff144c
4a2396c
 
8defa71
4a2396c
bff144c
 
 
2f4ab65
 
 
bff144c
a440d33
bff144c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9df53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
"""
Tests de la publicación saliente al bus del Core (`app/integrations/core_events.py`) y
de que los 4 puntos de notificación (`hce.notify_resultado_solicitud`,
`monitoreo.notify_alta`/`notify_baja`, `facturacion.notify_cama_lista`) sigan haciendo el
mismo request REST que hoy, sin cambios observables, mientras el `event_type_id`
correspondiente esté en `None` (default actual — ver `M6_DISEÑO.md` §7).
"""
from datetime import datetime, timezone

from app.config import settings
from app.integrations import core_events, facturacion, hce, monitoreo
from tests.factories import make_cama


# ─── publish_event: no-op mientras no haya event_type_id ──────────────────


def test_publish_event_sin_id_no_hace_ningun_request(monkeypatch):
    called = []
    monkeypatch.setattr("app.integrations.core_events._post", lambda *a, **k: called.append((a, k)))

    result = core_events.publish_event(None, {"foo": "bar"})

    assert result is True
    assert called == []


def test_publish_event_con_id_publica_al_core(monkeypatch):
    calls = []

    def _fake_post(url, body):
        calls.append((url, body))
        return {"id": 999}

    monkeypatch.setattr(core_events, "_post", _fake_post)

    result = core_events.publish_event(14, {"foo": "bar"})

    assert result is True
    assert len(calls) == 1
    url, body = calls[0]
    assert url == f"{settings.m10_core_url}/events/log"
    assert body["event_type_id"] == 14
    assert body["publisher_module"] == "internacion"
    assert body["payload"] == '{"foo": "bar"}'


def test_publish_event_con_id_pero_post_falla_devuelve_false(monkeypatch):
    monkeypatch.setattr(core_events, "_post", lambda *a, **k: None)

    assert core_events.publish_event(14, {"foo": "bar"}) is False


# ─── notify_* : REST sin cambios + publish_event adicional (hoy no-op) ─────


def test_notify_resultado_solicitud_solo_publica_evento_sin_rest(monkeypatch):
    """Corrección 2026-07: el REST a M1 (`/hce/solicitudes/{id}/resultado`) se deprecó — ese
    path no existe en el contrato real de M1. Canal único: el evento del bus."""
    monkeypatch.setattr(settings, "mock_external_services", False)
    monkeypatch.setattr(settings, "hce_solicitud_resuelta_event_type_id", 25)
    rest_calls = []
    publish_calls = []
    monkeypatch.setattr(
        "app.integrations.hce._post",
        lambda url, payload: rest_calls.append((url, payload)) or {"ok": True},
    )
    monkeypatch.setattr(
        "app.integrations.core_events.publish_event",
        lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True,
    )

    ok = hce.notify_resultado_solicitud("HCE-SOL-1", "APROBADA", motivo=None)

    assert ok is True
    assert len(rest_calls) == 0  # el REST ya no se llama
    assert len(publish_calls) == 1
    event_type_id, event_payload = publish_calls[0]
    assert event_type_id == 25
    assert event_payload["solicitud_hce_id"] == "HCE-SOL-1"
    assert event_payload["resultado"] == "APROBADA"


def test_notify_alta_sin_event_type_id_usa_rest_como_backup(monkeypatch):
    """Cuando monitoreo_alta_event_type_id es None, va directo al HTTP sin llamar publish_event."""
    monkeypatch.setattr(settings, "mock_external_services", False)
    monkeypatch.setattr(settings, "monitoreo_alta_event_type_id", None)
    rest_calls = []
    publish_calls = []
    monkeypatch.setattr(
        "app.integrations.monitoreo._post",
        lambda url, payload: rest_calls.append((url, payload)) or {"ok": True},
    )
    monkeypatch.setattr(
        "app.integrations.core_events.publish_event",
        lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True,
    )

    ok = monitoreo.notify_alta(7, cama_id=9)

    assert ok is True
    assert len(rest_calls) == 1
    assert rest_calls[0][1]["cama_id"] == 9
    assert len(publish_calls) == 0  # no se llama publish_event cuando event_type_id es None


def test_notify_baja_sin_event_type_id_usa_rest_como_backup(monkeypatch):
    """Cuando monitoreo_baja_event_type_id es None, va directo al HTTP sin llamar publish_event."""
    monkeypatch.setattr(settings, "mock_external_services", False)
    monkeypatch.setattr(settings, "monitoreo_baja_event_type_id", None)
    rest_calls = []
    publish_calls = []
    monkeypatch.setattr(
        "app.integrations.monitoreo._post",
        lambda url, payload: rest_calls.append((url, payload)) or {"ok": True},
    )
    monkeypatch.setattr(
        "app.integrations.core_events.publish_event",
        lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True,
    )

    ok = monitoreo.notify_baja(7, cama_id=9)

    assert ok is True
    assert len(rest_calls) == 1
    assert rest_calls[0][1]["cama_id"] == 9
    assert len(publish_calls) == 0  # no se llama publish_event cuando event_type_id es None


def test_notify_alta_con_event_type_id_publica_al_bus_con_cama_id(monkeypatch):
    """Con monitoreo_alta_event_type_id=26 configurado (id real de M9), publica al bus con
    cama_id incluido en el payload."""
    monkeypatch.setattr(settings, "mock_external_services", False)
    monkeypatch.setattr(settings, "monitoreo_alta_event_type_id", 26)
    publish_calls = []
    monkeypatch.setattr(
        "app.integrations.core_events.publish_event",
        lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True,
    )

    ok = monitoreo.notify_alta(7, cama_id=9)

    assert ok is True
    assert len(publish_calls) == 1
    event_type_id, payload = publish_calls[0]
    assert event_type_id == 26
    assert payload["cama_id"] == 9


def test_notify_baja_con_event_type_id_publica_al_bus_con_cama_id(monkeypatch):
    """Con monitoreo_baja_event_type_id=27 configurado (id real de M9), publica al bus con
    cama_id incluido en el payload."""
    monkeypatch.setattr(settings, "mock_external_services", False)
    monkeypatch.setattr(settings, "monitoreo_baja_event_type_id", 27)
    publish_calls = []
    monkeypatch.setattr(
        "app.integrations.core_events.publish_event",
        lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True,
    )

    ok = monitoreo.notify_baja(7, cama_id=9)

    assert ok is True
    assert len(publish_calls) == 1
    event_type_id, payload = publish_calls[0]
    assert event_type_id == 27
    assert payload["cama_id"] == 9


def test_notify_cama_lista_desactivado_no_envia_nada(monkeypatch):
    """Pausa manual (2026-07, `facturacion_cierre_habilitado=False` por default): no se manda
    nada a M7, ni evento ni REST, y la función devuelve True (fire-and-forget)."""
    monkeypatch.setattr(settings, "mock_external_services", False)
    monkeypatch.setattr(settings, "facturacion_cierre_habilitado", False)
    rest_calls = []
    publish_calls = []
    monkeypatch.setattr(
        "app.integrations.facturacion._post",
        lambda *a, **k: rest_calls.append((a, k)) or {"ok": True},
    )
    monkeypatch.setattr(
        "app.integrations.core_events.publish_event",
        lambda *a, **k: publish_calls.append((a, k)) or True,
    )

    cama = make_cama(id=315, paciente_id=7)
    ok = facturacion.notify_cama_lista(cama, db=None)

    assert ok is True
    assert rest_calls == []
    assert publish_calls == []


def test_notify_cama_lista_sigue_llamando_rest_con_payload_minimo(monkeypatch):
    """El REST directo es fallback/testing manual según M7 — payload mínimo, sin cambios."""
    monkeypatch.setattr(settings, "mock_external_services", False)
    monkeypatch.setattr(settings, "facturacion_cierre_habilitado", True)
    monkeypatch.setattr(settings, "facturacion_cama_lista_event_type_id", None)
    rest_calls = []
    monkeypatch.setattr(
        "app.integrations.facturacion._post",
        lambda url, payload: rest_calls.append((url, payload)) or {"ok": True},
    )
    monkeypatch.setattr("app.integrations.core_events.publish_event", lambda *a, **k: True)

    cama = make_cama(id=315, paciente_id=7)
    ok = facturacion.notify_cama_lista(cama, db=None)

    assert ok is True
    assert len(rest_calls) == 1
    url, payload = rest_calls[0]
    assert url == f"{settings.m7_facturacion_url}/api/v1/webhooks/internacion/cama-lista"
    assert payload == {
        "evento": "CAMA_LISTA",
        "idEventoExterno": payload["idEventoExterno"],
        "camaId": "315",
        "idPacienteExterno": 7,
        "timestampEvento": payload["timestampEvento"],
    }
    assert payload["timestampEvento"].endswith("Z")


def test_notify_cama_lista_publica_evento_rico_con_datos_del_episodio(monkeypatch):
    """El evento del Core (event_type_id=19, confirmado por M7) lleva el payload rico
    CIERRE_INTERNACION con los datos del episodio persistidos en la Cama."""
    monkeypatch.setattr(settings, "mock_external_services", False)
    monkeypatch.setattr(settings, "facturacion_cierre_habilitado", True)
    monkeypatch.setattr(settings, "facturacion_cama_lista_event_type_id", 19)
    monkeypatch.setattr("app.integrations.facturacion._post", lambda *a, **k: {"ok": True})
    publish_calls = []
    monkeypatch.setattr(
        "app.integrations.core_events.publish_event",
        lambda event_type_id, payload, publisher_module="internacion": publish_calls.append(
            (event_type_id, payload, publisher_module)
        )
        or True,
    )

    cama = make_cama(
        id=315,
        paciente_id=7,
        solicitud_hce_id="HCE-SOL-00123",
        fecha_ingreso=datetime(2026, 6, 20, 14, 30, tzinfo=timezone.utc),
        alta_tipo="ALTA_MEDICA",
        alta_timestamp=datetime(2026, 6, 25, 10, 0, tzinfo=timezone.utc),
    )

    facturacion.notify_cama_lista(cama, db=None)

    assert len(publish_calls) == 1
    event_type_id, payload, publisher_module = publish_calls[0]
    assert event_type_id == 19
    assert publisher_module == "modulo_6"
    assert payload["evento"] == "CIERRE_INTERNACION"
    assert "camaId" not in payload  # no es parte del contrato de M7 — ver M6_DISEÑO.md §7.2
    assert "camasUtilizadas" not in payload
    assert payload["idInternacionExterna"] == "HCE-SOL-00123"
    assert payload["idEpisodioExterno"] is None  # bloqueante externo — M1 no lo provee aún
    assert payload["idPacienteExterno"] == 7  # int — InternacionM6Request.idPacienteExterno es Long
    assert payload["fechaIngreso"] == "2026-06-20T14:30:00Z"
    assert payload["fechaAlta"] == "2026-06-25T10:00:00Z"
    assert payload["tipoAlta"] == "ALTA_MEDICA"
    assert "timestampEvento" in payload and payload["timestampEvento"].endswith("Z")


def test_notify_cama_lista_manda_episodio_id_como_entero_cuando_esta_poblado(monkeypatch):
    """episodio_id llega a la cama desde la solicitud/traslado (M1 lo crea al crear la
    solicitud — ver M6_INTEGRACION_M1_HCE.md §4.3), no desde el webhook de alta médica.
    Tiene que salir como entero en el evento, igual que idPacienteExterno."""
    monkeypatch.setattr(settings, "mock_external_services", False)
    monkeypatch.setattr(settings, "facturacion_cierre_habilitado", True)
    monkeypatch.setattr(settings, "facturacion_cama_lista_event_type_id", 19)
    monkeypatch.setattr("app.integrations.facturacion._post", lambda *a, **k: {"ok": True})
    publish_calls = []
    monkeypatch.setattr(
        "app.integrations.core_events.publish_event",
        lambda event_type_id, payload, publisher_module="internacion": publish_calls.append(
            (event_type_id, payload, publisher_module)
        )
        or True,
    )

    cama = make_cama(id=315, paciente_id=7, episodio_id=700)

    facturacion.notify_cama_lista(cama, db=None)

    _, payload, _ = publish_calls[0]
    assert payload["idEpisodioExterno"] == 700
    assert isinstance(payload["idEpisodioExterno"], int)


# ─── notify_movimiento: endpoint real de M1 (corrección 2026-07) ───────────


def test_notify_movimiento_arma_payload_real_de_internacion_ingreso(monkeypatch):
    """El path viejo (/hce/movimientos) no existe en el contrato real de M1 — el real es
    /internacion/ingreso (IngresoInternacionRequest), reusado tanto para ingreso como para
    traslado reenviando el mismo id_episodio."""
    monkeypatch.setattr(settings, "mock_external_services", False)
    rest_calls = []
    monkeypatch.setattr(
        "app.integrations.hce._post",
        lambda url, payload: rest_calls.append((url, payload)) or {"ok": True},
    )

    cama = make_cama(id=12, numero=4, sector="UTI", tipo="CRITICA", episodio_id=700)
    actor = {"usuario_id": 20, "rol": "MEDICO"}

    ok = hce.notify_movimiento(cama, paciente_id=10500, actor=actor)

    assert ok is True
    assert len(rest_calls) == 1
    url, payload = rest_calls[0]
    assert url == f"{settings.m1_hce_url}/api/v1/internacion/ingreso"
    assert payload["id_paciente"] == 10500
    assert payload["id_episodio"] == 700
    assert payload["sector"] == "UTI"
    assert payload["habitacion"] == "CRITICA"
    assert payload["cama"] == "Cama 4"
    assert payload["medico_solicitante"] == "20"
    assert "fecha_ingreso" in payload


def test_notify_movimiento_sin_actor_manda_medico_solicitante_null(monkeypatch):
    monkeypatch.setattr(settings, "mock_external_services", False)
    rest_calls = []
    monkeypatch.setattr(
        "app.integrations.hce._post",
        lambda url, payload: rest_calls.append((url, payload)) or {"ok": True},
    )

    cama = make_cama(id=12, numero=4, sector="UTI", tipo="CRITICA", episodio_id=700)

    ok = hce.notify_movimiento(cama, paciente_id=10500, actor=None)

    assert ok is True
    _, payload = rest_calls[0]
    assert payload["medico_solicitante"] is None