Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1d5f1e0cc4 | |||
| ca54656124 | |||
| 102999c8de | |||
| 7798d007d1 | |||
| c72c03988e | |||
| 91537e9efd | |||
| f11abd8f6e | |||
| 6afe329e52 | |||
| 96a29cfb19 | |||
| b9adedbf6f |
@@ -96,3 +96,29 @@ uv run pytest -q
|
|||||||
|
|
||||||
Las pruebas contra MySQL en vivo se activan con `MYSQL_TEST_URL`; sin ella
|
Las pruebas contra MySQL en vivo se activan con `MYSQL_TEST_URL`; sin ella
|
||||||
se omiten.
|
se omiten.
|
||||||
|
|
||||||
|
### Seguimiento CaMa sintético
|
||||||
|
|
||||||
|
`GET /cama/seguimiento` entrega la tabla declarativa de demostración, sin consultar una base. Por defecto usa corte fijo `2026-10-20`, ventana de 3 meses, página 1 y tamaño 50. `corte` acepta fecha ISO; `meses` admite 1, 3, 6 o 12; `page` comienza en 1 y `page_size` va de 1 a 200. La ventana incluye desde el día siguiente a restar meses calendario (ajustando fin de mes) hasta el corte inclusive. Se seleccionan filas por fecha de mastografía. No se acota un corte solicitado a la última fecha del fixture.
|
||||||
|
|
||||||
|
Los filtros opcionales son `estatus` (`PENDIENTE_BIOPSIA`, `BIOPSIA_SIN_RESULTADO`, `CANCER_CONFIRMADO`, `BENIGNO`, `INFO_INSUFICIENTE`), `birads` (`BIRADS_4A`, `BIRADS_4B`, `BIRADS_4C`, `BIRADS_5`, `BIRADS_6`), `grupo_edad` (`40-49`, `50-59`, `60-69`, `70+`) y `prioridad` (`ALTA`, `MEDIA`, `BAJA`). `filtros_disponibles` anuncia códigos y etiquetas; las celdas incluyen etiquetas y campos `*_codigo`. Se ordena por fecha descendente e ID ascendente, antes de paginar. Una página fuera de rango devuelve 200 con `items: []`; una lista vacía tiene cero páginas. Parámetros inválidos producen 400 y un fallo de lectura 500 con JSON `error`.
|
||||||
|
|
||||||
|
#### Contratos candidatos F5B
|
||||||
|
|
||||||
|
`GET /cama/seguimiento/exportacion?corte=2026-10-20&meses=1&birads=BIRADS_5` devuelve todas las coincidencias, con los mismos filtros y orden de la lista. El cuerpo incluye `simulado`, `corte`, `ventana`, `campo_ventana`, `filtros`, `filtros_disponibles`, `columnas`, `total_items` e `items`. Ejemplo abreviado (los arreglos de metadatos se omiten aquí, pero siempre se envían):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"simulado":true,"corte":"2026-10-20","ventana":{"meses":1,"desde":"2026-09-21","hasta":"2026-10-20"},"campo_ventana":"mastografia_fecha","filtros":{"estatus":null,"birads":"BIRADS_5","grupo_edad":null,"prioridad":null},"total_items":1,"items":[{"id_seudonimo":"M-0001","mastografia_fecha":"2026-10-15","estatus":"Pendiente de biopsia","estatus_codigo":"PENDIENTE_BIOPSIA","birads":"BI-RADS 5","birads_codigo":"BIRADS_5","grupo_edad":"50-59","grupo_edad_codigo":"50-59","prioridad":"Alta","prioridad_codigo":"ALTA","biopsia":null,"biopsia_fecha":null,"dias_mastografia_diagnostico":null}]}
|
||||||
|
```
|
||||||
|
|
||||||
|
Más de 5,000 coincidencias produce 413 con `error`, sin truncar. No requiere parámetros de paginación; si se envían, se validan como en la lista pero no limitan el resultado. JSON vacío es 200 con `total_items: 0` e `items: []`. Las respuestas, incluidos errores, llevan `Cache-Control: no-store`.
|
||||||
|
|
||||||
|
`GET /cama/pacientes/M-0001?corte=2026-10-20&meses=1` devuelve `{"simulado":true,"corte":"2026-10-20","ventana":{"meses":1,"desde":"2026-09-21","hasta":"2026-10-20"},"item":{...}}`, donde `item` es exactamente la fila anterior. Deben enviarse el corte y la ventana de la lista; un ID inexistente o fuera de esa ventana devuelve 404. Solo existen los campos de la fila: historial, pronóstico y demás apartados no disponibles se omiten; los campos existentes sin datos son `null`. También utiliza `no-store`. Los ID `M-...` pertenecen exclusivamente al fixture y no son `pac_id`.
|
||||||
|
|
||||||
|
#### Ruta futura a persistencia
|
||||||
|
|
||||||
|
La conexión CaMa se configura mediante `CAMA_DATABASE_URL` en `Persistance/persistance/settings.py` y `db.py`; el valor por defecto es `sqlite:///cama.db`, mientras `.env.example` propone otra ruta. Esto no identifica el motor instalado en DEV. En staging, `Paciente`, `Mastografia`, `BiopsiaMama` y `OrdenesEstudio` están en `Core/core/cama/models`; la plata expone `Persona`, `Procedimiento` y `Observacion` mediante `indicadores_kit/cama/tablas.py`. `indicadores_kit/cama/plata.py` transforma tomas, reportes y observaciones; no asumir que `cama_linea_de_tiempo` está disponible en una instalación sin comprobarlo.
|
||||||
|
|
||||||
|
Antes de consultar persistencia hay que validar identidad entre `pac_id` y `pac_id_hospital`, claves opcionales, la relación `biopsiamama.mast_id`, órdenes, múltiples estudios/resultados, fechas de toma y reporte, y selección de eventos conocidos al corte. La biopsia sin fecha de reporte no aporta aún resultado en el patrón de plata. El servicio `seguimiento_de` de CaCu ilustra sesión externa, reglas parametrizadas, agrupación por paciente, ventana, orden y seudonimización; sus reglas clínicas no deben copiarse como reglas CaMa. Un identificador opaco estable con clave secreta y separación por dominio, por ejemplo HMAC, requiere acordar gestión y rotación de clave, colisiones y resolución autorizada para detalle; no exponer `str(pac_id)` directamente.
|
||||||
|
|
||||||
|
Angular hoy exige `simulado === true` en `SeguimientoTablaService`. Una fuente real requiere acordar el contrato y tratamiento de `simulado: false`, adaptar tipos, validación, etiquetas, pruebas y acceso antes de consumirla. No se ha cambiado el proveedor ni se ha verificado el despliegue remoto.
|
||||||
|
|||||||
@@ -0,0 +1,477 @@
|
|||||||
|
{
|
||||||
|
"id": "cama_histopatologia_birads",
|
||||||
|
"titulo": "Histopatología por BI-RADS (demostración sintética)",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"contrato": "C2",
|
||||||
|
"unidad": "paciente",
|
||||||
|
"tipo_periodo": "semestre",
|
||||||
|
"periodos": [
|
||||||
|
"2025-S1"
|
||||||
|
],
|
||||||
|
"estrato": "birads",
|
||||||
|
"valores_estrato": [
|
||||||
|
"BIRADS_4",
|
||||||
|
"BIRADS_4A",
|
||||||
|
"BIRADS_4B",
|
||||||
|
"BIRADS_4C",
|
||||||
|
"BIRADS_5",
|
||||||
|
"BIRADS_6"
|
||||||
|
],
|
||||||
|
"etiquetas_estrato": {
|
||||||
|
"BIRADS_4": "BI-RADS 4 sin subtipo",
|
||||||
|
"BIRADS_4A": "BI-RADS 4A",
|
||||||
|
"BIRADS_4B": "BI-RADS 4B",
|
||||||
|
"BIRADS_4C": "BI-RADS 4C",
|
||||||
|
"BIRADS_5": "BI-RADS 5",
|
||||||
|
"BIRADS_6": "BI-RADS 6"
|
||||||
|
},
|
||||||
|
"grupos": {
|
||||||
|
"TOTAL": "Total"
|
||||||
|
},
|
||||||
|
"categorias": {
|
||||||
|
"BENIGNO": {
|
||||||
|
"etiqueta": "Benigno",
|
||||||
|
"color": "#9DBFE3",
|
||||||
|
"grupo": "NO_MALIGNO",
|
||||||
|
"gravedad": 1
|
||||||
|
},
|
||||||
|
"RIESGO_B3": {
|
||||||
|
"etiqueta": "Lesión de riesgo (B3)",
|
||||||
|
"color": "#2F6DB3",
|
||||||
|
"grupo": "NO_MALIGNO",
|
||||||
|
"gravedad": 2
|
||||||
|
},
|
||||||
|
"IN_SITU": {
|
||||||
|
"etiqueta": "Carcinoma in situ",
|
||||||
|
"color": "#D9822B",
|
||||||
|
"grupo": "MALIGNO",
|
||||||
|
"gravedad": 3
|
||||||
|
},
|
||||||
|
"INVASOR": {
|
||||||
|
"etiqueta": "Carcinoma invasor",
|
||||||
|
"color": "#B5482E",
|
||||||
|
"grupo": "MALIGNO",
|
||||||
|
"gravedad": 4
|
||||||
|
},
|
||||||
|
"SIN_BIOPSIA": {
|
||||||
|
"etiqueta": "Sin biopsia reportada",
|
||||||
|
"color": "#C9CDD2",
|
||||||
|
"grupo": null,
|
||||||
|
"gravedad": null
|
||||||
|
},
|
||||||
|
"SIN_DATO": {
|
||||||
|
"etiqueta": "Sin dato",
|
||||||
|
"color": "#C9CDD2",
|
||||||
|
"grupo": "SIN_DATO",
|
||||||
|
"gravedad": null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"grupos_de_categoria": {
|
||||||
|
"NO_MALIGNO": "No maligno",
|
||||||
|
"MALIGNO": "Maligno",
|
||||||
|
"SIN_DATO": "Sin dato"
|
||||||
|
},
|
||||||
|
"notas": [
|
||||||
|
"Convención provisional para datos sintéticos; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado."
|
||||||
|
],
|
||||||
|
"reportes": [
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"report_id": 141,
|
||||||
|
"periodo_inicio": "2025-01-01",
|
||||||
|
"periodo_fin": "2025-07-01",
|
||||||
|
"fecha_corte": "2025-12-31",
|
||||||
|
"generado_en": "2026-11-12T16:33:37.621606+00:00",
|
||||||
|
"kit_version": "0.8.0",
|
||||||
|
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
|
||||||
|
"parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe",
|
||||||
|
"parametros": {
|
||||||
|
"sql": {
|
||||||
|
"_catalogo": [
|
||||||
|
"BENIGNO",
|
||||||
|
"RIESGO_B3",
|
||||||
|
"IN_SITU",
|
||||||
|
"INVASOR"
|
||||||
|
],
|
||||||
|
"_grupos": [
|
||||||
|
"TOTAL"
|
||||||
|
],
|
||||||
|
"fecha_corte": "2025-12-31",
|
||||||
|
"periodo_fin": "2025-07-01",
|
||||||
|
"periodo_inicio": "2025-01-01"
|
||||||
|
},
|
||||||
|
"umbral_supresion": 5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"filas": [
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4",
|
||||||
|
"categoria": "BENIGNO",
|
||||||
|
"n": 2,
|
||||||
|
"orden": 0,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4",
|
||||||
|
"categoria": "RIESGO_B3",
|
||||||
|
"n": 0,
|
||||||
|
"orden": 1,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4",
|
||||||
|
"categoria": "IN_SITU",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 2,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4",
|
||||||
|
"categoria": "INVASOR",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 3,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4",
|
||||||
|
"categoria": "SIN_BIOPSIA",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 4,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4",
|
||||||
|
"categoria": "SIN_DATO",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 5,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4A",
|
||||||
|
"categoria": "BENIGNO",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 0,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4A",
|
||||||
|
"categoria": "RIESGO_B3",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 1,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4A",
|
||||||
|
"categoria": "IN_SITU",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 2,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4A",
|
||||||
|
"categoria": "INVASOR",
|
||||||
|
"n": 2,
|
||||||
|
"orden": 3,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4A",
|
||||||
|
"categoria": "SIN_BIOPSIA",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 4,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4A",
|
||||||
|
"categoria": "SIN_DATO",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 5,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4B",
|
||||||
|
"categoria": "BENIGNO",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 0,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4B",
|
||||||
|
"categoria": "RIESGO_B3",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 1,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4B",
|
||||||
|
"categoria": "IN_SITU",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 2,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4B",
|
||||||
|
"categoria": "INVASOR",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 3,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4B",
|
||||||
|
"categoria": "SIN_BIOPSIA",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 4,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4B",
|
||||||
|
"categoria": "SIN_DATO",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 5,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4C",
|
||||||
|
"categoria": "BENIGNO",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 0,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4C",
|
||||||
|
"categoria": "RIESGO_B3",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 1,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4C",
|
||||||
|
"categoria": "IN_SITU",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 2,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4C",
|
||||||
|
"categoria": "INVASOR",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 3,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4C",
|
||||||
|
"categoria": "SIN_BIOPSIA",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 4,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4C",
|
||||||
|
"categoria": "SIN_DATO",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 5,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_5",
|
||||||
|
"categoria": "BENIGNO",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 0,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_5",
|
||||||
|
"categoria": "RIESGO_B3",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 1,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_5",
|
||||||
|
"categoria": "IN_SITU",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 2,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_5",
|
||||||
|
"categoria": "INVASOR",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 3,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_5",
|
||||||
|
"categoria": "SIN_BIOPSIA",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 4,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_5",
|
||||||
|
"categoria": "SIN_DATO",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 5,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_6",
|
||||||
|
"categoria": "BENIGNO",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 0,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_6",
|
||||||
|
"categoria": "RIESGO_B3",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 1,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_6",
|
||||||
|
"categoria": "IN_SITU",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 2,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_6",
|
||||||
|
"categoria": "INVASOR",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 3,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_6",
|
||||||
|
"categoria": "SIN_BIOPSIA",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 4,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_6",
|
||||||
|
"categoria": "SIN_DATO",
|
||||||
|
"n": 1,
|
||||||
|
"orden": 5,
|
||||||
|
"suprimido": 0
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"totales_estrato": [
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4",
|
||||||
|
"n": 6,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4A",
|
||||||
|
"n": 7,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4B",
|
||||||
|
"n": 6,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_4C",
|
||||||
|
"n": 6,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_5",
|
||||||
|
"n": 6,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": "BIRADS_6",
|
||||||
|
"n": 6,
|
||||||
|
"suprimido": 0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
{
|
||||||
|
"id": "cama_histopatologia_birads",
|
||||||
|
"titulo": "Histopatología por BI-RADS (demostración sintética)",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"contrato": "C2",
|
||||||
|
"unidad": "paciente",
|
||||||
|
"tipo_periodo": "semestre",
|
||||||
|
"periodos": [
|
||||||
|
"2025-S1"
|
||||||
|
],
|
||||||
|
"estrato": null,
|
||||||
|
"valores_estrato": [],
|
||||||
|
"etiquetas_estrato": {},
|
||||||
|
"grupos": {
|
||||||
|
"TOTAL": "Total"
|
||||||
|
},
|
||||||
|
"categorias": {
|
||||||
|
"BENIGNO": {
|
||||||
|
"etiqueta": "Benigno",
|
||||||
|
"color": "#9DBFE3",
|
||||||
|
"grupo": "NO_MALIGNO",
|
||||||
|
"gravedad": 1
|
||||||
|
},
|
||||||
|
"RIESGO_B3": {
|
||||||
|
"etiqueta": "Lesión de riesgo (B3)",
|
||||||
|
"color": "#2F6DB3",
|
||||||
|
"grupo": "NO_MALIGNO",
|
||||||
|
"gravedad": 2
|
||||||
|
},
|
||||||
|
"IN_SITU": {
|
||||||
|
"etiqueta": "Carcinoma in situ",
|
||||||
|
"color": "#D9822B",
|
||||||
|
"grupo": "MALIGNO",
|
||||||
|
"gravedad": 3
|
||||||
|
},
|
||||||
|
"INVASOR": {
|
||||||
|
"etiqueta": "Carcinoma invasor",
|
||||||
|
"color": "#B5482E",
|
||||||
|
"grupo": "MALIGNO",
|
||||||
|
"gravedad": 4
|
||||||
|
},
|
||||||
|
"SIN_BIOPSIA": {
|
||||||
|
"etiqueta": "Sin biopsia reportada",
|
||||||
|
"color": "#C9CDD2",
|
||||||
|
"grupo": null,
|
||||||
|
"gravedad": null
|
||||||
|
},
|
||||||
|
"SIN_DATO": {
|
||||||
|
"etiqueta": "Sin dato",
|
||||||
|
"color": "#C9CDD2",
|
||||||
|
"grupo": "SIN_DATO",
|
||||||
|
"gravedad": null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"grupos_de_categoria": {
|
||||||
|
"NO_MALIGNO": "No maligno",
|
||||||
|
"MALIGNO": "Maligno",
|
||||||
|
"SIN_DATO": "Sin dato"
|
||||||
|
},
|
||||||
|
"notas": [
|
||||||
|
"Convención provisional para datos sintéticos; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado."
|
||||||
|
],
|
||||||
|
"reportes": [
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"report_id": 141,
|
||||||
|
"periodo_inicio": "2025-01-01",
|
||||||
|
"periodo_fin": "2025-07-01",
|
||||||
|
"fecha_corte": "2025-12-31",
|
||||||
|
"generado_en": "2026-11-12T16:33:37.621606+00:00",
|
||||||
|
"kit_version": "0.8.0",
|
||||||
|
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
|
||||||
|
"parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe",
|
||||||
|
"parametros": {
|
||||||
|
"sql": {
|
||||||
|
"_catalogo": [
|
||||||
|
"BENIGNO",
|
||||||
|
"RIESGO_B3",
|
||||||
|
"IN_SITU",
|
||||||
|
"INVASOR"
|
||||||
|
],
|
||||||
|
"_grupos": [
|
||||||
|
"TOTAL"
|
||||||
|
],
|
||||||
|
"fecha_corte": "2025-12-31",
|
||||||
|
"periodo_fin": "2025-07-01",
|
||||||
|
"periodo_inicio": "2025-01-01"
|
||||||
|
},
|
||||||
|
"umbral_supresion": 5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"filas": [
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": null,
|
||||||
|
"categoria": "BENIGNO",
|
||||||
|
"n": 7,
|
||||||
|
"orden": 0,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": null,
|
||||||
|
"categoria": "RIESGO_B3",
|
||||||
|
"n": 5,
|
||||||
|
"orden": 1,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": null,
|
||||||
|
"categoria": "IN_SITU",
|
||||||
|
"n": 6,
|
||||||
|
"orden": 2,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": null,
|
||||||
|
"categoria": "INVASOR",
|
||||||
|
"n": 7,
|
||||||
|
"orden": 3,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": null,
|
||||||
|
"categoria": "SIN_BIOPSIA",
|
||||||
|
"n": 6,
|
||||||
|
"orden": 4,
|
||||||
|
"suprimido": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"periodo": "2025-S1",
|
||||||
|
"grupo": "TOTAL",
|
||||||
|
"estrato": null,
|
||||||
|
"categoria": "SIN_DATO",
|
||||||
|
"n": 6,
|
||||||
|
"orden": 5,
|
||||||
|
"suprimido": 0
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"totales_estrato": []
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
# Breast cohort: synthetic integration contract
|
||||||
|
|
||||||
|
This contract is opt-in and only for a synthetic source. The server must set
|
||||||
|
`CAMA_COHORT_SYNTHETIC` to `True`, provide `CAMA_COHORT_READER(cutoff)` and
|
||||||
|
provide `CAMA_COHORT_ACCESS(request)`. Without a reader the aggregate returns
|
||||||
|
503. Without an access callback or when it returns false, all cohort patient
|
||||||
|
list, detail and export requests return 403. The existing fixture endpoints
|
||||||
|
remain available when `cohorte` is absent. This is not a production access
|
||||||
|
policy; authorization for real patient data has not been implemented.
|
||||||
|
|
||||||
|
`GET /cama/analisis/indicadores?corte=2026-10-20` returns a descriptive count
|
||||||
|
by BI-RADS. It includes `cohorte`, `revision`, `escenario`, `corte`,
|
||||||
|
`umbral_supresion`, `unidad`, `denominador` and `grupos`. A sample group is
|
||||||
|
`{"codigo":"BIRADS_5","n":6,"suprimido":false}`. A suppressed group's `n`
|
||||||
|
is null. The prototype's required `indicadores` array is empty: the new
|
||||||
|
`grupos` is a count distribution, not an incidence or survival estimate.
|
||||||
|
No survival, recurrence, subgroup grid or other analysis endpoints are supplied.
|
||||||
|
|
||||||
|
One patient contributes once: choose the latest mammogram with a BI-RADS report
|
||||||
|
available by cutoff; then include it if BI-RADS is 4, 4A, 4B, 4C, 5 or 6.
|
||||||
|
`revision` is a digest of the materialized cohort, including its data and stable
|
||||||
|
pseudonyms. It is an integrity marker, not an authorization credential.
|
||||||
|
|
||||||
|
For each patient request send `cohorte=cama_birads_v1`, `escenario=diagnostico`,
|
||||||
|
the exact `revision` and `corte` from the aggregate, `meses`, and any selected
|
||||||
|
`birads` or `grupo_edad`. For example:
|
||||||
|
|
||||||
|
```
|
||||||
|
GET /cama/seguimiento?cohorte=cama_birads_v1&escenario=diagnostico&revision=<revision>&corte=2026-10-20&meses=0&birads=BIRADS_5
|
||||||
|
```
|
||||||
|
|
||||||
|
For the same selected population use the same query on
|
||||||
|
`/cama/seguimiento/exportacion` or `/cama/pacientes/<id_seudonimo>`; list
|
||||||
|
accepts `page` and `page_size` (maximum 200). Export is limited to 5,000.
|
||||||
|
`meses=0` means the whole eligible cohort through cutoff. Its inclusive
|
||||||
|
`desde` is the earliest eligible mammography date before filtering; when the
|
||||||
|
cohort is empty it is the cutoff. `hasta` is the inclusive cutoff. Windows 1,
|
||||||
|
3, 6 and 12 retain their calendar-month semantics.
|
||||||
|
|
||||||
|
BI-RADS codes are `BIRADS_4`, `BIRADS_4A`, `BIRADS_4B`, `BIRADS_4C`,
|
||||||
|
`BIRADS_5`, `BIRADS_6`. Age options are `MENOR_40`, `40-49`, `50-59`,
|
||||||
|
`60-69`, `70+`, `SIN_DATO`. Filters combine with AND. Unknown, duplicated or
|
||||||
|
invalid parameters return 400. A filtered group with fewer than five patients,
|
||||||
|
or a nonempty whole cohort smaller than five, returns 403; empty unfiltered
|
||||||
|
cohorts return an empty page. A revision mismatch returns 409; absent detail
|
||||||
|
returns 404, an unavailable reader returns 503 and oversized exports return 413.
|
||||||
|
Authorization is checked independently of suppression. Responses containing
|
||||||
|
patient data carry `Cache-Control: no-store`.
|
||||||
|
|
||||||
|
The source uses the kit's silver mammography and biopsy queries. A biopsy must
|
||||||
|
be linked through its order to the selected mammogram and patient. Clinical
|
||||||
|
dates and load start timestamps are distinct fields. Procedure and observation
|
||||||
|
load timestamps must be no later than the UTC cutoff day. Silver stores only
|
||||||
|
the current row: a historical value overwritten later cannot be reconstructed,
|
||||||
|
and the person table does not version date of birth. Therefore this contract
|
||||||
|
does not certify a historical snapshot. Revision detects changes between
|
||||||
|
requests but does not persist the previous cohort. The current implementation
|
||||||
|
materializes the full cohort in memory and has not been sized for production.
|
||||||
|
|
||||||
|
The local example `examples/serve_cama_cohort.py` accepts an existing synthetic
|
||||||
|
SQLite file in `CAMA_SYNTHETIC_SQLITE`, opens it read-only, binds to loopback,
|
||||||
|
and requires `CAMA_COHORT_SECRET` and `CAMA_COHORT_ACCESS_TOKEN` of at least
|
||||||
|
32 characters. Send the latter in `X-Cama-Cohort-Token` for patient requests.
|
||||||
|
Other domain database URLs are set to isolated in-memory SQLite by the example.
|
||||||
|
The Windows-only `fcntl` shim raises if locking is attempted: this example does
|
||||||
|
not validate file-locking functionality.
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"""Run the cohort endpoints locally against an explicitly supplied synthetic SQLite file."""
|
||||||
|
|
||||||
|
import hmac
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sqlite3
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
if os.name == 'nt':
|
||||||
|
import sys
|
||||||
|
import types
|
||||||
|
|
||||||
|
fcntl = types.ModuleType('fcntl')
|
||||||
|
fcntl.LOCK_EX, fcntl.LOCK_UN = 2, 8
|
||||||
|
|
||||||
|
def unavailable(*args):
|
||||||
|
raise RuntimeError('File locking is unavailable in this local Windows example')
|
||||||
|
|
||||||
|
fcntl.flock = unavailable
|
||||||
|
sys.modules['fcntl'] = fcntl
|
||||||
|
|
||||||
|
|
||||||
|
path = Path(os.environ['CAMA_SYNTHETIC_SQLITE']).resolve(strict=True)
|
||||||
|
secret = os.environ['CAMA_COHORT_SECRET'].encode()
|
||||||
|
token = os.environ['CAMA_COHORT_ACCESS_TOKEN']
|
||||||
|
if len(secret) < 32 or len(token) < 32:
|
||||||
|
raise ValueError('Both the cohort secret and access token must be at least 32 characters')
|
||||||
|
if not path.is_file():
|
||||||
|
raise ValueError('The synthetic SQLite database must already exist')
|
||||||
|
|
||||||
|
# The cohort reader can only open the named file in read-only mode.
|
||||||
|
uri = 'file:' + quote(path.as_posix(), safe='/:') + '?mode=ro'
|
||||||
|
engine = create_engine('sqlite://', creator=lambda: sqlite3.connect(uri, uri=True))
|
||||||
|
|
||||||
|
# The other application blueprints must not inherit a live database URL.
|
||||||
|
for domain in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE'):
|
||||||
|
os.environ[domain + '_DATABASE_URL'] = 'sqlite:///:memory:'
|
||||||
|
|
||||||
|
from webapi import create_app
|
||||||
|
from webapi.cama_cohort import CamaCohort
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
|
||||||
|
|
||||||
|
def read(cutoff):
|
||||||
|
with Session(engine) as session:
|
||||||
|
return CamaCohort(session, secret).rows(cutoff)
|
||||||
|
|
||||||
|
|
||||||
|
def authorized(request):
|
||||||
|
return hmac.compare_digest(request.headers.get('X-Cama-Cohort-Token', ''), token)
|
||||||
|
|
||||||
|
|
||||||
|
app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=authorized)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
app.run(host='127.0.0.1', port=int(os.environ.get('CAMA_COHORT_PORT', '5059')), debug=False)
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
"""Exercise cohort selection with isolated synthetic silver rows and Flask clients."""
|
||||||
|
|
||||||
|
from datetime import date, datetime, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from flask import Flask
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from indicadores_kit.cama.tablas import TABLAS
|
||||||
|
from webapi.cama_analysis import analysis
|
||||||
|
from webapi.cama_cohort import CamaCohort
|
||||||
|
from webapi.seguimiento_cama import blueprint_seguimiento_cama
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def cohort_db():
|
||||||
|
"""Six eligible people, one linked biopsy and one biopsy without a link."""
|
||||||
|
t = TABLAS
|
||||||
|
engine = create_engine('sqlite:///:memory:')
|
||||||
|
for model in (t.Persona, t.Carga, t.Procedimiento, t.Observacion):
|
||||||
|
model.__table__.create(engine)
|
||||||
|
with Session(engine) as session:
|
||||||
|
session.add_all([
|
||||||
|
t.Carga(carga_id=1, fuente='test', inicio=datetime(2025, 1, 1, tzinfo=timezone.utc)),
|
||||||
|
t.Carga(carga_id=2, fuente='test', inicio=datetime(2027, 1, 1, tzinfo=timezone.utc)),
|
||||||
|
])
|
||||||
|
for patient in range(1, 7):
|
||||||
|
session.add(t.Persona(pac_id=patient, pac_id_hospital=f'T-{patient}', fecha_nacimiento=date(1970, 1, 1)))
|
||||||
|
session.add(t.Procedimiento(procedimiento_id=patient * 10, fuente_tabla='mastografia', fuente_id=str(patient),
|
||||||
|
carga_id=1, pac_id=patient, estudio_id='mastografia', clase='toma', fecha=date(2025, 2, 1)))
|
||||||
|
session.add(t.Procedimiento(procedimiento_id=patient * 10 + 1, padre_id=patient * 10, fuente_tabla='mastografia',
|
||||||
|
fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='mastografia',
|
||||||
|
clase='reporte', fecha=date(2025, 2, 2)))
|
||||||
|
session.add(t.Observacion(observacion_id=patient, procedimiento_id=patient * 10 + 1, carga_id=1,
|
||||||
|
pac_id=patient, resultado_id='mastografia.birads', valor_fuente='B5'))
|
||||||
|
for patient, parent, load in ((1, 10, 1), (2, None, 1), (3, 30, 2), (4, 40, 1)):
|
||||||
|
report_date = date(2027, 2, 15) if patient == 4 else date(2025, 2, 15)
|
||||||
|
session.add(t.Procedimiento(procedimiento_id=100 + patient * 2, padre_id=parent, fuente_tabla='biopsiamama',
|
||||||
|
fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='biopsia',
|
||||||
|
clase='orden', fecha=date(2025, 2, 10)))
|
||||||
|
session.add(t.Procedimiento(procedimiento_id=101 + patient * 2, padre_id=100 + patient * 2,
|
||||||
|
fuente_tabla='biopsiamama', fuente_id=str(patient), carga_id=1, pac_id=patient,
|
||||||
|
estudio_id='biopsia', clase='reporte', fecha=report_date))
|
||||||
|
session.add(t.Observacion(observacion_id=100 + patient, procedimiento_id=101 + patient * 2, carga_id=load,
|
||||||
|
pac_id=patient, resultado_id='biopsia.grado', valor_fuente='BENIGNO'))
|
||||||
|
session.commit()
|
||||||
|
yield engine
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(cohort_db):
|
||||||
|
"""Configure an explicitly synthetic reader and an authorized test principal."""
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.register_blueprint(analysis, url_prefix='/cama')
|
||||||
|
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix='/cama')
|
||||||
|
def read(cutoff):
|
||||||
|
with Session(cohort_db) as session:
|
||||||
|
return CamaCohort(session, b'x' * 32).rows(cutoff)
|
||||||
|
app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=lambda req: True)
|
||||||
|
return app.test_client()
|
||||||
|
|
||||||
|
|
||||||
|
QUERY = '?cohorte=cama_birads_v1&escenario=diagnostico&corte=2026-10-20&meses=0&birads=BIRADS_5'
|
||||||
|
|
||||||
|
|
||||||
|
def query(client, cutoff='2026-10-20'):
|
||||||
|
revision = client.get('/cama/analisis/indicadores?corte=' + cutoff).get_json()['revision']
|
||||||
|
return QUERY.replace('2026-10-20', cutoff) + '&revision=' + revision
|
||||||
|
|
||||||
|
|
||||||
|
def test_aggregate_list_detail_and_export_have_one_selection(client):
|
||||||
|
"""The published aggregate reconciles with pages, patient details and export."""
|
||||||
|
aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json()
|
||||||
|
assert next(g for g in aggregate['grupos'] if g['codigo'] == 'BIRADS_5')['n'] == 6
|
||||||
|
selection = query(client)
|
||||||
|
first = client.get('/cama/seguimiento' + selection + '&page_size=2').get_json()
|
||||||
|
assert first['ventana'] == {'meses': 0, 'desde': '2025-02-01', 'hasta': '2026-10-20'}
|
||||||
|
items = []
|
||||||
|
for page in (1, 2, 3):
|
||||||
|
data = client.get('/cama/seguimiento' + selection + f'&page_size=2&page={page}').get_json()
|
||||||
|
items.extend(data['items'])
|
||||||
|
exported = client.get('/cama/seguimiento/exportacion' + selection).get_json()
|
||||||
|
assert exported['items'] == items and exported['total_items'] == 6
|
||||||
|
for item in items:
|
||||||
|
detail = client.get('/cama/pacientes/' + item['id_seudonimo'] + selection).get_json()
|
||||||
|
assert detail['item'] == item and detail['corte'] == aggregate['corte']
|
||||||
|
assert sum(item['biopsia'] == 'BENIGNO' for item in items) == 1
|
||||||
|
assert client.get('/cama/seguimiento' + selection).get_json()['items'] == items
|
||||||
|
|
||||||
|
|
||||||
|
def test_rejects_unknown_and_suppressed_selections_and_denies_access(client):
|
||||||
|
"""Unknown filters and small groups cannot silently broaden patient access."""
|
||||||
|
selection = query(client)
|
||||||
|
assert client.get('/cama/seguimiento' + selection + '&estadio=IV').status_code == 400
|
||||||
|
assert client.get('/cama/seguimiento' + selection.replace('BIRADS_5', 'BIRADS_4A')).status_code == 403
|
||||||
|
assert client.get('/cama/seguimiento' + selection.replace('cama_birads_v1', 'otra')).status_code == 400
|
||||||
|
assert client.get('/cama/seguimiento' + selection.replace(selection[-64:], '0' * 64)).status_code == 409
|
||||||
|
client.application.config['CAMA_COHORT_ACCESS'] = None
|
||||||
|
assert client.get('/cama/seguimiento' + selection).status_code == 403
|
||||||
|
assert client.get('/cama/seguimiento/exportacion' + selection).status_code == 403
|
||||||
|
assert client.get('/cama/pacientes/some-id' + selection).status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_cutoff_excludes_later_clinical_and_load_dates(client):
|
||||||
|
"""A report or observation not yet known at the cutoff cannot appear."""
|
||||||
|
early = query(client, '2025-02-09')
|
||||||
|
rows = client.get('/cama/seguimiento' + early).get_json()['items']
|
||||||
|
assert len(rows) == 6 and all(row['biopsia'] is None for row in rows)
|
||||||
|
empty = query(client, '2025-02-01').replace('&birads=BIRADS_5', '')
|
||||||
|
response = client.get('/cama/seguimiento' + empty).get_json()
|
||||||
|
assert response['items'] == [] and response['ventana']['desde'] == '2025-02-01'
|
||||||
|
|
||||||
|
|
||||||
|
def test_links_and_load_dates_are_distinct(client, cohort_db):
|
||||||
|
"""A missing link and a late load cannot supply a diagnosis before cutoff."""
|
||||||
|
with Session(cohort_db) as session:
|
||||||
|
ids = {i: CamaCohort(session, b'x' * 32)._id(i) for i in range(1, 5)}
|
||||||
|
data = client.get('/cama/seguimiento' + query(client)).get_json()
|
||||||
|
rows = {item['id_seudonimo']: item for item in data['items']}
|
||||||
|
assert rows[ids[1]]['biopsia'] == 'BENIGNO'
|
||||||
|
assert rows[ids[2]]['biopsia'] is None and rows[ids[2]]['biopsia_fecha'] is None
|
||||||
|
assert rows[ids[3]]['biopsia'] is None and rows[ids[3]]['biopsia_fecha'] == '2025-02-15'
|
||||||
|
assert rows[ids[4]]['biopsia'] is None and rows[ids[4]]['biopsia_fecha'] is None
|
||||||
|
later = client.get('/cama/seguimiento' + query(client, '2027-12-01')).get_json()
|
||||||
|
rows_later = {item['id_seudonimo']: item for item in later['items']}
|
||||||
|
assert rows_later[ids[3]]['biopsia'] == 'BENIGNO'
|
||||||
|
assert rows_later[ids[4]]['biopsia_fecha'] == '2027-02-15'
|
||||||
|
assert set(rows) == set(rows_later)
|
||||||
|
|
||||||
|
|
||||||
|
def test_full_application_registers_cohort_and_preserves_legacy(client):
|
||||||
|
"""The application registers the aggregate while retaining legacy follow-up."""
|
||||||
|
from webapi import create_app
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
app.config.update(client.application.config)
|
||||||
|
full = app.test_client()
|
||||||
|
assert full.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 200
|
||||||
|
assert full.get('/cama/seguimiento').status_code == 200
|
||||||
|
assert full.get('/cama/seguimiento?meses=12&resultado=INVASOR').status_code == 400
|
||||||
|
rows = full.get('/cama/seguimiento?corte=2026-10-16&meses=1').get_json()['items']
|
||||||
|
future = next(row for row in rows if row['id_seudonimo'] == 'M-0002')
|
||||||
|
assert future['biopsia_fecha'] is None and future['biopsia'] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_windows_and_disabled_provider(client):
|
||||||
|
"""Regular windows remain available and the reader is opt-in."""
|
||||||
|
selection = query(client).replace('&meses=0', '&meses=1').replace('&birads=BIRADS_5', '')
|
||||||
|
body = client.get('/cama/seguimiento' + selection).get_json()
|
||||||
|
assert body['items'] == [] and body['ventana']['desde'] == '2026-09-21'
|
||||||
|
client.application.config['CAMA_COHORT_SYNTHETIC'] = False
|
||||||
|
assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503
|
||||||
|
|
||||||
|
|
||||||
|
def test_newer_noneligible_result_changes_revision_and_excludes_patient(client, cohort_db):
|
||||||
|
"""The latest reported result is selected before checking BI-RADS eligibility."""
|
||||||
|
previous = query(client)
|
||||||
|
with Session(cohort_db) as session:
|
||||||
|
session.add(TABLAS.Procedimiento(procedimiento_id=200, fuente_tabla='mastografia', fuente_id='new',
|
||||||
|
carga_id=1, pac_id=6, estudio_id='mastografia', clase='toma', fecha=date(2025, 4, 1)))
|
||||||
|
session.add(TABLAS.Procedimiento(procedimiento_id=201, padre_id=200, fuente_tabla='mastografia', fuente_id='new',
|
||||||
|
carga_id=1, pac_id=6, estudio_id='mastografia', clase='reporte', fecha=date(2025, 4, 2)))
|
||||||
|
session.add(TABLAS.Observacion(observacion_id=200, procedimiento_id=201, carga_id=1, pac_id=6,
|
||||||
|
resultado_id='mastografia.birads', valor_fuente='B1'))
|
||||||
|
session.commit()
|
||||||
|
assert client.get('/cama/seguimiento' + previous).status_code == 409
|
||||||
|
aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json()
|
||||||
|
assert next(g for g in aggregate['grupos'] if g['codigo'] == 'BIRADS_5')['n'] == 5
|
||||||
|
assert len(client.get('/cama/seguimiento' + query(client)).get_json()['items']) == 5
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
"""`commit_discovered_fields`: writes captions no known field claims
|
||||||
|
straight into `procedimiento`/`observacion`, tagged apart from every
|
||||||
|
staging-derived row with `FUENTE_CATALOGO_ABIERTO`. Fails if a known
|
||||||
|
patient's discovered fields stop landing there, or if an unmatched one
|
||||||
|
stops growing the catalog instead of being silently dropped.
|
||||||
|
"""
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlmodel import select
|
||||||
|
|
||||||
|
from indicadores_kit.registry import catalogos
|
||||||
|
from indicadores_kit.tablas import tablas_de
|
||||||
|
|
||||||
|
from extraction import ExtractedRecord
|
||||||
|
from extraction.nlp import DiscoveredField, Evidence
|
||||||
|
from webapi.imports.services.catalog_commit_service import FUENTE_CATALOGO_ABIERTO, commit_discovered_fields
|
||||||
|
|
||||||
|
EVIDENCE = Evidence("fila.pdf", 1, "")
|
||||||
|
|
||||||
|
|
||||||
|
def _record(key: str, pairs: list[tuple[str, str]]) -> ExtractedRecord:
|
||||||
|
return ExtractedRecord(
|
||||||
|
values={}, sources=[], key=key, discovered=[DiscoveredField(c, v, EVIDENCE) for c, v in pairs]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def cacu_catalog(tmp_path, monkeypatch):
|
||||||
|
"""`add_resultado`/`sincronizar` write real rows and a real file:
|
||||||
|
kept off the checked-in `cacu.toml` and off any other domain's data."""
|
||||||
|
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||||
|
(tmp_path / "cacu.toml").write_text(
|
||||||
|
'[citologia]\netiqueta = "Citología cervical"\n\n'
|
||||||
|
'[citologia.resultados.calidad_muestra]\netiqueta = "Calidad de la muestra"\ntipo_valor = "texto"\n',
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
return tmp_path / "cacu.toml"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def known_patient(wire_domain):
|
||||||
|
wire_domain("cacu")
|
||||||
|
from core.cacu.paciente.model import Paciente
|
||||||
|
from persistance.cacu import paciente_repository
|
||||||
|
|
||||||
|
paciente_repository.create(Paciente(pac_id_hospital="DOC-FB-1", pac_fecha_nacimiento=date(1990, 1, 1)))
|
||||||
|
return "DOC-FB-1"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_matched_field_is_written_on_the_existing_resultado(cacu_catalog, known_patient):
|
||||||
|
result = commit_discovered_fields(
|
||||||
|
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria")])], proyecto="cacu", estudio_id="citologia"
|
||||||
|
)
|
||||||
|
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
|
||||||
|
|
||||||
|
from persistance.cacu import carga_repository
|
||||||
|
|
||||||
|
with carga_repository.open_session() as sesion:
|
||||||
|
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||||
|
assert observacion.resultado_id == "citologia.calidad_muestra"
|
||||||
|
assert observacion.valor_texto == "Insatisfactoria"
|
||||||
|
[procedimiento] = sesion.exec(select(carga_repository.procedimiento)).all()
|
||||||
|
assert procedimiento.fuente_tabla == FUENTE_CATALOGO_ABIERTO
|
||||||
|
assert procedimiento.fuente_id == known_patient
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_unmatched_field_mints_a_resultado_and_is_written_too(cacu_catalog, known_patient):
|
||||||
|
result = commit_discovered_fields(
|
||||||
|
[_record(known_patient, [("Tipo de fijador", "Formol")])], proyecto="cacu", estudio_id="citologia"
|
||||||
|
)
|
||||||
|
assert result.fields_minted == 1
|
||||||
|
nombres = set(catalogos._leer(cacu_catalog)["citologia"]["resultados"])
|
||||||
|
assert nombres == {"calidad_muestra", "tipo_de_fijador"} # the fixture's field, plus the minted one
|
||||||
|
minted_id = "citologia.tipo_de_fijador"
|
||||||
|
|
||||||
|
catalogo = catalogos.catalogo_desde_toml(cacu_catalog, tablas=tablas_de("cacu"))
|
||||||
|
assert minted_id in {r.resultado_id for r in catalogo.resultados}
|
||||||
|
|
||||||
|
from persistance.cacu import carga_repository
|
||||||
|
|
||||||
|
with carga_repository.open_session() as sesion:
|
||||||
|
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||||
|
assert observacion.resultado_id == minted_id
|
||||||
|
assert observacion.valor_texto == "Formol"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_patient_outside_persona_is_skipped_not_dropped_silently(cacu_catalog, known_patient):
|
||||||
|
result = commit_discovered_fields(
|
||||||
|
[_record("NOT-A-PATIENT", [("Calidad de muestra", "x")])], proyecto="cacu", estudio_id="citologia"
|
||||||
|
)
|
||||||
|
assert (result.records_written, result.records_without_patient) == (0, 1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_record_without_discovered_fields_is_ignored(cacu_catalog, known_patient):
|
||||||
|
result = commit_discovered_fields([_record(known_patient, [])], proyecto="cacu", estudio_id="citologia")
|
||||||
|
assert result.records_written == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_repeated_caption_is_folded_not_written_twice(cacu_catalog, known_patient):
|
||||||
|
"""A static label printed on several pages of the same document (a date,
|
||||||
|
a signature line) discovers as one `DiscoveredField` per occurrence,
|
||||||
|
on purpose (`discover_captions`'s docstring). Fails if this stops
|
||||||
|
folding repeats before writing: `observacion` has one row per
|
||||||
|
`(procedimiento, resultado_id)`, so a second occurrence of the same
|
||||||
|
resultado_id raises `IntegrityError` and the whole record's fields —
|
||||||
|
including the ones that weren't duplicated — are lost."""
|
||||||
|
result = commit_discovered_fields(
|
||||||
|
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria"), ("Calidad de muestra", "Satisfactoria")])],
|
||||||
|
proyecto="cacu",
|
||||||
|
estudio_id="citologia",
|
||||||
|
)
|
||||||
|
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
|
||||||
|
|
||||||
|
from persistance.cacu import carga_repository
|
||||||
|
|
||||||
|
with carga_repository.open_session() as sesion:
|
||||||
|
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||||
|
assert observacion.resultado_id == "citologia.calidad_muestra"
|
||||||
|
assert observacion.valor_texto == "Insatisfactoria"
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
"""`catalog_matching.match_or_mint`: fails if it stops reusing an existing
|
||||||
|
catalog field for an OCR caption that's clearly the same thing worded
|
||||||
|
differently, or if an unmatched caption stops being added to the catalog
|
||||||
|
and silently drops its value instead.
|
||||||
|
"""
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from indicadores_kit.registry import catalogos
|
||||||
|
from indicadores_kit.registry.catalogos import Catalogo
|
||||||
|
from indicadores_kit.tablas import tablas_de
|
||||||
|
|
||||||
|
from extraction.nlp import DiscoveredField, Evidence
|
||||||
|
from webapi.imports.schemas.catalog_matching import match_or_mint
|
||||||
|
|
||||||
|
EVIDENCE = Evidence("fila.pdf", 1, "")
|
||||||
|
|
||||||
|
|
||||||
|
def _field(caption: str, value: str) -> DiscoveredField:
|
||||||
|
return DiscoveredField(caption, value, EVIDENCE)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def catalogo() -> Catalogo:
|
||||||
|
tablas = tablas_de("cacu")
|
||||||
|
return Catalogo(
|
||||||
|
estudios=[tablas.CatEstudio(estudio_id="citologia", etiqueta="Citología cervical")],
|
||||||
|
resultados=[
|
||||||
|
tablas.CatResultado(
|
||||||
|
resultado_id="citologia.calidad_muestra", estudio_id="citologia",
|
||||||
|
etiqueta="Calidad de la muestra", tipo_valor="codigo",
|
||||||
|
),
|
||||||
|
tablas.CatResultado(
|
||||||
|
resultado_id="citologia.celulas_glandulares", estudio_id="citologia",
|
||||||
|
etiqueta="Células glandulares", tipo_valor="texto",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
valores=[
|
||||||
|
tablas.CatValor(
|
||||||
|
resultado_id="citologia.calidad_muestra", valor_id="SATISFACTORIO",
|
||||||
|
etiqueta="Satisfactoria", orden=1, estado="vigente",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def catalogo_toml(tmp_path, monkeypatch):
|
||||||
|
"""`add_resultado` writes to disk; keep it off the real `cacu.toml`."""
|
||||||
|
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||||
|
(tmp_path / "cacu.toml").write_text("", encoding="utf-8")
|
||||||
|
return tmp_path / "cacu.toml"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_worded_differently_caption_reuses_the_existing_resultado(catalogo, catalogo_toml):
|
||||||
|
[matched] = match_or_mint(
|
||||||
|
[_field("Calidad de muestra", "SATISFACTORIO")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
|
||||||
|
)
|
||||||
|
assert matched.resultado_id == "citologia.calidad_muestra" and not matched.is_new
|
||||||
|
assert matched.observacion["valor_id"] == "SATISFACTORIO"
|
||||||
|
assert catalogo_toml.read_text(encoding="utf-8") == "" # nothing minted
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_unmatched_caption_in_a_known_estudio_is_minted_there(catalogo, catalogo_toml):
|
||||||
|
[matched] = match_or_mint(
|
||||||
|
[_field("Tipo de fijador", "Formol")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
|
||||||
|
)
|
||||||
|
assert matched.is_new and matched.resultado_id.startswith("citologia.")
|
||||||
|
assert matched.observacion["valor_texto"] == "Formol"
|
||||||
|
|
||||||
|
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
|
||||||
|
assert matched.resultado_id in {r.resultado_id for r in sincronizado.resultados}
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_unmatched_caption_with_no_estudio_falls_back_to_documento_externo(catalogo, catalogo_toml):
|
||||||
|
[matched] = match_or_mint([_field("Observación suelta", "algo")], proyecto="cacu", catalogo=catalogo)
|
||||||
|
assert matched.resultado_id == "documento_externo." + matched.resultado_id.split(".", 1)[1]
|
||||||
|
|
||||||
|
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
|
||||||
|
assert "documento_externo" in {e.estudio_id for e in sincronizado.estudios}
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_inferred_tipo_valor_follows_the_value_shape(catalogo, catalogo_toml):
|
||||||
|
fecha, numero, texto = match_or_mint(
|
||||||
|
[_field("Fecha de algo", "15/01/2024"), _field("Cuenta de algo", "12.5"), _field("Nota libre", "ninguna")],
|
||||||
|
proyecto="cacu", catalogo=catalogo, estudio_id="citologia",
|
||||||
|
)
|
||||||
|
assert fecha.observacion["valor_fecha"] == date(2024, 1, 15)
|
||||||
|
assert numero.observacion["valor_numerico"] == 12.5
|
||||||
|
assert texto.observacion["valor_texto"] == "ninguna"
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
"""`DocumentConnector` reading its documents from a SQL source instead of
|
||||||
|
uploaded files: one document per row, read from a column that may hold a
|
||||||
|
PDF (`varbinary(max)`) or already be plain text, both without a filesystem
|
||||||
|
path in between. Fails if the bridge to `SqlConnector` breaks, or if a
|
||||||
|
plain-text column stops reaching the same field extraction a PDF does.
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy import create_engine, text
|
||||||
|
|
||||||
|
from extraction.testing import text_pdf
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def client(wire_domain):
|
||||||
|
wire_domain("cacu")
|
||||||
|
|
||||||
|
from webapi import create_app
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
app.config.update(TESTING=True)
|
||||||
|
with app.test_client() as test_client:
|
||||||
|
yield test_client
|
||||||
|
|
||||||
|
|
||||||
|
REPORT = text_pdf(
|
||||||
|
[["Expediente: SQL-0001", "Fecha de nacimiento: 12/03/1981", "VPH alto riesgo: POSITIVO"]]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def sqlite_studies_table(tmp_path):
|
||||||
|
"""A source table shaped like ISSSTELEON's: one row per study, its
|
||||||
|
report in a binary column, plus a plain-text variant of the same
|
||||||
|
report in another row, both alongside the row's own key column."""
|
||||||
|
db_path = tmp_path / "estudios.db"
|
||||||
|
url = f"sqlite:///{db_path}"
|
||||||
|
engine = create_engine(url)
|
||||||
|
with engine.begin() as conn:
|
||||||
|
conn.execute(text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
|
||||||
|
conn.execute(
|
||||||
|
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
|
||||||
|
{"id": "ROW-1", "reporte": REPORT},
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
|
||||||
|
{
|
||||||
|
"id": "ROW-2",
|
||||||
|
"reporte": "Expediente: SQL-0002\nFecha de nacimiento: 01/01/1990\nVPH alto riesgo: NEGATIVO",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return url
|
||||||
|
|
||||||
|
|
||||||
|
def _sql_payload(url: str, **overrides) -> dict:
|
||||||
|
return {"connection_string": url, "table": "estudios", "column": "reporte", "key_column": "estudio_id", **overrides}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table):
|
||||||
|
body = client.post(
|
||||||
|
"/imports/sources/document/extract",
|
||||||
|
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
|
||||||
|
).get_json()
|
||||||
|
[first, second] = body["records"]
|
||||||
|
assert first["key"] == "SQL-0001"
|
||||||
|
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||||
|
assert first["sources"] == [{"document": "ROW-1", "page_numbers": [1]}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_plain_text_column_reaches_the_same_field_extraction(client, sqlite_studies_table):
|
||||||
|
"""Fails if a source whose bundle is a plain string (not binary at
|
||||||
|
all) stops producing fields, since ISSSTELEON's column may not always
|
||||||
|
be a PDF (`extraction.readers.TextReader`)."""
|
||||||
|
body = client.post(
|
||||||
|
"/imports/sources/document/extract",
|
||||||
|
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
|
||||||
|
).get_json()
|
||||||
|
[_, second] = body["records"]
|
||||||
|
assert second["key"] == "SQL-0002"
|
||||||
|
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
|
||||||
|
assert second["sources"] == [{"document": "ROW-2", "page_numbers": [1]}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_sql_sourced_documents_commit_like_uploaded_ones(client, sqlite_studies_table):
|
||||||
|
source = {
|
||||||
|
"source_type": "document",
|
||||||
|
"target": "cacu.CitologiaCervical",
|
||||||
|
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||||
|
"payload": {"sql": _sql_payload(sqlite_studies_table)},
|
||||||
|
"label": "estudios",
|
||||||
|
}
|
||||||
|
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||||
|
assert result["created"] == 2, result
|
||||||
|
|
||||||
|
from persistance.cacu import citologia_cervical_repository
|
||||||
|
|
||||||
|
rows = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100) if r.pac_id_hospital.startswith("SQL-")}
|
||||||
|
assert rows["SQL-0001"].cit_vph_resultado == "POSITIVO"
|
||||||
|
assert rows["SQL-0002"].cit_vph_resultado == "NEGATIVO"
|
||||||
|
|
||||||
|
|
||||||
|
def test_column_and_key_column_must_differ(client, sqlite_studies_table):
|
||||||
|
response = client.post(
|
||||||
|
"/imports/sources/document/extract",
|
||||||
|
json={"sql": _sql_payload(sqlite_studies_table, key_column="reporte"), "target": "cacu.CitologiaCervical"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 400 and "key_column" in response.get_json()["error"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_missing_column_is_a_bad_request(client, sqlite_studies_table):
|
||||||
|
payload = _sql_payload(sqlite_studies_table)
|
||||||
|
del payload["column"]
|
||||||
|
response = client.post(
|
||||||
|
"/imports/sources/document/extract", json={"sql": payload, "target": "cacu.CitologiaCervical"}
|
||||||
|
)
|
||||||
|
assert response.status_code == 400 and "column" in response.get_json()["error"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(client, tmp_path, monkeypatch):
|
||||||
|
"""Mixing sources: a field the import schema doesn't name (`Tipo de
|
||||||
|
fijador`) still reaches the silver layer through the open-catalog
|
||||||
|
path, alongside the recognized fields `commit_sources` writes as
|
||||||
|
before. Fails if `/imports/commit` stops wiring that second path in.
|
||||||
|
Its own table and patient (`SQL-EXTRA-1`), so it doesn't collide with
|
||||||
|
the module's other tests sharing this `client`'s database."""
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from sqlalchemy import create_engine, text as sa_text
|
||||||
|
from sqlmodel import select
|
||||||
|
|
||||||
|
from indicadores_kit.registry import catalogos
|
||||||
|
from core.cacu.paciente.model import Paciente
|
||||||
|
from persistance.cacu import carga_repository, paciente_repository
|
||||||
|
|
||||||
|
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||||
|
(tmp_path / "cacu.toml").write_text('[citologia]\netiqueta = "Citología cervical"\n', encoding="utf-8")
|
||||||
|
paciente_repository.create(Paciente(pac_id_hospital="SQL-EXTRA-1", pac_fecha_nacimiento=date(1981, 3, 12)))
|
||||||
|
|
||||||
|
db_url = f"sqlite:///{tmp_path / 'estudios_extra.db'}"
|
||||||
|
report = text_pdf([["Expediente: SQL-EXTRA-1", "VPH alto riesgo: POSITIVO", "Tipo de fijador: Formol"]])
|
||||||
|
with create_engine(db_url).begin() as conn:
|
||||||
|
conn.execute(sa_text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
|
||||||
|
conn.execute(sa_text("INSERT INTO estudios (estudio_id, reporte) VALUES ('ROW-1', :r)"), {"r": report})
|
||||||
|
|
||||||
|
source = {
|
||||||
|
"source_type": "document",
|
||||||
|
"target": "cacu.CitologiaCervical",
|
||||||
|
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||||
|
"payload": {"sql": _sql_payload(db_url), "estudio_id": "citologia"},
|
||||||
|
"label": "estudios_extra",
|
||||||
|
}
|
||||||
|
body = client.post("/imports/commit", json={"sources": [source]}).get_json()
|
||||||
|
assert body["results"][0]["created"] == 1, body
|
||||||
|
|
||||||
|
[report] = [r for r in body["catalog_fallback"] if r["label"] == "estudios_extra"]
|
||||||
|
assert report["records_written"] == 1 and report["fields_minted"] == 1
|
||||||
|
|
||||||
|
with carga_repository.open_session() as sesion:
|
||||||
|
[minted] = list(
|
||||||
|
sesion.exec(select(carga_repository.observacion).where(carga_repository.observacion.pac_id.in_(
|
||||||
|
select(Paciente.pac_id).where(Paciente.pac_id_hospital == "SQL-EXTRA-1")
|
||||||
|
)))
|
||||||
|
)
|
||||||
|
assert minted.resultado_id == "citologia.tipo_de_fijador" and minted.valor_texto == "Formol"
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
"""Publicación HTTP de CAM-01 y CAM-02 sobre la base sintética del kit."""
|
||||||
|
import pytest
|
||||||
|
from conftest import cliente_de
|
||||||
|
|
||||||
|
IDS = {"cama_tasa_deteccion_histopatologica": "C1", "cama_dias_resultado_diagnostico": "C3r"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def client(tmp_path_factory):
|
||||||
|
yield from cliente_de("cama", tmp_path_factory)
|
||||||
|
|
||||||
|
|
||||||
|
def test_catalogo_publica_las_dos_medidas(client):
|
||||||
|
"""Keep C1/C3r publication while titles remain suitable for the interface."""
|
||||||
|
catalogo = {item["id"]: item for item in client.get("/cama/indicadores").get_json()}
|
||||||
|
for identificador, contrato in IDS.items():
|
||||||
|
assert catalogo[identificador]["contrato"] == contrato
|
||||||
|
assert "demostración" not in catalogo[identificador]["titulo"]
|
||||||
|
assert "sintética" not in catalogo[identificador]["titulo"]
|
||||||
|
assert set(catalogo[identificador]["tipos_periodo"]) == {"mes", "semestre"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("indicador,contrato", IDS.items())
|
||||||
|
def test_periodos_metadatos_y_datos(client, indicador, contrato):
|
||||||
|
raiz = f"/cama/indicadores/{indicador}"
|
||||||
|
assert client.get(raiz + "/metadatos").status_code == 200
|
||||||
|
assert client.get(raiz + "/periodos").status_code == 200
|
||||||
|
response = client.get(raiz + "/datos?periodos=2025-S1")
|
||||||
|
assert response.status_code == 200 and response.is_json
|
||||||
|
data = response.get_json()
|
||||||
|
assert data["contrato"] == contrato and data["periodos"] == ["2025-S1"]
|
||||||
|
assert isinstance(data["filas"], list) and data["filas"]
|
||||||
|
assert client.get(raiz + "/datos?periodos=2025-13").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def client_sin_supresion(tmp_path_factory):
|
||||||
|
from indicadores_kit.demostracion import base_de_prueba
|
||||||
|
from indicadores_kit.registry.parametros import RUTA_PARAMETROS
|
||||||
|
from persistance import db
|
||||||
|
from persistance.settings import settings
|
||||||
|
from webapi import create_app
|
||||||
|
|
||||||
|
carpeta = tmp_path_factory.mktemp("cama_f4b2")
|
||||||
|
parametros = carpeta / "parametros.toml"
|
||||||
|
parametros.write_text(RUTA_PARAMETROS.read_text(encoding="utf-8").replace("valor = 5", "valor = 1"), encoding="utf-8")
|
||||||
|
with pytest.MonkeyPatch.context() as mp:
|
||||||
|
mp.setattr(settings, "cama_database_url", f"sqlite:///{carpeta / 'demo.db'}")
|
||||||
|
db.get_cama_engine.cache_clear()
|
||||||
|
try:
|
||||||
|
base_de_prueba(db.get_cama_engine(), "cama", ruta_parametros=parametros)
|
||||||
|
yield create_app().test_client()
|
||||||
|
finally:
|
||||||
|
db.get_cama_engine().dispose()
|
||||||
|
db.get_cama_engine.cache_clear()
|
||||||
|
|
||||||
|
|
||||||
|
def test_valores_sinteticos_visibles_con_umbral_de_prueba(client_sin_supresion):
|
||||||
|
raiz = "/cama/indicadores/"
|
||||||
|
c1 = client_sin_supresion.get(raiz + "cama_tasa_deteccion_histopatologica/datos?periodos=2025-S1").get_json()
|
||||||
|
c3 = client_sin_supresion.get(raiz + "cama_dias_resultado_diagnostico/datos?periodos=2025-S1").get_json()
|
||||||
|
assert c1["filas"][0]["numerador"] == 0 and c1["filas"][0]["denominador"] == 1
|
||||||
|
assert c1["filas"][0]["valor"] == 0 and c1["filas"][0]["ic_alto"] > 0
|
||||||
|
fila = c3["filas"][0]
|
||||||
|
assert (fila["n"], fila["q1"], fila["mediana"], fila["q3"]) == (5, 3, 7, 10)
|
||||||
|
assert fila["n_excluido"] == 1 and fila["unidad"] == "dias"
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
"""Publicación C2 de CAM-03 con dos matrices sintéticas y base aislada."""
|
||||||
|
from datetime import date
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlmodel import Session
|
||||||
|
from conftest import cliente_de
|
||||||
|
from indicadores_kit.cama.familias.histopatologia_birads.fixture_demo import agregar_en
|
||||||
|
from indicadores_kit.cama.tablas import TABLAS
|
||||||
|
from indicadores_kit.demostracion import base_de_prueba
|
||||||
|
from indicadores_kit.pruebas import calcular_measure
|
||||||
|
from indicadores_kit.registry.measures import measures_de
|
||||||
|
from persistance import db
|
||||||
|
from persistance.settings import settings
|
||||||
|
from webapi import create_app
|
||||||
|
|
||||||
|
ID = "cama_histopatologia_birads"
|
||||||
|
RAIZ = f"/cama/indicadores/{ID}"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def publicaciones(tmp_path_factory):
|
||||||
|
resultados = []
|
||||||
|
for variante in (1, 2):
|
||||||
|
ruta = tmp_path_factory.mktemp(f"matriz{variante}") / "cama.db"
|
||||||
|
with pytest.MonkeyPatch.context() as mp:
|
||||||
|
mp.setattr(settings, "cama_database_url", f"sqlite:///{ruta}")
|
||||||
|
db.get_cama_engine.cache_clear()
|
||||||
|
motor = db.get_cama_engine()
|
||||||
|
try:
|
||||||
|
base_de_prueba(motor, "cama")
|
||||||
|
with Session(motor) as sesion:
|
||||||
|
agregar_en(sesion, variante=variante)
|
||||||
|
medida = measures_de("cama")[ID]
|
||||||
|
for periodo in ("2025-S1", "2025-02"):
|
||||||
|
calcular_measure(sesion, medida, periodo, tablas=TABLAS, corte=date(2025, 12, 31))
|
||||||
|
cliente = create_app().test_client()
|
||||||
|
general = cliente.get(RAIZ + "/datos?periodos=2025-S1")
|
||||||
|
matriz = cliente.get(RAIZ + "/datos?periodos=2025-S1&estrato=birads")
|
||||||
|
assert general.status_code == matriz.status_code == 200
|
||||||
|
resultados.append((general.get_json(), matriz.get_json()))
|
||||||
|
if variante == 1:
|
||||||
|
destinos = os.environ.get("CAM03_EJEMPLOS_DIR")
|
||||||
|
if destinos:
|
||||||
|
carpeta = Path(destinos)
|
||||||
|
carpeta.mkdir(parents=True, exist_ok=True)
|
||||||
|
for nombre, respuesta in (("cam03-general.json", general), ("cam03-birads.json", matriz)):
|
||||||
|
(carpeta / nombre).write_text(json.dumps(respuesta.get_json(), ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||||
|
catalogo = cliente.get("/cama/indicadores").get_json()
|
||||||
|
assert {"cama_tasa_deteccion_histopatologica", "cama_dias_resultado_diagnostico", ID} <= {i["id"] for i in catalogo}
|
||||||
|
historicos = ("cama_birads_456_paciente", "cama_birads_456_mastografia",
|
||||||
|
"cama_confirmacion_birads45", "cama_dias_toma_diagnostico", "cama_eu38a")
|
||||||
|
assert set(historicos) <= {i["id"] for i in catalogo}
|
||||||
|
for historico in historicos:
|
||||||
|
assert cliente.get(f"/cama/indicadores/{historico}/datos?periodos=2025-S1").status_code == 200
|
||||||
|
assert cliente.get(RAIZ + "/metadatos").status_code == 200
|
||||||
|
assert next(i for i in catalogo if i['id'] == ID)['titulo'] == 'Histopatología por BI-RADS'
|
||||||
|
assert matriz.get_json()['titulo'] == 'Histopatología por BI-RADS'
|
||||||
|
assert 'datos sintéticos' not in matriz.get_json()['notas'][0]
|
||||||
|
assert cliente.get(RAIZ + "/periodos").status_code == 200
|
||||||
|
assert cliente.get(RAIZ + "/datos?periodos=2025-02&estrato=birads").status_code == 200
|
||||||
|
figura = cliente.get(RAIZ + "/figuras/fig_c2_donas?periodos=2025-S1")
|
||||||
|
assert figura.status_code == 200
|
||||||
|
finally:
|
||||||
|
motor.dispose()
|
||||||
|
db.get_cama_engine.cache_clear()
|
||||||
|
return resultados
|
||||||
|
|
||||||
|
|
||||||
|
def test_cruce_completo_y_catalogos(publicaciones):
|
||||||
|
general, datos = publicaciones[0]
|
||||||
|
assert datos["contrato"] == general["contrato"] == "C2"
|
||||||
|
assert datos["estrato"] == "birads" and general["estrato"] is None
|
||||||
|
estratos = {"BIRADS_4", "BIRADS_4A", "BIRADS_4B", "BIRADS_4C", "BIRADS_5", "BIRADS_6"}
|
||||||
|
categorias = {"BENIGNO", "RIESGO_B3", "IN_SITU", "INVASOR", "SIN_DATO", "SIN_BIOPSIA"}
|
||||||
|
assert set(datos["valores_estrato"]) == estratos
|
||||||
|
assert {(f["estrato"], f["categoria"]) for f in datos["filas"]} == {(e, c) for e in estratos for c in categorias}
|
||||||
|
assert datos["categorias"]["BENIGNO"]["grupo"] == "NO_MALIGNO"
|
||||||
|
assert datos["categorias"]["RIESGO_B3"]["grupo"] == "NO_MALIGNO"
|
||||||
|
assert datos["categorias"]["IN_SITU"]["grupo"] == datos["categorias"]["INVASOR"]["grupo"] == "MALIGNO"
|
||||||
|
assert datos["categorias"]["SIN_DATO"]["grupo"] == "SIN_DATO"
|
||||||
|
assert datos["categorias"]["SIN_BIOPSIA"]["grupo"] is None
|
||||||
|
assert datos["grupos_de_categoria"]["MALIGNO"] == "Maligno"
|
||||||
|
celdas = {(f["estrato"], f["categoria"]): f for f in datos["filas"]}
|
||||||
|
assert celdas["BIRADS_4", "RIESGO_B3"]["n"] == 0 and celdas["BIRADS_4", "RIESGO_B3"]["suprimido"] == 0
|
||||||
|
assert celdas["BIRADS_4", "SIN_DATO"]["n"] == 1
|
||||||
|
for total in datos["totales_estrato"]:
|
||||||
|
assert total["n"] == sum(f["n"] for f in datos["filas"] if f["estrato"] == total["estrato"])
|
||||||
|
assert sum(f["n"] for f in general["filas"]) == sum(f["n"] for f in datos["filas"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_mismas_marginales_no_ocultan_celdas_distintas(publicaciones):
|
||||||
|
(g1, m1), (g2, m2) = publicaciones
|
||||||
|
assert {f["categoria"]: f["n"] for f in g1["filas"]} == {f["categoria"]: f["n"] for f in g2["filas"]}
|
||||||
|
assert {f["estrato"]: f["n"] for f in m1["totales_estrato"]} == {f["estrato"]: f["n"] for f in m2["totales_estrato"]}
|
||||||
|
assert {(f["estrato"], f["categoria"]): f["n"] for f in m1["filas"]} != {(f["estrato"], f["categoria"]): f["n"] for f in m2["filas"]}
|
||||||
|
|
||||||
|
|
||||||
|
def test_supresion_en_fixture_pequeno(tmp_path_factory):
|
||||||
|
for cliente in cliente_de("cama", tmp_path_factory):
|
||||||
|
datos = cliente.get(RAIZ + "/datos?periodos=2025-S1&estrato=birads").get_json()
|
||||||
|
assert datos["filas"] and all(f["suprimido"] == 1 and f["n"] is None for f in datos["filas"])
|
||||||
|
assert all(t["suprimido"] == 1 and t["n"] is None for t in datos["totales_estrato"])
|
||||||
|
assert "BIRADS_4" not in datos["valores_estrato"]
|
||||||
|
assert not any(f["estrato"] == "BIRADS_4" for f in datos["filas"])
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
"""Contrato HTTP de seguimiento CaMa, con datos exclusivamente inventados."""
|
||||||
|
import pytest
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
from webapi.seguimiento_cama import blueprint_seguimiento_cama
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client():
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix="/cama")
|
||||||
|
return app.test_client()
|
||||||
|
|
||||||
|
|
||||||
|
def get(client, query=""):
|
||||||
|
return client.get("/cama/seguimiento" + query)
|
||||||
|
|
||||||
|
|
||||||
|
def test_formato_y_metadatos(client):
|
||||||
|
response = get(client)
|
||||||
|
assert response.status_code == 200 and response.mimetype == "application/json"
|
||||||
|
data = response.get_json()
|
||||||
|
assert set(data) == {"simulado", "corte", "ventana", "campo_ventana", "filtros", "filtros_disponibles", "columnas", "paginacion", "items"}
|
||||||
|
assert data["simulado"] is True and data["corte"] == "2026-10-20"
|
||||||
|
assert data["ventana"] == {"meses": 3, "desde": "2026-07-21", "hasta": "2026-10-20"}
|
||||||
|
assert data["paginacion"] == {"page": 1, "page_size": 50, "total_items": 5, "total_pages": 1}
|
||||||
|
assert set(data["filtros"]) == {f["clave"] for f in data["filtros_disponibles"]}
|
||||||
|
assert all(f["opciones"] for f in data["filtros_disponibles"])
|
||||||
|
assert data["campo_ventana"] == "mastografia_fecha"
|
||||||
|
assert [c["clave"] for c in data["columnas"]] == ["id_seudonimo", "grupo_edad", "estatus", "birads", "biopsia", "dias_mastografia_diagnostico", "prioridad"]
|
||||||
|
for f in data["filtros_disponibles"]:
|
||||||
|
opciones = {o["codigo"]: o["etiqueta"] for o in f["opciones"]}
|
||||||
|
assert all(opciones[i[f["clave"] + "_codigo"]] == i[f["clave"]] for i in data["items"])
|
||||||
|
assert all(isinstance(v, (str, int, float)) or v is None for i in data["items"] for v in i.values())
|
||||||
|
assert len({i["id_seudonimo"] for i in data["items"]}) == 5
|
||||||
|
assert "pac_id" not in response.get_data(as_text=True)
|
||||||
|
for columna in data["columnas"]:
|
||||||
|
assert all(columna["clave"] in item and all(d["clave"] in item for d in columna.get("detalles", [])) for item in data["items"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_ruta_registrada_en_aplicacion():
|
||||||
|
from webapi import create_app
|
||||||
|
|
||||||
|
response = create_app().test_client().get("/cama/seguimiento")
|
||||||
|
assert response.status_code == 200 and response.get_json()["simulado"] is True
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("clave,codigo,valor", [
|
||||||
|
("estatus", "PENDIENTE_BIOPSIA", "Pendiente de biopsia"), ("birads", "BIRADS_5", "BI-RADS 5"),
|
||||||
|
("grupo_edad", "40-49", "40-49"), ("prioridad", "ALTA", "Alta"),
|
||||||
|
])
|
||||||
|
def test_filtros(client, clave, codigo, valor):
|
||||||
|
data = get(client, f"?meses=12&{clave}={codigo}").get_json()
|
||||||
|
assert data["filtros"][clave] == codigo and data["items"]
|
||||||
|
assert all(item[clave] == valor for item in data["items"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_combinacion_paginacion_y_orden(client):
|
||||||
|
query = "?meses=12&prioridad=ALTA&page_size=1"
|
||||||
|
paginas = [get(client, query + f"&page={n}").get_json() for n in (1, 2, 3)]
|
||||||
|
assert all(p["paginacion"]["total_items"] == 3 and p["paginacion"]["total_pages"] == 3 for p in paginas)
|
||||||
|
assert [p["items"][0]["id_seudonimo"] for p in paginas] == ["M-0001", "M-0004", "M-0007"]
|
||||||
|
fuera = get(client, query + "&page=4")
|
||||||
|
assert fuera.status_code == 200 and fuera.get_json()["items"] == []
|
||||||
|
assert fuera.get_json()["paginacion"]["total_pages"] == 3
|
||||||
|
ids = [i["id_seudonimo"] for i in get(client).get_json()["items"]]
|
||||||
|
assert ids[:2] == ["M-0001", "M-0002"]
|
||||||
|
assert ids == [i["id_seudonimo"] for i in get(client).get_json()["items"]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_ventanas_y_fronteras(client):
|
||||||
|
assert get(client, "?corte=2026-10-20&meses=1").get_json()["ventana"]["desde"] == "2026-09-21"
|
||||||
|
assert get(client, "?corte=2026-10-20&meses=6").get_json()["paginacion"]["total_items"] == 6
|
||||||
|
assert get(client, "?corte=2026-10-20&meses=12").get_json()["paginacion"]["total_items"] == 8
|
||||||
|
assert [i["id_seudonimo"] for i in get(client, "?corte=2026-07-21&meses=1").get_json()["items"]] == ["M-0005"]
|
||||||
|
assert get(client, "?corte=2024-03-31&meses=1").get_json()["ventana"]["desde"] == "2024-03-01"
|
||||||
|
|
||||||
|
|
||||||
|
def test_vacio_y_pagina_vacia(client):
|
||||||
|
for query in ("?corte=2020-01-01&page=5", "?estatus=BENIGNO&birads=BIRADS_5"):
|
||||||
|
response = get(client, query)
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.get_json()["items"] == []
|
||||||
|
assert response.get_json()["paginacion"]["total_pages"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("query", ["?corte=ayer", "?corte=2026-02-30", "?corte=0001-01-01", "?meses=2", "?meses=x", "?page=0", "?page=-1", "?page_size=0", "?page_size=201", "?estatus=X", "?birads=X", "?grupo_edad=X", "?prioridad=X"])
|
||||||
|
def test_parametros_invalidos(client, query):
|
||||||
|
response = get(client, query)
|
||||||
|
assert response.status_code == 400 and isinstance(response.get_json()["error"], str)
|
||||||
|
|
||||||
|
|
||||||
|
def test_error_de_fuente_es_json(client, monkeypatch):
|
||||||
|
def fallar(corte, desde):
|
||||||
|
raise RuntimeError("detalle interno")
|
||||||
|
monkeypatch.setattr("webapi.seguimiento_cama.leer_fixture", fallar)
|
||||||
|
response = get(client)
|
||||||
|
assert response.status_code == 500 and response.is_json
|
||||||
|
assert "detalle interno" not in response.get_data(as_text=True)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("query", ["?meses=12", "?meses=6&estatus=BENIGNO", "?meses=12&birads=BIRADS_5", "?meses=12&grupo_edad=40-49", "?meses=12&prioridad=ALTA", "?meses=12&prioridad=ALTA&birads=BIRADS_5", "?corte=2026-07-21&meses=1", "?estatus=BENIGNO&birads=BIRADS_5"])
|
||||||
|
def test_exportacion_coincide_con_paginas(client, query):
|
||||||
|
response = client.get('/cama/seguimiento/exportacion' + query + '&page=2&page_size=1')
|
||||||
|
assert response.status_code == 200 and response.headers['Cache-Control'] == 'no-store'
|
||||||
|
data = response.get_json()
|
||||||
|
primera = get(client, query + '&page=1&page_size=1').get_json()
|
||||||
|
items = []
|
||||||
|
for page in range(1, primera['paginacion']['total_pages'] + 1):
|
||||||
|
items.extend(get(client, query + f'&page={page}&page_size=1').get_json()['items'])
|
||||||
|
assert data['items'] == items
|
||||||
|
assert data['total_items'] == len(items) == primera['paginacion']['total_items']
|
||||||
|
for key in ('simulado', 'corte', 'ventana', 'campo_ventana', 'filtros', 'filtros_disponibles', 'columnas'):
|
||||||
|
assert data[key] == primera[key]
|
||||||
|
assert data['simulado'] is True
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('query', ['?corte=ayer', '?corte=0001-01-01', '?meses=2', '?meses=x', '?estatus=X', '?birads=X', '?grupo_edad=X', '?prioridad=X'])
|
||||||
|
def test_exportacion_parametros_invalidos(client, query):
|
||||||
|
response = client.get('/cama/seguimiento/exportacion' + query)
|
||||||
|
assert response.status_code == 400 and response.headers['Cache-Control'] == 'no-store'
|
||||||
|
|
||||||
|
|
||||||
|
def test_exportacion_limite_y_error(client, monkeypatch):
|
||||||
|
import webapi.seguimiento_cama as modulo
|
||||||
|
original = modulo.leer_fixture
|
||||||
|
fila = original(None, None)[0]
|
||||||
|
monkeypatch.setattr(modulo, 'leer_fixture', lambda corte, desde: [fila] * 5000)
|
||||||
|
assert client.get('/cama/seguimiento/exportacion').get_json()['total_items'] == 5000
|
||||||
|
monkeypatch.setattr(modulo, 'leer_fixture', lambda corte, desde: [fila] * 5001)
|
||||||
|
response = client.get('/cama/seguimiento/exportacion')
|
||||||
|
assert response.status_code == 413 and 'items' not in response.get_json()
|
||||||
|
def fallar(corte, desde):
|
||||||
|
raise RuntimeError('secreto interno')
|
||||||
|
monkeypatch.setattr(modulo, 'leer_fixture', fallar)
|
||||||
|
response = client.get('/cama/seguimiento/exportacion')
|
||||||
|
assert response.status_code == 500 and 'secreto interno' not in response.get_data(as_text=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_detalle_misma_fila_y_ausencias(client):
|
||||||
|
lista = get(client, '?meses=12').get_json()
|
||||||
|
response = client.get('/cama/pacientes/M-0001?meses=12')
|
||||||
|
data = response.get_json()
|
||||||
|
assert response.status_code == 200 and response.headers['Cache-Control'] == 'no-store'
|
||||||
|
assert data['simulado'] is True and data['ventana'] == lista['ventana']
|
||||||
|
assert data['item'] == lista['items'][0]
|
||||||
|
assert data['item']['biopsia'] is None and data['item']['biopsia_fecha'] is None
|
||||||
|
assert set(data) == {'simulado', 'corte', 'ventana', 'item'}
|
||||||
|
assert set(data['item']) == set(lista['items'][0])
|
||||||
|
assert client.get('/cama/pacientes/M-0008').status_code == 404
|
||||||
|
assert client.get('/cama/pacientes/M-0008?meses=12').status_code == 200
|
||||||
|
assert client.get('/cama/pacientes/M-9999?meses=12').status_code == 404
|
||||||
|
assert client.get('/cama/pacientes/M-0001?meses=2').status_code == 400
|
||||||
@@ -13,6 +13,8 @@ from webapi.blueprints.imports import imports_bp
|
|||||||
from webapi.blueprints.reportes import reportes_bp
|
from webapi.blueprints.reportes import reportes_bp
|
||||||
from webapi.blueprints.tea import tea_bp
|
from webapi.blueprints.tea import tea_bp
|
||||||
from webapi.seguimiento import blueprint_de_seguimiento
|
from webapi.seguimiento import blueprint_de_seguimiento
|
||||||
|
from webapi.seguimiento_cama import blueprint_seguimiento_cama
|
||||||
|
from webapi.cama_analysis import analysis as cama_analysis
|
||||||
|
|
||||||
|
|
||||||
class IsoJSONProvider(DefaultJSONProvider):
|
class IsoJSONProvider(DefaultJSONProvider):
|
||||||
@@ -72,6 +74,8 @@ def create_app() -> Flask:
|
|||||||
|
|
||||||
app.register_blueprint(cacu_bp, url_prefix="/cacu")
|
app.register_blueprint(cacu_bp, url_prefix="/cacu")
|
||||||
app.register_blueprint(cama_bp, url_prefix="/cama")
|
app.register_blueprint(cama_bp, url_prefix="/cama")
|
||||||
|
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix="/cama")
|
||||||
|
app.register_blueprint(cama_analysis, url_prefix="/cama")
|
||||||
app.register_blueprint(tea_bp, url_prefix="/tea")
|
app.register_blueprint(tea_bp, url_prefix="/tea")
|
||||||
app.register_blueprint(imports_bp, url_prefix="/imports")
|
app.register_blueprint(imports_bp, url_prefix="/imports")
|
||||||
app.register_blueprint(data_bp, url_prefix="/data")
|
app.register_blueprint(data_bp, url_prefix="/data")
|
||||||
|
|||||||
@@ -4,9 +4,11 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
|
|
||||||
from flask import Blueprint, Response, jsonify, request
|
from flask import Blueprint, Response, jsonify, request
|
||||||
|
from sqlalchemy.exc import SQLAlchemyError
|
||||||
|
|
||||||
from extraction import BBox, ExtractionError
|
from extraction import BBox, ExtractionError
|
||||||
from extraction.readers import reader_for
|
from extraction.readers import reader_for
|
||||||
|
from indicadores_kit.registry.catalogos import CatalogoInvalido
|
||||||
from webapi.imports import audit as import_audit
|
from webapi.imports import audit as import_audit
|
||||||
from webapi.imports.connectors import ConnectorError, build_connector, catalog, connector_class, kind_for_filename
|
from webapi.imports.connectors import ConnectorError, build_connector, catalog, connector_class, kind_for_filename
|
||||||
from webapi.imports.connectors.base import decode_file
|
from webapi.imports.connectors.base import decode_file
|
||||||
@@ -14,6 +16,7 @@ from webapi.imports.connectors.pdf import PdfConnector
|
|||||||
from webapi.imports.connectors.sql import SqlConnector
|
from webapi.imports.connectors.sql import SqlConnector
|
||||||
from webapi.imports.connectors.tabular import FileConnector
|
from webapi.imports.connectors.tabular import FileConnector
|
||||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||||
|
from webapi.imports.services.catalog_commit_service import commit_discovered_fields
|
||||||
from webapi.imports.services.import_service import (
|
from webapi.imports.services.import_service import (
|
||||||
DatabaseRefused,
|
DatabaseRefused,
|
||||||
ImportRequestError,
|
ImportRequestError,
|
||||||
@@ -251,11 +254,13 @@ def document_extract():
|
|||||||
"""Reads the documents, splits them into patient records and extracts
|
"""Reads the documents, splits them into patient records and extracts
|
||||||
the target's fields: `{files: [{name, file_base64}], target,
|
the target's fields: `{files: [{name, file_base64}], target,
|
||||||
segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?}`.
|
segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?}`.
|
||||||
|
`files` may be `sql` instead: `{connection details, table|query, column,
|
||||||
|
key_column}`, one document per row (a PDF or plain-text column).
|
||||||
Each record comes back with per-field confidence and evidence, conflicts
|
Each record comes back with per-field confidence and evidence, conflicts
|
||||||
between sources, and the images found on its pages."""
|
between sources, and the images found on its pages."""
|
||||||
body = _json_body()
|
body = _json_body()
|
||||||
_require(body, "target")
|
_require(body, "target")
|
||||||
if not body.get("files"):
|
if not body.get("files") and not body.get("sql"):
|
||||||
raise BadRequest("faltan los archivos")
|
raise BadRequest("faltan los archivos")
|
||||||
return jsonify(document_report(body))
|
return jsonify(document_report(body))
|
||||||
|
|
||||||
@@ -302,6 +307,41 @@ def validate():
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
|
||||||
|
"""For every `document` source in the request (uploaded, or reading a
|
||||||
|
SQL column — same connector either way), writes the captions no known
|
||||||
|
field claimed straight into the silver layer (`catalog_commit_service`),
|
||||||
|
matched or minted against the project's catalog. Best-effort: the
|
||||||
|
structured fields already landed through `commit_sources`, so a failure
|
||||||
|
here is reported, not raised."""
|
||||||
|
reports = []
|
||||||
|
for raw in raw_sources:
|
||||||
|
if not isinstance(raw, dict) or raw.get("source_type") != "document":
|
||||||
|
continue
|
||||||
|
target = raw.get("target") or ""
|
||||||
|
domain = target.split(".", 1)[0]
|
||||||
|
if not domain:
|
||||||
|
continue
|
||||||
|
payload = {**(raw.get("payload") or {}), "target": target}
|
||||||
|
try:
|
||||||
|
connector = build_connector("document", payload)
|
||||||
|
result = commit_discovered_fields(connector.records, proyecto=domain, estudio_id=payload.get("estudio_id"))
|
||||||
|
except (ConnectorError, ExtractionError, CatalogoInvalido, SQLAlchemyError) as exc:
|
||||||
|
log.warning("catalog_fallback: %s no se pudo procesar: %s", raw.get("label") or target, exc)
|
||||||
|
continue
|
||||||
|
reports.append(
|
||||||
|
{
|
||||||
|
"label": raw.get("label"),
|
||||||
|
"domain": result.proyecto,
|
||||||
|
"records_written": result.records_written,
|
||||||
|
"records_without_patient": result.records_without_patient,
|
||||||
|
"fields_matched": result.fields_matched,
|
||||||
|
"fields_minted": result.fields_minted,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return reports
|
||||||
|
|
||||||
|
|
||||||
@imports_bp.post("/commit")
|
@imports_bp.post("/commit")
|
||||||
def commit():
|
def commit():
|
||||||
"""`{sources: [...], on_conflict: "reject"|"upsert", merge_duplicates: bool}`.
|
"""`{sources: [...], on_conflict: "reject"|"upsert", merge_duplicates: bool}`.
|
||||||
@@ -333,6 +373,7 @@ def commit():
|
|||||||
"ok": all(r.rejected == 0 for r in results),
|
"ok": all(r.rejected == 0 for r in results),
|
||||||
"audit_id": audit.id,
|
"audit_id": audit.id,
|
||||||
"indicadores_en_recalculo": recalculating,
|
"indicadores_en_recalculo": recalculating,
|
||||||
|
"catalog_fallback": _commit_catalog_fallback(body.get("sources") or []),
|
||||||
"results": [
|
"results": [
|
||||||
{
|
{
|
||||||
"target": r.target,
|
"target": r.target,
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
"""Aggregate and select the breast cohort through the same configured reader."""
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
|
||||||
|
from flask import Blueprint, current_app, jsonify, request
|
||||||
|
|
||||||
|
from webapi.cama_cohort import COHORT, SCENARIO, THRESHOLD
|
||||||
|
|
||||||
|
analysis = Blueprint('cama_analysis', __name__)
|
||||||
|
BIRADS = ('BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6')
|
||||||
|
AGES = ('MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO')
|
||||||
|
|
||||||
|
|
||||||
|
class SelectionError(Exception):
|
||||||
|
def __init__(self, message, status=400):
|
||||||
|
self.message, self.status = message, status
|
||||||
|
|
||||||
|
|
||||||
|
def read_cohort(cutoff):
|
||||||
|
reader = current_app.config.get('CAMA_COHORT_READER')
|
||||||
|
if current_app.config.get('CAMA_COHORT_SYNTHETIC') is not True or not callable(reader):
|
||||||
|
raise SelectionError('Cohorte no disponible', 503)
|
||||||
|
return reader(cutoff)
|
||||||
|
|
||||||
|
|
||||||
|
def cutoff_arg(args):
|
||||||
|
text = args.get('corte')
|
||||||
|
if not text:
|
||||||
|
raise SelectionError('Se requiere corte')
|
||||||
|
try:
|
||||||
|
value = date.fromisoformat(text)
|
||||||
|
if value.isoformat() != text or value.year == 9999:
|
||||||
|
raise ValueError()
|
||||||
|
return value
|
||||||
|
except ValueError:
|
||||||
|
raise SelectionError('Corte inválido') from None
|
||||||
|
|
||||||
|
|
||||||
|
def patient_access():
|
||||||
|
check = current_app.config.get('CAMA_COHORT_ACCESS')
|
||||||
|
if not callable(check) or not check(request):
|
||||||
|
raise SelectionError('Acceso no autorizado', 403)
|
||||||
|
|
||||||
|
|
||||||
|
def revision_of(rows):
|
||||||
|
"""Identify the materialized cohort without exposing its patient identifiers."""
|
||||||
|
encoded = json.dumps(rows, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode()
|
||||||
|
return hashlib.sha256(encoded).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def cohort_request(args):
|
||||||
|
allowed = {'cohorte', 'revision', 'escenario', 'corte', 'meses', 'page', 'page_size', 'birads', 'grupo_edad'}
|
||||||
|
if set(args) - allowed or any(len(args.getlist(k)) != 1 for k in args):
|
||||||
|
raise SelectionError('Parámetros desconocidos o repetidos')
|
||||||
|
if args.get('cohorte') != COHORT or args.get('escenario') != SCENARIO:
|
||||||
|
raise SelectionError('Cohorte o escenario desconocido')
|
||||||
|
revision = args.get('revision', '')
|
||||||
|
if len(revision) != 64 or any(c not in '0123456789abcdef' for c in revision):
|
||||||
|
raise SelectionError('Revisión de cohorte inválida')
|
||||||
|
cutoff = cutoff_arg(args)
|
||||||
|
try:
|
||||||
|
months = int(args.get('meses', '3'))
|
||||||
|
page = int(args.get('page', '1'))
|
||||||
|
size = int(args.get('page_size', '50'))
|
||||||
|
if months not in (0, 1, 3, 6, 12) or page < 1 or not 1 <= size <= 200:
|
||||||
|
raise ValueError()
|
||||||
|
except ValueError:
|
||||||
|
raise SelectionError('Ventana o paginación inválida') from None
|
||||||
|
filters = {key: args.get(key) for key in ('birads', 'grupo_edad')}
|
||||||
|
if filters['birads'] not in (None, *BIRADS) or filters['grupo_edad'] not in (None, *AGES):
|
||||||
|
raise SelectionError('Filtro inválido')
|
||||||
|
return cutoff, months, page, size, filters, revision
|
||||||
|
|
||||||
|
|
||||||
|
def selected(args):
|
||||||
|
patient_access()
|
||||||
|
cutoff, months, page, size, filters, revision = cohort_request(args)
|
||||||
|
rows = read_cohort(cutoff)
|
||||||
|
if not hmac.compare_digest(revision, revision_of(rows)):
|
||||||
|
raise SelectionError('La cohorte cambió; actualiza el análisis', 409)
|
||||||
|
selected_rows = [row for row in rows if all(v is None or row[k] == v for k, v in filters.items())]
|
||||||
|
if months:
|
||||||
|
from webapi.seguimiento_cama import _desde
|
||||||
|
since = _desde(cutoff, months)
|
||||||
|
else:
|
||||||
|
since = min((date.fromisoformat(r['mastografia_fecha']) for r in rows), default=cutoff)
|
||||||
|
selected_rows = [r for r in selected_rows if since <= date.fromisoformat(r['mastografia_fecha']) <= cutoff]
|
||||||
|
# Every filtered selection is checked on the server after applying the window.
|
||||||
|
if len(selected_rows) < THRESHOLD and (selected_rows or any(filters.values())):
|
||||||
|
raise SelectionError('Selección no disponible', 403)
|
||||||
|
return cutoff, months, page, size, filters, since, selected_rows, revision
|
||||||
|
|
||||||
|
|
||||||
|
def selection_response(args, mode, patient=None):
|
||||||
|
cutoff, months, page, size, filters, since, rows, revision = selected(args)
|
||||||
|
options = [('birads', 'Categoría BI-RADS', BIRADS), ('grupo_edad', 'Grupo de edad', AGES)]
|
||||||
|
columns = [
|
||||||
|
{'clave': 'id_seudonimo', 'etiqueta': 'Identificador seudónimo'},
|
||||||
|
{'clave': 'grupo_edad', 'etiqueta': 'Grupo de edad'},
|
||||||
|
{'clave': 'birads', 'etiqueta': 'Última mastografía', 'detalles': [{'clave': 'mastografia_fecha', 'etiqueta': 'Fecha'}]},
|
||||||
|
{'clave': 'biopsia', 'etiqueta': 'Resultado histopatológico', 'detalles': [{'clave': 'biopsia_fecha', 'etiqueta': 'Fecha de reporte'}]},
|
||||||
|
]
|
||||||
|
meta = {'simulado': True, 'cohorte': COHORT, 'revision': revision, 'escenario': SCENARIO, 'corte': cutoff.isoformat(),
|
||||||
|
'ventana': {'meses': months, 'desde': since.isoformat(), 'hasta': cutoff.isoformat()},
|
||||||
|
'campo_ventana': 'mastografia_fecha', 'filtros': filters,
|
||||||
|
'filtros_disponibles': [{'clave': k, 'etiqueta': label, 'opciones': [{'codigo': v, 'etiqueta': v} for v in values]}
|
||||||
|
for k, label, values in options], 'columnas': columns}
|
||||||
|
if mode == 'patient':
|
||||||
|
found = next((row for row in rows if row['id_seudonimo'] == patient), None)
|
||||||
|
if found is None:
|
||||||
|
raise SelectionError('Paciente no encontrado', 404)
|
||||||
|
return jsonify(**meta, item=found)
|
||||||
|
if mode == 'export':
|
||||||
|
if len(rows) > 5000:
|
||||||
|
raise SelectionError('La exportación supera el límite de 5000 registros', 413)
|
||||||
|
return jsonify(**meta, total_items=len(rows), items=rows)
|
||||||
|
return jsonify(**meta, paginacion={'page': page, 'page_size': size, 'total_items': len(rows),
|
||||||
|
'total_pages': (len(rows) + size - 1) // size},
|
||||||
|
items=rows[(page - 1) * size:page * size])
|
||||||
|
|
||||||
|
|
||||||
|
@analysis.get('/analisis/indicadores')
|
||||||
|
def indicators():
|
||||||
|
try:
|
||||||
|
if set(request.args) != {'corte'} or len(request.args.getlist('corte')) != 1:
|
||||||
|
raise SelectionError('Se requiere únicamente corte')
|
||||||
|
cutoff = cutoff_arg(request.args)
|
||||||
|
rows = read_cohort(cutoff)
|
||||||
|
groups = []
|
||||||
|
for code in BIRADS:
|
||||||
|
count = sum(r['birads'] == code for r in rows)
|
||||||
|
groups.append({'codigo': code, 'n': count if count >= THRESHOLD else None, 'suprimido': count < THRESHOLD})
|
||||||
|
return jsonify(simulado=True, cohorte=COHORT, revision=revision_of(rows), escenario=SCENARIO, corte=cutoff.isoformat(),
|
||||||
|
horizonte_dias=0, umbral_supresion=THRESHOLD, unidad='paciente',
|
||||||
|
denominador='pacientes elegibles con última mastografía reportada BI-RADS 4 a 6',
|
||||||
|
indicadores=[], grupos=groups)
|
||||||
|
except SelectionError as e:
|
||||||
|
return jsonify(error=e.message), e.status
|
||||||
|
|
||||||
|
|
||||||
|
@analysis.after_request
|
||||||
|
def no_cache(response):
|
||||||
|
response.headers['Cache-Control'] = 'no-store'
|
||||||
|
return response
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
"""Read the breast screening cohort from the existing silver tables.
|
||||||
|
|
||||||
|
The current silver tables keep only the last version of each fact. Filtering by
|
||||||
|
load date prevents future facts from appearing at an earlier cutoff, but cannot
|
||||||
|
restore a previous value after an update.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import date, datetime, time, timedelta, timezone
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from indicadores_kit.cama.consultas.plata import biopsias, mastografias
|
||||||
|
from indicadores_kit.cama.familias.histopatologia_birads.consulta import BIRADS
|
||||||
|
from indicadores_kit.cama.tablas import TABLAS
|
||||||
|
|
||||||
|
|
||||||
|
COHORT = "cama_birads_v1"
|
||||||
|
SCENARIO = "diagnostico"
|
||||||
|
THRESHOLD = 5
|
||||||
|
|
||||||
|
|
||||||
|
def _date(value):
|
||||||
|
return date.fromisoformat(value) if isinstance(value, str) else value
|
||||||
|
|
||||||
|
|
||||||
|
def _known(value, cutoff):
|
||||||
|
if value is None:
|
||||||
|
return False
|
||||||
|
if isinstance(value, str):
|
||||||
|
value = datetime.fromisoformat(value)
|
||||||
|
if value.tzinfo is None:
|
||||||
|
value = value.replace(tzinfo=timezone.utc)
|
||||||
|
return value < datetime.combine(cutoff + timedelta(days=1), time.min, timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def _age_group(birth, cutoff):
|
||||||
|
if birth is None or birth > cutoff:
|
||||||
|
return "SIN_DATO"
|
||||||
|
age = cutoff.year - birth.year - ((cutoff.month, cutoff.day) < (birth.month, birth.day))
|
||||||
|
if age < 40:
|
||||||
|
return "MENOR_40"
|
||||||
|
if age >= 70:
|
||||||
|
return "70+"
|
||||||
|
return f"{age // 10 * 10}-{age // 10 * 10 + 9}"
|
||||||
|
|
||||||
|
|
||||||
|
class CamaCohort:
|
||||||
|
"""Materialize one row per eligible patient, using a caller-owned session."""
|
||||||
|
|
||||||
|
def __init__(self, session, secret: bytes):
|
||||||
|
if not secret or len(secret) < 32:
|
||||||
|
raise ValueError("A stable secret of at least 32 bytes is required")
|
||||||
|
self.session = session
|
||||||
|
self.secret = secret
|
||||||
|
|
||||||
|
def _id(self, patient):
|
||||||
|
return hmac.new(self.secret, f"cama:{patient}".encode(), hashlib.sha256).hexdigest()
|
||||||
|
|
||||||
|
def rows(self, cutoff: date):
|
||||||
|
t = TABLAS
|
||||||
|
loads = {x.carga_id: x.inicio for x in self.session.execute(select(t.Carga)).scalars()}
|
||||||
|
procedures = {x.procedimiento_id: x for x in self.session.execute(select(t.Procedimiento)).scalars()}
|
||||||
|
observations = {(x.procedimiento_id, x.resultado_id): x for x in self.session.execute(select(t.Observacion)).scalars()}
|
||||||
|
people = {x.pac_id: x for x in self.session.execute(select(t.Persona)).scalars()}
|
||||||
|
|
||||||
|
def procedure_known(identifier):
|
||||||
|
p = procedures.get(identifier)
|
||||||
|
return bool(p and _known(loads.get(p.carga_id), cutoff))
|
||||||
|
|
||||||
|
def observation_known(identifier, result):
|
||||||
|
o = observations.get((identifier, result))
|
||||||
|
return bool(o and _known(loads.get(o.carga_id), cutoff))
|
||||||
|
|
||||||
|
def load_time(record):
|
||||||
|
value = loads.get(record.carga_id) if record else None
|
||||||
|
return value.isoformat() if value else None
|
||||||
|
|
||||||
|
candidates = {}
|
||||||
|
for row in self.session.execute(select(mastografias(t))).mappings():
|
||||||
|
taken, reported = _date(row['fecha_toma']), _date(row['fecha_reporte'])
|
||||||
|
if not (taken and reported and taken <= reported <= cutoff and row['birads']
|
||||||
|
and procedure_known(row['procedimiento_id']) and procedure_known(row['reporte_id'])
|
||||||
|
and observation_known(row['reporte_id'], 'mastografia.birads')):
|
||||||
|
continue
|
||||||
|
key = (taken, str(row['fuente_id']), reported, row['reporte_id'])
|
||||||
|
prior = candidates.get(row['pac_id'])
|
||||||
|
if prior is None or key > prior[0]:
|
||||||
|
candidates[row['pac_id']] = (key, row)
|
||||||
|
|
||||||
|
reports = {}
|
||||||
|
orders = {}
|
||||||
|
for p in procedures.values():
|
||||||
|
when = _date(p.fecha)
|
||||||
|
if (p.estudio_id != 'biopsia' or p.clase != 'orden' or not p.padre_id or not when
|
||||||
|
or when > cutoff or not procedure_known(p.procedimiento_id)):
|
||||||
|
continue
|
||||||
|
key = (p.pac_id, p.padre_id)
|
||||||
|
rank = (when, str(p.fuente_id), p.procedimiento_id)
|
||||||
|
if key not in orders or rank > orders[key][0]:
|
||||||
|
orders[key] = (rank, p)
|
||||||
|
for row in self.session.execute(select(biopsias(t))).mappings():
|
||||||
|
reported, ordered = _date(row['fecha_reporte']), _date(row['fecha_solicitud'])
|
||||||
|
procedure = procedures.get(row['procedimiento_id'])
|
||||||
|
order = procedures.get(procedure.padre_id) if procedure else None
|
||||||
|
if not (reported and ordered and ordered <= reported <= cutoff and row['toma_id']
|
||||||
|
and row['pac_id'] == row['toma_pac_id'] and procedure_known(row['procedimiento_id'])
|
||||||
|
and order and procedure_known(order.procedimiento_id)):
|
||||||
|
continue
|
||||||
|
key = (row['pac_id'], row['toma_id'])
|
||||||
|
rank = (reported, str(row['fuente_id']), row['procedimiento_id'])
|
||||||
|
if key not in reports or rank > reports[key][0]:
|
||||||
|
reports[key] = (rank, row)
|
||||||
|
|
||||||
|
rows = []
|
||||||
|
for patient, (_, m) in candidates.items():
|
||||||
|
code = BIRADS.get(m['birads'])
|
||||||
|
if not code or patient not in people:
|
||||||
|
continue
|
||||||
|
b = reports.get((patient, m['procedimiento_id']))
|
||||||
|
b = b[1] if b and _date(b[1]['fecha_reporte']) >= _date(m['fecha_toma']) else None
|
||||||
|
order = procedures[procedures[b['procedimiento_id']].padre_id] if b else None
|
||||||
|
if not order:
|
||||||
|
found_order = orders.get((patient, m['procedimiento_id']))
|
||||||
|
order = found_order[1] if found_order and _date(found_order[1].fecha) >= _date(m['fecha_toma']) else None
|
||||||
|
grade = b['grado'] if b and observation_known(b['procedimiento_id'], 'biopsia.grado') else None
|
||||||
|
rows.append({
|
||||||
|
'id_seudonimo': self._id(patient), 'mastografia_fecha': _date(m['fecha_toma']).isoformat(),
|
||||||
|
'mastografia_reporte_fecha': _date(m['fecha_reporte']).isoformat(),
|
||||||
|
'birads': code, 'grupo_edad': _age_group(people[patient].fecha_nacimiento, cutoff),
|
||||||
|
'biopsia': grade, 'biopsia_fecha': _date(b['fecha_reporte']).isoformat() if b else None,
|
||||||
|
'biopsia_solicitud_fecha': _date(order.fecha).isoformat() if order else None,
|
||||||
|
'toma_carga_inicio': load_time(procedures[m['procedimiento_id']]),
|
||||||
|
'mastografia_reporte_carga_inicio': load_time(procedures[m['reporte_id']]),
|
||||||
|
'birads_carga_inicio': load_time(observations.get((m['reporte_id'], 'mastografia.birads'))),
|
||||||
|
'biopsia_solicitud_carga_inicio': load_time(order),
|
||||||
|
'biopsia_reporte_carga_inicio': load_time(procedures[b['procedimiento_id']]) if b else None,
|
||||||
|
'biopsia_resultado_carga_inicio': load_time(observations.get((b['procedimiento_id'], 'biopsia.grado')))
|
||||||
|
if b and observation_known(b['procedimiento_id'], 'biopsia.grado') else None,
|
||||||
|
})
|
||||||
|
return sorted(rows, key=lambda row: (-date.fromisoformat(row['mastografia_fecha']).toordinal(), row['id_seudonimo']))
|
||||||
@@ -12,6 +12,7 @@ from extraction.segmentation import SEGMENTERS
|
|||||||
from webapi.imports.connectors.base import decode_file
|
from webapi.imports.connectors.base import decode_file
|
||||||
from webapi.imports.connectors.errors import ConnectorError
|
from webapi.imports.connectors.errors import ConnectorError
|
||||||
from webapi.imports.connectors.registry import register_connector
|
from webapi.imports.connectors.registry import register_connector
|
||||||
|
from webapi.imports.connectors.sql import SqlConnector
|
||||||
from webapi.imports.connectors.tabular import DataFrameConnector
|
from webapi.imports.connectors.tabular import DataFrameConnector
|
||||||
from webapi.imports.schemas.field_specs import field_specs_for, key_field_for
|
from webapi.imports.schemas.field_specs import field_specs_for, key_field_for
|
||||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||||
@@ -48,16 +49,49 @@ class _ResultCache:
|
|||||||
_CACHE = _ResultCache()
|
_CACHE = _ResultCache()
|
||||||
|
|
||||||
|
|
||||||
|
def _files_from_sql(sql: dict[str, Any]) -> list[tuple[str, bytes]]:
|
||||||
|
"""One `(name, bytes)` per row of a SQL source (connected the same way
|
||||||
|
`SqlConnector` is): `column` is the field bundle (a `varbinary(max)`
|
||||||
|
PDF, or already a plain string — `read_document` reads either), and
|
||||||
|
`key_column` names the row (a patient or study id) for tracing. Any
|
||||||
|
column type `SqlConnector` can read works; it's not limited to PDFs."""
|
||||||
|
column = sql.get("column")
|
||||||
|
if not column:
|
||||||
|
raise ConnectorError("falta column")
|
||||||
|
if not sql.get("query") and not sql.get("table"):
|
||||||
|
raise ConnectorError("falta table o query")
|
||||||
|
key_column = sql.get("key_column") or column
|
||||||
|
if key_column == column:
|
||||||
|
raise ConnectorError("key_column debe ser distinta de column")
|
||||||
|
connector = SqlConnector.connect(sql)
|
||||||
|
connector = (
|
||||||
|
connector.select_query(sql["query"]) if sql.get("query") else connector.select_table(sql["table"], schema=sql.get("schema"))
|
||||||
|
)
|
||||||
|
files = []
|
||||||
|
for row in connector.read_rows({column: "contenido", key_column: "clave"}):
|
||||||
|
raw = row.get("contenido")
|
||||||
|
if raw is None:
|
||||||
|
continue
|
||||||
|
name = str(row.get("clave", len(files) + 1))
|
||||||
|
files.append((name, raw if isinstance(raw, bytes) else str(raw).encode("utf-8")))
|
||||||
|
return files
|
||||||
|
|
||||||
|
|
||||||
@register_connector
|
@register_connector
|
||||||
class DocumentConnector(DataFrameConnector):
|
class DocumentConnector(DataFrameConnector):
|
||||||
"""Clinical documents that are not tables: one report per patient,
|
"""Clinical documents that are not tables: one report per patient,
|
||||||
several pages per patient, many patients per file, scans, free text.
|
several pages per patient, many patients per file, scans, free text —
|
||||||
|
uploaded directly, or read one row at a time from a SQL source whose
|
||||||
|
`payload` carries `sql` (a connection plus `table`/`query`, `column`
|
||||||
|
and `key_column`) instead of `files`; either way, every row's content
|
||||||
|
reaches the same extraction, PDF, image or plain text alike.
|
||||||
|
|
||||||
Every file is read page by page (text layer or OCR), split into
|
Every file is read page by page (text layer or OCR; plain text as its
|
||||||
per-patient records, and the target entity's fields are extracted from
|
own lines), split into per-patient records, and the target entity's
|
||||||
labels and narrative text. Records of the same patient found in other
|
fields are extracted from labels and narrative text. Records of the
|
||||||
pages or files are merged. Each row also carries the record's pages as
|
same patient found in other pages or files — or rows — are merged.
|
||||||
a PDF (`documento`), mappable to the entity's file column.
|
Each row also carries the record's pages as a PDF (`documento`),
|
||||||
|
mappable to the entity's file column, when the source produced one.
|
||||||
|
|
||||||
Corrections made while reviewing travel in `overrides`
|
Corrections made while reviewing travel in `overrides`
|
||||||
(`{"<row>": {"field": value}}`) and win over the extracted value.
|
(`{"<row>": {"field": value}}`) and win over the extracted value.
|
||||||
@@ -65,7 +99,7 @@ class DocumentConnector(DataFrameConnector):
|
|||||||
|
|
||||||
kind = "document"
|
kind = "document"
|
||||||
label = "Documentos clínicos"
|
label = "Documentos clínicos"
|
||||||
description = "Reportes, formatos y notas en PDF o imagen; los campos se extraen del texto libre"
|
description = "Reportes, formatos y notas en PDF, imagen o texto; los campos se extraen del contenido"
|
||||||
category = "document"
|
category = "document"
|
||||||
icon = "document_scanner"
|
icon = "document_scanner"
|
||||||
extensions: ClassVar[tuple[str, ...]] = tuple(supported_extensions())
|
extensions: ClassVar[tuple[str, ...]] = tuple(supported_extensions())
|
||||||
@@ -103,7 +137,12 @@ class DocumentConnector(DataFrameConnector):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_payload(cls, payload: dict[str, Any]) -> "DocumentConnector":
|
def from_payload(cls, payload: dict[str, Any]) -> "DocumentConnector":
|
||||||
files = [(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)]
|
if payload.get("sql"):
|
||||||
|
files = _files_from_sql(payload["sql"])
|
||||||
|
else:
|
||||||
|
files = [
|
||||||
|
(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)
|
||||||
|
]
|
||||||
return cls(
|
return cls(
|
||||||
files,
|
files,
|
||||||
target=payload["target"],
|
target=payload["target"],
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
"""Matching OCR-discovered captions against a project's catalog, and
|
||||||
|
minting new catalog entries when nothing matches well enough.
|
||||||
|
|
||||||
|
`discover_captions` (Extraction) finds `caption: value` lines no known
|
||||||
|
`FieldSpec` already explains. For each one, this module decides whether an
|
||||||
|
existing `resultado_id` means the same thing closely enough to reuse
|
||||||
|
(`rapidfuzz`, tolerant of how a hospital's own report wording differs from
|
||||||
|
the catalog's own), or whether it's a field the catalog doesn't have yet —
|
||||||
|
in which case it's added (`add_resultado`), never silently dropped.
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
import unicodedata
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from rapidfuzz import fuzz, process
|
||||||
|
|
||||||
|
from extraction.nlp import DiscoveredField
|
||||||
|
from extraction.nlp.text import find_date, fold
|
||||||
|
from indicadores_kit.plata.procedimiento import valor_de_observacion
|
||||||
|
from indicadores_kit.registry.catalogos import Catalogo, add_resultado
|
||||||
|
|
||||||
|
# `token_sort_ratio`, not `WRatio`: `WRatio`'s partial-alignment bonus scores
|
||||||
|
# two short, unrelated captions that merely share common words ("de", "del")
|
||||||
|
# too high for this use (two genuinely different captions can clear 80).
|
||||||
|
# Lower than `extraction.nlp.extractors.FUZZY_LABEL_THRESHOLD` (0-100 scale
|
||||||
|
# here, that one 0-1): a caption is free text, not a single known label
|
||||||
|
# tolerating only OCR noise, so it varies more from the catalog's wording.
|
||||||
|
CAPTION_MATCH_THRESHOLD = 80.0
|
||||||
|
CAPTION_SCORER = fuzz.token_sort_ratio
|
||||||
|
FALLBACK_ESTUDIO_ID = "documento_externo"
|
||||||
|
FALLBACK_ESTUDIO_ETIQUETA = "Documento externo"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class MatchedField:
|
||||||
|
"""One discovered caption, resolved to a `resultado_id` (existing or
|
||||||
|
just minted) with its value already shaped for `observacion`."""
|
||||||
|
|
||||||
|
resultado_id: str
|
||||||
|
is_new: bool
|
||||||
|
observacion: dict
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class _NewResultado:
|
||||||
|
resultado_id: str
|
||||||
|
tipo_valor: str
|
||||||
|
|
||||||
|
|
||||||
|
def match_or_mint(
|
||||||
|
discovered: list[DiscoveredField], *, proyecto: str, catalogo: Catalogo, estudio_id: str | None = None
|
||||||
|
) -> list[MatchedField]:
|
||||||
|
"""One `MatchedField` per discovered caption, in order.
|
||||||
|
|
||||||
|
`estudio_id`, when the caller already knows it (the row's own
|
||||||
|
study-type column, resolved through `codigos_hospital`), scopes which
|
||||||
|
resultados are tried first and which estudio a minted field joins;
|
||||||
|
without it, every resultado in the catalog is a candidate and a new
|
||||||
|
field's estudio is guessed the same way, or falls back to
|
||||||
|
`documento_externo`.
|
||||||
|
"""
|
||||||
|
labels = _resultado_labels(catalogo, estudio_id)
|
||||||
|
valid_codes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"}
|
||||||
|
by_resultado_id = {r.resultado_id: r for r in catalogo.resultados}
|
||||||
|
resolved = []
|
||||||
|
for field in discovered:
|
||||||
|
found = _best_match(field.caption, labels)
|
||||||
|
if found is not None:
|
||||||
|
resultado, is_new = by_resultado_id[found], False
|
||||||
|
else:
|
||||||
|
resultado = _mint(field, proyecto=proyecto, estudio_id=estudio_id, catalogo=catalogo)
|
||||||
|
is_new = True
|
||||||
|
value = _coerce_value(field.value, resultado.tipo_valor)
|
||||||
|
observacion = valor_de_observacion(
|
||||||
|
value,
|
||||||
|
field.value,
|
||||||
|
tipo_valor=resultado.tipo_valor,
|
||||||
|
en_catalogo=lambda v, r=resultado.resultado_id: (r, v) in valid_codes,
|
||||||
|
)
|
||||||
|
resolved.append(MatchedField(resultado.resultado_id, is_new, observacion))
|
||||||
|
return resolved
|
||||||
|
|
||||||
|
|
||||||
|
def _resultado_labels(catalogo: Catalogo, estudio_id: str | None) -> dict[str, str]:
|
||||||
|
resultados = catalogo.resultados
|
||||||
|
if estudio_id is not None:
|
||||||
|
of_estudio = [r for r in resultados if r.estudio_id == estudio_id]
|
||||||
|
if of_estudio:
|
||||||
|
resultados = of_estudio
|
||||||
|
return {r.resultado_id: fold(r.etiqueta) for r in resultados}
|
||||||
|
|
||||||
|
|
||||||
|
def _best_match(caption: str, labels: dict[str, str]) -> str | None:
|
||||||
|
if not labels:
|
||||||
|
return None
|
||||||
|
found = process.extractOne(fold(caption), labels, scorer=CAPTION_SCORER, score_cutoff=CAPTION_MATCH_THRESHOLD)
|
||||||
|
return found[2] if found is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def _mint(field: DiscoveredField, *, proyecto: str, estudio_id: str | None, catalogo: Catalogo) -> _NewResultado:
|
||||||
|
estudio = estudio_id
|
||||||
|
estudio_etiqueta = None
|
||||||
|
if estudio is None:
|
||||||
|
estudio_labels = {e.estudio_id: fold(e.etiqueta) for e in catalogo.estudios}
|
||||||
|
found = process.extractOne(fold(field.caption), estudio_labels, scorer=CAPTION_SCORER, score_cutoff=CAPTION_MATCH_THRESHOLD)
|
||||||
|
estudio = found[2] if found is not None else None
|
||||||
|
if estudio is None:
|
||||||
|
estudio, estudio_etiqueta = FALLBACK_ESTUDIO_ID, FALLBACK_ESTUDIO_ETIQUETA
|
||||||
|
tipo_valor = _infer_tipo_valor(field.value)
|
||||||
|
resultado_id = add_resultado(
|
||||||
|
proyecto,
|
||||||
|
estudio_id=estudio,
|
||||||
|
nombre=_slug(field.caption),
|
||||||
|
etiqueta=field.caption.strip(),
|
||||||
|
tipo_valor=tipo_valor,
|
||||||
|
estudio_etiqueta=estudio_etiqueta,
|
||||||
|
)
|
||||||
|
return _NewResultado(resultado_id, tipo_valor)
|
||||||
|
|
||||||
|
|
||||||
|
def _slug(text: str) -> str:
|
||||||
|
without_accents = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("ascii")
|
||||||
|
return re.sub(r"[^a-z0-9]+", "_", without_accents.lower()).strip("_") or "campo"
|
||||||
|
|
||||||
|
|
||||||
|
def _infer_tipo_valor(value: str) -> str:
|
||||||
|
if find_date(value) is not None:
|
||||||
|
return "fecha"
|
||||||
|
if _is_number(value):
|
||||||
|
return "numero"
|
||||||
|
return "texto"
|
||||||
|
|
||||||
|
|
||||||
|
def _is_number(value: str) -> bool:
|
||||||
|
try:
|
||||||
|
float(value.strip().replace(",", "."))
|
||||||
|
return True
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _coerce_value(value: str, tipo_valor: str):
|
||||||
|
if tipo_valor == "fecha":
|
||||||
|
found = find_date(value)
|
||||||
|
return found[0] if found else None
|
||||||
|
if tipo_valor in ("numero", "booleano"):
|
||||||
|
try:
|
||||||
|
return float(value.strip().replace(",", "."))
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return value
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
"""Writes the catalog-fallback fields a document source's records carry
|
||||||
|
(captions no known `FieldSpec` claimed, see `extraction.nlp.discovery`)
|
||||||
|
into the silver layer directly: one synthetic `procedimiento` per record
|
||||||
|
per estudio its resolved fields touch, with their `observacion`s matched
|
||||||
|
or minted against the project's catalog (`catalog_matching`).
|
||||||
|
|
||||||
|
There is no staging row for these — the whole point is a field outside
|
||||||
|
today's structured schemas — so this bypasses `DESDE_STAGING` and writes
|
||||||
|
straight through the domain's existing `carga_repository`, the same one
|
||||||
|
`webapi.orquestacion`'s `cargar` step uses for staging-derived batches.
|
||||||
|
|
||||||
|
Marked clearly apart from every staging-derived procedimiento:
|
||||||
|
`fuente_tabla` is the sentinel `FUENTE_CATALOGO_ABIERTO`, never a real
|
||||||
|
staging table name. `fuente_id` is the record's own natural key (not a SQL
|
||||||
|
row's surrogate id), so reprocessing the same record later — read again
|
||||||
|
from the SQL source, re-uploaded as a file, or corrected by hand — updates
|
||||||
|
the same rows in place instead of duplicating them; the structured fields
|
||||||
|
a source also carries keep going through the unmodified staging/import
|
||||||
|
path (`commit_sources`), independently of this.
|
||||||
|
"""
|
||||||
|
from collections import defaultdict
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from importlib import import_module
|
||||||
|
|
||||||
|
from extraction import ExtractedRecord
|
||||||
|
from indicadores_kit.plata.procedimiento import LotePlata
|
||||||
|
from indicadores_kit.registry.catalogos import Catalogo, catalogo_desde_toml, ruta_de_catalogo
|
||||||
|
from indicadores_kit.tablas import tablas_de
|
||||||
|
|
||||||
|
from webapi.imports.schemas.catalog_matching import MatchedField, match_or_mint
|
||||||
|
|
||||||
|
FUENTE_CATALOGO_ABIERTO = "catalogo_abierto"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class CatalogCommitResult:
|
||||||
|
proyecto: str
|
||||||
|
records_written: int = 0
|
||||||
|
records_without_patient: int = 0
|
||||||
|
fields_matched: int = 0
|
||||||
|
fields_minted: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
def commit_discovered_fields(
|
||||||
|
records: list[ExtractedRecord], *, proyecto: str, estudio_id: str | None = None
|
||||||
|
) -> CatalogCommitResult:
|
||||||
|
"""A patient without a row in `persona` is counted and skipped: this
|
||||||
|
path only fills in fields for a patient already known, it doesn't
|
||||||
|
create one."""
|
||||||
|
dominio = import_module(f"persistance.{proyecto}")
|
||||||
|
tablas = tablas_de(proyecto)
|
||||||
|
ruta = ruta_de_catalogo(proyecto)
|
||||||
|
catalogo = catalogo_desde_toml(ruta, tablas=tablas)
|
||||||
|
|
||||||
|
result = CatalogCommitResult(proyecto=proyecto)
|
||||||
|
procedures, observations = [], []
|
||||||
|
for record in records:
|
||||||
|
if not record.discovered or record.key is None:
|
||||||
|
continue
|
||||||
|
patients = dominio.paciente_repository.list(pac_id_hospital=record.key, limit=1)
|
||||||
|
if not patients:
|
||||||
|
result.records_without_patient += 1
|
||||||
|
continue
|
||||||
|
pac_id = patients[0].pac_id
|
||||||
|
|
||||||
|
matched = match_or_mint(record.discovered, proyecto=proyecto, catalogo=catalogo, estudio_id=estudio_id)
|
||||||
|
if any(field.is_new for field in matched):
|
||||||
|
catalogo = catalogo_desde_toml(ruta, tablas=tablas) # so a later record in this batch can match it too
|
||||||
|
matched = _fold_duplicates(matched)
|
||||||
|
|
||||||
|
by_estudio: dict[str, list] = defaultdict(list)
|
||||||
|
for field in matched:
|
||||||
|
by_estudio[field.resultado_id.split(".", 1)[0]].append(field)
|
||||||
|
result.fields_minted += int(field.is_new)
|
||||||
|
result.fields_matched += int(not field.is_new)
|
||||||
|
for estudio, fields in by_estudio.items():
|
||||||
|
key = (FUENTE_CATALOGO_ABIERTO, record.key, estudio, "reporte")
|
||||||
|
procedures.append({"llave": key, "padres": [], "pac_id": pac_id, "fecha": None, "fecha_del_padre": False})
|
||||||
|
observations += [
|
||||||
|
{"procedimiento": key, "pac_id": pac_id, "resultado_id": field.resultado_id, **field.observacion}
|
||||||
|
for field in fields
|
||||||
|
]
|
||||||
|
result.records_written += 1
|
||||||
|
|
||||||
|
if procedures:
|
||||||
|
_sync_catalog(dominio, proyecto, tablas)
|
||||||
|
dominio.carga_repository.guardar_carga(
|
||||||
|
fuente=FUENTE_CATALOGO_ABIERTO, personas=(), plata=LotePlata(procedures, observations, {})
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _fold_duplicates(matched: list[MatchedField]) -> list[MatchedField]:
|
||||||
|
"""A record's discovered captions can repeat the same resultado_id (a
|
||||||
|
static label such as "FECHA" printed on several pages): `observacion`
|
||||||
|
has one row per `(procedimiento, resultado_id)`, so only the first
|
||||||
|
occurrence survives. `discover_captions` keeps every repeat on purpose
|
||||||
|
and leaves folding to the caller (see its docstring)."""
|
||||||
|
seen: set[str] = set()
|
||||||
|
folded = []
|
||||||
|
for field in matched:
|
||||||
|
if field.resultado_id in seen:
|
||||||
|
continue
|
||||||
|
seen.add(field.resultado_id)
|
||||||
|
folded.append(field)
|
||||||
|
return folded
|
||||||
|
|
||||||
|
|
||||||
|
def _sync_catalog(dominio, proyecto: str, tablas) -> None:
|
||||||
|
"""A field minted by `match_or_mint` only exists in the TOML until this
|
||||||
|
runs: `procedimiento.estudio_id` and `observacion`'s catalog both need
|
||||||
|
the matching `cat_estudio`/`cat_resultado` row to already be there."""
|
||||||
|
catalogo: Catalogo = catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas)
|
||||||
|
dominio.catalogo_repository.sincronizar(catalogo.estudios, catalogo.resultados, catalogo.valores)
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
"""Seguimiento CaMa de demostración: contrato independiente de la fuente de datos.
|
||||||
|
|
||||||
|
Para conectar cama_linea_de_tiempo, sustituir ``leer_fixture`` por un lector que
|
||||||
|
entregue los mismos campos escalares y fechas de estudio; mantener el filtrado,
|
||||||
|
orden y contrato HTTP. Los IDs de este fixture no representan pacientes reales.
|
||||||
|
"""
|
||||||
|
import calendar
|
||||||
|
import logging
|
||||||
|
from datetime import date, timedelta
|
||||||
|
|
||||||
|
from flask import Blueprint, jsonify, request
|
||||||
|
|
||||||
|
from webapi.seguimiento import _pedido
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
CATEGORIAS = {
|
||||||
|
"estatus": ("Estatus de seguimiento", {"PENDIENTE_BIOPSIA": "Pendiente de biopsia", "BIOPSIA_SIN_RESULTADO": "Biopsia sin resultado", "CANCER_CONFIRMADO": "Cáncer confirmado", "BENIGNO": "Benigno, regresa a tamizaje", "INFO_INSUFICIENTE": "Información insuficiente"}),
|
||||||
|
"birads": ("Categoría BI-RADS", {f"BIRADS_{v}": f"BI-RADS {v}" for v in ("4A", "4B", "4C", "5", "6")}),
|
||||||
|
"grupo_edad": ("Grupo de edad", {v: v for v in ("40-49", "50-59", "60-69", "70+")}),
|
||||||
|
"prioridad": ("Prioridad", {"ALTA": "Alta", "MEDIA": "Media", "BAJA": "Baja"}),
|
||||||
|
}
|
||||||
|
COLUMNAS = [
|
||||||
|
{"clave": "id_seudonimo", "etiqueta": "Identificador seudónimo"},
|
||||||
|
{"clave": "grupo_edad", "etiqueta": "Grupo de edad"},
|
||||||
|
{"clave": "estatus", "etiqueta": "Estatus de seguimiento"},
|
||||||
|
{"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]},
|
||||||
|
{"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de biopsia"}]},
|
||||||
|
{"clave": "dias_mastografia_diagnostico", "etiqueta": "Días de mastografía a diagnóstico"},
|
||||||
|
{"clave": "prioridad", "etiqueta": "Prioridad"},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def leer_fixture(corte, desde):
|
||||||
|
"""Filas inventadas; el futuro lector recibe el corte y la ventana solicitados."""
|
||||||
|
datos = [
|
||||||
|
("M-0001", "2026-10-15", "PENDIENTE_BIOPSIA", "BIRADS_5", "50-59", "ALTA", None, None, None),
|
||||||
|
("M-0002", "2026-10-15", "BIOPSIA_SIN_RESULTADO", "BIRADS_4A", "40-49", "MEDIA", None, "2026-10-18", None),
|
||||||
|
("M-0003", "2026-09-01", "BENIGNO", "BIRADS_4B", "60-69", "BAJA", "Benigno", "2026-09-10", 16),
|
||||||
|
("M-0004", "2026-08-15", "CANCER_CONFIRMADO", "BIRADS_4C", "70+", "ALTA", "Carcinoma invasor", "2026-08-22", 20),
|
||||||
|
("M-0005", "2026-07-21", "INFO_INSUFICIENTE", "BIRADS_6", "40-49", "MEDIA", None, None, None),
|
||||||
|
("M-0006", "2026-05-01", "BENIGNO", "BIRADS_4B", "60-69", "BAJA", "Benigno", "2026-05-09", 15),
|
||||||
|
("M-0007", "2026-01-20", "PENDIENTE_BIOPSIA", "BIRADS_5", "50-59", "ALTA", None, None, None),
|
||||||
|
("M-0008", "2025-11-01", "BIOPSIA_SIN_RESULTADO", "BIRADS_4A", "40-49", "MEDIA", None, "2025-11-10", None),
|
||||||
|
]
|
||||||
|
claves = ("id_seudonimo", "mastografia_fecha", "estatus", "birads", "grupo_edad", "prioridad", "biopsia", "biopsia_fecha", "dias_mastografia_diagnostico")
|
||||||
|
return [dict(zip(claves, fila)) for fila in datos]
|
||||||
|
|
||||||
|
|
||||||
|
def _desde(corte, meses):
|
||||||
|
indice = corte.year * 12 + corte.month - 1 - meses
|
||||||
|
anio, mes = divmod(indice, 12)
|
||||||
|
if anio < 1:
|
||||||
|
raise ValueError("la ventana excede el rango de fechas admitido")
|
||||||
|
anterior = date(anio, mes + 1, min(corte.day, calendar.monthrange(anio, mes + 1)[1]))
|
||||||
|
return anterior + timedelta(days=1)
|
||||||
|
|
||||||
|
|
||||||
|
def _consulta(args):
|
||||||
|
allowed = {'corte', 'meses', 'page', 'page_size', *CATEGORIAS}
|
||||||
|
if set(args) - allowed or any(len(args.getlist(key)) != 1 for key in args):
|
||||||
|
raise ValueError('Parámetros desconocidos o repetidos')
|
||||||
|
pedido = _pedido(args)
|
||||||
|
corte = pedido.get("corte", date(2026, 10, 20))
|
||||||
|
meses, page, size = (pedido.get("meses", 3), pedido.get("page", 1), pedido.get("page_size", 50))
|
||||||
|
if meses not in (1, 3, 6, 12) or page < 1 or not 1 <= size <= 200:
|
||||||
|
raise ValueError("meses debe ser 1, 3, 6 o 12; page desde 1 y page_size entre 1 y 200")
|
||||||
|
filtros = {clave: args.get(clave) or None for clave in CATEGORIAS}
|
||||||
|
for clave, valor in filtros.items():
|
||||||
|
if valor is not None and valor not in CATEGORIAS[clave][1]:
|
||||||
|
raise ValueError(f"{clave} desconocido: {valor!r}")
|
||||||
|
return corte, meses, page, size, filtros, _desde(corte, meses)
|
||||||
|
|
||||||
|
|
||||||
|
def _filas(corte, desde, filtros):
|
||||||
|
fuente = []
|
||||||
|
for original in leer_fixture(corte, desde):
|
||||||
|
fila = dict(original)
|
||||||
|
if fila['biopsia_fecha'] and fila['biopsia_fecha'] > corte.isoformat():
|
||||||
|
fila.update(biopsia=None, biopsia_fecha=None, dias_mastografia_diagnostico=None,
|
||||||
|
estatus='INFO_INSUFICIENTE')
|
||||||
|
fuente.append(fila)
|
||||||
|
filas = [fila for fila in fuente
|
||||||
|
if desde.isoformat() <= fila["mastografia_fecha"] <= corte.isoformat()
|
||||||
|
and all(valor is None or fila[clave] == valor for clave, valor in filtros.items())]
|
||||||
|
filas.sort(key=lambda fila: fila["id_seudonimo"])
|
||||||
|
filas.sort(key=lambda fila: fila["mastografia_fecha"], reverse=True)
|
||||||
|
return filas
|
||||||
|
|
||||||
|
|
||||||
|
def _item(fila):
|
||||||
|
item = dict(fila)
|
||||||
|
for clave, (_, opciones) in CATEGORIAS.items():
|
||||||
|
item[clave + "_codigo"] = item[clave]
|
||||||
|
item[clave] = opciones[item[clave]]
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
def _metadatos(corte, meses, desde, filtros):
|
||||||
|
return dict(simulado=True, corte=corte.isoformat(),
|
||||||
|
ventana={"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()},
|
||||||
|
campo_ventana="mastografia_fecha", filtros=filtros,
|
||||||
|
filtros_disponibles=[{"clave": clave, "etiqueta": etiqueta,
|
||||||
|
"opciones": [{"codigo": c, "etiqueta": e} for c, e in opciones.items()]}
|
||||||
|
for clave, (etiqueta, opciones) in CATEGORIAS.items()],
|
||||||
|
columnas=COLUMNAS)
|
||||||
|
|
||||||
|
|
||||||
|
def blueprint_seguimiento_cama():
|
||||||
|
blueprint = Blueprint("cama_seguimiento", __name__)
|
||||||
|
|
||||||
|
@blueprint.after_request
|
||||||
|
def sin_cache_en_contratos_nuevos(response):
|
||||||
|
if 'cohorte' in request.args or request.endpoint in ("cama_seguimiento.exportacion", "cama_seguimiento.paciente"):
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
return response
|
||||||
|
|
||||||
|
@blueprint.get("/seguimiento")
|
||||||
|
def seguimiento():
|
||||||
|
"""Lista sintética de seguimiento CaMa con filtros y columnas declarativos."""
|
||||||
|
if 'cohorte' in request.args:
|
||||||
|
from webapi.cama_analysis import SelectionError, selection_response
|
||||||
|
try:
|
||||||
|
return selection_response(request.args, 'list')
|
||||||
|
except SelectionError as error:
|
||||||
|
return jsonify(error=error.message), error.status
|
||||||
|
try:
|
||||||
|
corte, meses, page, size, filtros, desde = _consulta(request.args)
|
||||||
|
except ValueError as error:
|
||||||
|
return jsonify(error=str(error)), 400
|
||||||
|
try:
|
||||||
|
filas = _filas(corte, desde, filtros)
|
||||||
|
total = len(filas)
|
||||||
|
return jsonify(**_metadatos(corte, meses, desde, filtros),
|
||||||
|
paginacion={"page": page, "page_size": size, "total_items": total,
|
||||||
|
"total_pages": (total + size - 1) // size},
|
||||||
|
items=[_item(fila) for fila in filas[(page - 1) * size:page * size]])
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error al leer seguimiento CaMa")
|
||||||
|
return jsonify(error="No se pudo consultar el seguimiento CaMa"), 500
|
||||||
|
|
||||||
|
@blueprint.get("/seguimiento/exportacion")
|
||||||
|
def exportacion():
|
||||||
|
if 'cohorte' in request.args:
|
||||||
|
from webapi.cama_analysis import SelectionError, selection_response
|
||||||
|
try:
|
||||||
|
return selection_response(request.args, 'export')
|
||||||
|
except SelectionError as error:
|
||||||
|
return jsonify(error=error.message), error.status
|
||||||
|
try:
|
||||||
|
corte, meses, _, _, filtros, desde = _consulta(request.args)
|
||||||
|
except ValueError as error:
|
||||||
|
return jsonify(error=str(error)), 400
|
||||||
|
try:
|
||||||
|
filas = _filas(corte, desde, filtros)
|
||||||
|
if len(filas) > 5000:
|
||||||
|
return jsonify(error="La exportación supera el límite de 5000 registros"), 413
|
||||||
|
return jsonify(**_metadatos(corte, meses, desde, filtros), total_items=len(filas),
|
||||||
|
items=[_item(fila) for fila in filas])
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error al exportar seguimiento CaMa")
|
||||||
|
return jsonify(error="No se pudo consultar el seguimiento CaMa"), 500
|
||||||
|
|
||||||
|
@blueprint.get("/pacientes/<id_seudonimo>")
|
||||||
|
def paciente(id_seudonimo):
|
||||||
|
if 'cohorte' in request.args:
|
||||||
|
from webapi.cama_analysis import SelectionError, selection_response
|
||||||
|
try:
|
||||||
|
return selection_response(request.args, 'patient', id_seudonimo)
|
||||||
|
except SelectionError as error:
|
||||||
|
return jsonify(error=error.message), error.status
|
||||||
|
try:
|
||||||
|
corte, meses, _, _, _, desde = _consulta(request.args)
|
||||||
|
except ValueError as error:
|
||||||
|
return jsonify(error=str(error)), 400
|
||||||
|
try:
|
||||||
|
filas = _filas(corte, desde, {clave: None for clave in CATEGORIAS})
|
||||||
|
fila = next((fila for fila in filas if fila["id_seudonimo"] == id_seudonimo), None)
|
||||||
|
if fila is None:
|
||||||
|
return jsonify(error="Paciente no encontrado en la ventana solicitada"), 404
|
||||||
|
return jsonify(simulado=True, corte=corte.isoformat(),
|
||||||
|
ventana={"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()},
|
||||||
|
item=_item(fila))
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error al consultar paciente CaMa")
|
||||||
|
return jsonify(error="No se pudo consultar el paciente CaMa"), 500
|
||||||
|
|
||||||
|
return blueprint
|
||||||
Reference in New Issue
Block a user