Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4c181af291 | |||
| 7d180417d8 | |||
| 00f773dd75 | |||
| 3bb1c8dd84 |
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"cacu/CACU-CONFIRMACION-CITOLOGIA": {
|
||||
"id": "cacu_confirmacion_citologia",
|
||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
||||
"indicador": {
|
||||
"id": "cacu_confirmacion_citologia",
|
||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
||||
"version": "0.1.2",
|
||||
"titulo": "Tasa de confirmación histopatológica",
|
||||
"contrato": "C2",
|
||||
@@ -19,7 +19,7 @@
|
||||
"filtros": []
|
||||
},
|
||||
"metadatos": {
|
||||
"id": "cacu_confirmacion_citologia",
|
||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
||||
"version": "0.1.2",
|
||||
"descripcion": "De las pacientes cuya última citología del periodo con resultado y calidad de espécimen satisfactoria es de alto grado (ASC-H, LIEAG o carcinoma in situ), cuántas tienen cada grado en la biopsia que esa citología originó, por resultado citológico. A la fecha de corte: sin un plazo máximo, una paciente «sin biopsia aún» puede pasar a un grado mientras lleguen reportes.",
|
||||
"ficha": {
|
||||
@@ -41,7 +41,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "cacu_confirmacion_citologia",
|
||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
||||
"titulo": "Tasa de confirmación histopatológica",
|
||||
"version": "0.1.2",
|
||||
"contrato": "C2",
|
||||
@@ -80,14 +80,51 @@
|
||||
"filas": []
|
||||
},
|
||||
"citologia_alto_grado": {
|
||||
"error": "Categoría no declarada en el estrato"
|
||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
||||
"titulo": "Tasa de confirmación histopatológica",
|
||||
"version": "0.1.2",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2021-S1",
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": "citologia_alto_grado",
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
"notas": [],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2021-S1",
|
||||
"report_id": 35,
|
||||
"periodo_inicio": "2021-01-01",
|
||||
"periodo_fin": "2021-07-01",
|
||||
"fecha_corte": "2026-11-16",
|
||||
"generado_en": "2026-11-16T23:08:24.181623+00:00"
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"report_id": 44,
|
||||
"periodo_inicio": "2025-07-01",
|
||||
"periodo_fin": "2026-01-01",
|
||||
"fecha_corte": "2026-11-16",
|
||||
"generado_en": "2026-11-16T23:08:24.682752+00:00"
|
||||
}
|
||||
],
|
||||
"filas": []
|
||||
}
|
||||
}
|
||||
},
|
||||
"cacu/CACU-DIAS-TOMA-DIAGNOSTICO": {
|
||||
"id": "cacu_dias_toma_diagnostico",
|
||||
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
|
||||
"indicador": {
|
||||
"id": "cacu_dias_toma_diagnostico",
|
||||
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
|
||||
"version": "0.2.3",
|
||||
"titulo": "Tiempo de tamizaje a diagnóstico",
|
||||
"contrato": "C3r",
|
||||
@@ -102,7 +139,7 @@
|
||||
"filtros": []
|
||||
},
|
||||
"metadatos": {
|
||||
"id": "cacu_dias_toma_diagnostico",
|
||||
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
|
||||
"version": "0.2.3",
|
||||
"descripcion": "Días naturales de la toma de cada citología del periodo a la primera nota médica posterior que la resuelve: un diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que diagnostican, dentro del horizonte y a la fecha de corte. Entran todas las citologías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.",
|
||||
"ficha": {
|
||||
@@ -134,7 +171,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "cacu_dias_toma_diagnostico",
|
||||
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
|
||||
"titulo": "Tiempo de tamizaje a diagnóstico",
|
||||
"version": "0.2.3",
|
||||
"contrato": "C3r",
|
||||
@@ -202,9 +239,9 @@
|
||||
}
|
||||
},
|
||||
"cacu/CACU-EU-TIEMPO-REPORTE": {
|
||||
"id": "cacu_eu_tiempo_reporte",
|
||||
"id": "CACU_EU_TIEMPO_REPORTE",
|
||||
"indicador": {
|
||||
"id": "cacu_eu_tiempo_reporte",
|
||||
"id": "CACU_EU_TIEMPO_REPORTE",
|
||||
"version": "0.2.1",
|
||||
"titulo": "Días de la toma de la citología a su resultado",
|
||||
"contrato": "C3r",
|
||||
@@ -219,7 +256,7 @@
|
||||
"filtros": []
|
||||
},
|
||||
"metadatos": {
|
||||
"id": "cacu_eu_tiempo_reporte",
|
||||
"id": "CACU_EU_TIEMPO_REPORTE",
|
||||
"version": "0.2.1",
|
||||
"descripcion": "Días naturales de la toma de cada citología del periodo a su resultado, a la fecha de corte. Las que aún no tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los excluidos.",
|
||||
"ficha": {
|
||||
@@ -251,7 +288,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "cacu_eu_tiempo_reporte",
|
||||
"id": "CACU_EU_TIEMPO_REPORTE",
|
||||
"titulo": "Días de la toma de la citología a su resultado",
|
||||
"version": "0.2.1",
|
||||
"contrato": "C3r",
|
||||
@@ -319,9 +356,9 @@
|
||||
}
|
||||
},
|
||||
"cacu/CACU-EU13": {
|
||||
"id": "cacu_eu13",
|
||||
"id": "CACU_EU13",
|
||||
"indicador": {
|
||||
"id": "cacu_eu13",
|
||||
"id": "CACU_EU13",
|
||||
"version": "0.3.2",
|
||||
"titulo": "Tasa de detección histopatológica",
|
||||
"contrato": "C1",
|
||||
@@ -339,7 +376,7 @@
|
||||
"filtros": []
|
||||
},
|
||||
"metadatos": {
|
||||
"id": "cacu_eu13",
|
||||
"id": "CACU_EU13",
|
||||
"version": "0.3.2",
|
||||
"descripcion": "De todas las mujeres tamizadas en el periodo, las que tienen una biopsia reportada con LIEAG (CIN 2 y 3), carcinoma in situ o carcinoma invasor, originada por una de sus citologías del periodo.",
|
||||
"ficha": {
|
||||
@@ -371,7 +408,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "cacu_eu13",
|
||||
"id": "CACU_EU13",
|
||||
"titulo": "Tasa de detección histopatológica",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
@@ -384,7 +421,7 @@
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"grupos": {
|
||||
"total": "Total"
|
||||
"principal": "principal"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
@@ -410,7 +447,7 @@
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2021-S1",
|
||||
"grupo": "total",
|
||||
"grupo": "principal",
|
||||
"estrato": null,
|
||||
"suprimido": 0,
|
||||
"numerador": 0,
|
||||
@@ -423,7 +460,7 @@
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "total",
|
||||
"grupo": "principal",
|
||||
"estrato": null,
|
||||
"suprimido": 0,
|
||||
"numerador": 1,
|
||||
@@ -437,7 +474,7 @@
|
||||
]
|
||||
},
|
||||
"grupo_edad": {
|
||||
"id": "cacu_eu13",
|
||||
"id": "CACU_EU13",
|
||||
"titulo": "Tasa de detección histopatológica",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
@@ -463,7 +500,7 @@
|
||||
"<25": "<25"
|
||||
},
|
||||
"grupos": {
|
||||
"total": "Total"
|
||||
"principal": "principal"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
@@ -489,7 +526,7 @@
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "total",
|
||||
"grupo": "principal",
|
||||
"estrato": "25-34",
|
||||
"suprimido": 0,
|
||||
"numerador": 0,
|
||||
@@ -502,7 +539,7 @@
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "total",
|
||||
"grupo": "principal",
|
||||
"estrato": "35-44",
|
||||
"suprimido": 0,
|
||||
"numerador": 0,
|
||||
@@ -515,7 +552,7 @@
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "total",
|
||||
"grupo": "principal",
|
||||
"estrato": "45-54",
|
||||
"suprimido": 0,
|
||||
"numerador": 1,
|
||||
@@ -528,7 +565,7 @@
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "total",
|
||||
"grupo": "principal",
|
||||
"estrato": "55-64",
|
||||
"suprimido": 0,
|
||||
"numerador": 0,
|
||||
@@ -541,7 +578,7 @@
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "total",
|
||||
"grupo": "principal",
|
||||
"estrato": "<25",
|
||||
"suprimido": 0,
|
||||
"numerador": 0,
|
||||
@@ -555,7 +592,7 @@
|
||||
]
|
||||
},
|
||||
"estatus_seguimiento": {
|
||||
"id": "cacu_eu13",
|
||||
"id": "CACU_EU13",
|
||||
"titulo": "Tasa de detección histopatológica",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
@@ -573,7 +610,7 @@
|
||||
"PRE_COLPOSCOPIA": "PRE_COLPOSCOPIA"
|
||||
},
|
||||
"grupos": {
|
||||
"total": "Total"
|
||||
"principal": "principal"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
@@ -599,7 +636,7 @@
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "total",
|
||||
"grupo": "principal",
|
||||
"estrato": "PRE_COLPOSCOPIA",
|
||||
"suprimido": 0,
|
||||
"numerador": 1,
|
||||
@@ -615,9 +652,9 @@
|
||||
}
|
||||
},
|
||||
"cacu/CACU-EU7": {
|
||||
"id": "cacu_eu7",
|
||||
"id": "CACU_EU7",
|
||||
"indicador": {
|
||||
"id": "cacu_eu7",
|
||||
"id": "CACU_EU7",
|
||||
"version": "0.3.3",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"contrato": "C2",
|
||||
@@ -635,7 +672,7 @@
|
||||
"filtros": []
|
||||
},
|
||||
"metadatos": {
|
||||
"id": "cacu_eu7",
|
||||
"id": "CACU_EU7",
|
||||
"version": "0.3.3",
|
||||
"descripcion": "Cuántas pacientes caen en cada resultado citológico en el periodo, cada una en el de su última citología con resultado y calidad de espécimen satisfactoria. «Sin dato»: resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.",
|
||||
"ficha": {
|
||||
@@ -657,7 +694,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "cacu_eu7",
|
||||
"id": "CACU_EU7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.3.3",
|
||||
"contrato": "C2",
|
||||
@@ -696,17 +733,91 @@
|
||||
"filas": []
|
||||
},
|
||||
"grupo_edad": {
|
||||
"error": "Categoría no declarada en el estrato"
|
||||
"id": "CACU_EU7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.3.3",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2021-S1",
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": "grupo_edad",
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
"notas": [],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2021-S1",
|
||||
"report_id": 83,
|
||||
"periodo_inicio": "2021-01-01",
|
||||
"periodo_fin": "2021-07-01",
|
||||
"fecha_corte": "2026-11-16",
|
||||
"generado_en": "2026-11-16T23:08:29.557925+00:00"
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"report_id": 92,
|
||||
"periodo_inicio": "2025-07-01",
|
||||
"periodo_fin": "2026-01-01",
|
||||
"fecha_corte": "2026-11-16",
|
||||
"generado_en": "2026-11-16T23:08:31.081202+00:00"
|
||||
}
|
||||
],
|
||||
"filas": []
|
||||
},
|
||||
"estatus_seguimiento": {
|
||||
"error": "Categoría no declarada en el estrato"
|
||||
"id": "CACU_EU7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.3.3",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2021-S1",
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": "estatus_seguimiento",
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
"notas": [],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2021-S1",
|
||||
"report_id": 83,
|
||||
"periodo_inicio": "2021-01-01",
|
||||
"periodo_fin": "2021-07-01",
|
||||
"fecha_corte": "2026-11-16",
|
||||
"generado_en": "2026-11-16T23:08:29.557925+00:00"
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"report_id": 92,
|
||||
"periodo_inicio": "2025-07-01",
|
||||
"periodo_fin": "2026-01-01",
|
||||
"fecha_corte": "2026-11-16",
|
||||
"generado_en": "2026-11-16T23:08:31.081202+00:00"
|
||||
}
|
||||
],
|
||||
"filas": []
|
||||
}
|
||||
}
|
||||
},
|
||||
"cacu/CACU-RIESGO-BANDA": {
|
||||
"id": "cacu_riesgo_banda",
|
||||
"id": "CACU_RIESGO_BANDA",
|
||||
"indicador": {
|
||||
"id": "cacu_riesgo_banda",
|
||||
"id": "CACU_RIESGO_BANDA",
|
||||
"version": "0.1.0",
|
||||
"titulo": "Pacientes en vigilancia por banda de riesgo de CIN2+",
|
||||
"contrato": "C2",
|
||||
@@ -720,7 +831,7 @@
|
||||
"filtros": []
|
||||
},
|
||||
"metadatos": {
|
||||
"id": "cacu_riesgo_banda",
|
||||
"id": "CACU_RIESGO_BANDA",
|
||||
"version": "0.1.0",
|
||||
"descripcion": "Cuántas pacientes de la cohorte de vigilancia, con citología índice en el periodo, caen en cada banda de riesgo estimado de CIN2+. Cuenta el lote de evaluaciones vigente (confirmado). «Sin dato»: la paciente no tiene evaluación confirmada en ese lote.",
|
||||
"ficha": {
|
||||
@@ -742,7 +853,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "cacu_riesgo_banda",
|
||||
"id": "CACU_RIESGO_BANDA",
|
||||
"titulo": "Pacientes en vigilancia por banda de riesgo de CIN2+",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C2",
|
||||
@@ -783,9 +894,9 @@
|
||||
}
|
||||
},
|
||||
"cacu/IND1": {
|
||||
"id": "ind1",
|
||||
"id": "IND1",
|
||||
"indicador": {
|
||||
"id": "ind1",
|
||||
"id": "IND1",
|
||||
"version": "0.3.2",
|
||||
"titulo": "Pacientes con citología anómala",
|
||||
"contrato": "C1",
|
||||
@@ -800,7 +911,7 @@
|
||||
"filtros": []
|
||||
},
|
||||
"metadatos": {
|
||||
"id": "ind1",
|
||||
"id": "IND1",
|
||||
"version": "0.3.2",
|
||||
"descripcion": "Proporción de pacientes con citología tomada en el periodo con al menos un resultado anómalo: ASC-US, LIEBG, ASC-H, LIEAG o carcinoma in situ (sistema Bethesda). Una paciente con varias citologías cuenta una vez.",
|
||||
"ficha": {
|
||||
@@ -832,7 +943,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "ind1",
|
||||
"id": "IND1",
|
||||
"titulo": "Pacientes con citología anómala",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
@@ -845,7 +956,7 @@
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"grupos": {
|
||||
"total": "Total"
|
||||
"principal": "principal"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
@@ -871,7 +982,7 @@
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2021-S1",
|
||||
"grupo": "total",
|
||||
"grupo": "principal",
|
||||
"estrato": null,
|
||||
"suprimido": 0,
|
||||
"numerador": 0,
|
||||
@@ -884,7 +995,7 @@
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "total",
|
||||
"grupo": "principal",
|
||||
"estrato": null,
|
||||
"suprimido": 0,
|
||||
"numerador": 19,
|
||||
|
||||
@@ -9,7 +9,7 @@ import { describePeriods, filterCompatibility, GlobalApplied } from './indicador
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { percentText } from './indicadores-format';
|
||||
import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
|
||||
|
||||
@@ -101,8 +101,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
|
||||
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|
||||
|| !(stratifiedCapabilities(this.indicador).includes(ESTRATO) || declaraEstrato(this.indicador, ESTRATO))
|
||||
|| !compatibility.compatible) {
|
||||
|| !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
<section class="route" aria-label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje">
|
||||
<h3 class="figure-title">Tiempos de la ruta del tamizaje</h3>
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando los tiempos de la ruta del tamizaje" /><p role="status">Cargando los tiempos de la ruta…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message() }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>{{ message() }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (model(); as m) {
|
||||
<div class="controls">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Periodo</mat-label>
|
||||
<mat-select [value]="m.period" (selectionChange)="selectPeriod($event.value)" aria-label="Periodo de la ruta del tamizaje">
|
||||
@for (period of m.periods; track period) { <mat-option [value]="period">{{ periodLabel(period) }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-button-toggle-group [value]="view()" (change)="selectView($event.value)" aria-label="Vista de los tiempos">
|
||||
<mat-button-toggle value="cumulative">Acumulado desde la toma</mat-button-toggle>
|
||||
<mat-button-toggle value="steps">Por pasos</mat-button-toggle>
|
||||
</mat-button-toggle-group>
|
||||
</div>
|
||||
@if (status() === 'empty') { <p role="status">No hay tiempos publicados para esta ruta.</p> }
|
||||
@else if (figure(); as figure) {
|
||||
<app-plotly-chart [figure]="figure" [showNotes]="false" label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje" />
|
||||
<p class="note">
|
||||
@if (view() === 'cumulative') {
|
||||
Cada barra es la mediana de días desde la toma de muestra hasta ese evento y el bigote va de Q1 a Q3. Cada fila cuenta solo a quienes llegaron a ese evento.
|
||||
El diagnóstico incluye a quienes lo recibieron tras el tamizaje, en la colposcopía o tras la biopsia, por eso su barra puede salir antes que la de biopsia.
|
||||
} @else {
|
||||
Cada barra es el tramo desde el evento anterior y empieza donde termina el tramo previo; la de color es el tramo más lento. Cada tramo cuenta solo a quienes llegaron a sus dos eventos.
|
||||
Las medianas de los tramos no tienen que sumar el tiempo acumulado.
|
||||
}
|
||||
</p>
|
||||
}
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de tiempos de la ruta del tamizaje" tabindex="0">
|
||||
<table><caption>Días por evento en {{ m.period ? periodLabel(m.period) : 'el periodo' }}</caption>
|
||||
<thead><tr><th scope="col">Evento</th><th scope="col">Desde la toma</th><th scope="col">Desde el paso anterior</th></tr></thead>
|
||||
<tbody>@for (row of m.rows; track row.step.id) {
|
||||
<tr><th scope="row">{{ row.step.label }}</th><td>{{ cellText(row.fromSample) }}</td><td>{{ cellText(row.fromPrevious) }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</section>
|
||||
@@ -1,13 +0,0 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.route { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
.controls { display: flex; flex-wrap: wrap; gap: 1rem 1.5rem; align-items: center; margin-block: .75rem; }
|
||||
.note { color: var(--issste-text-secondary); max-width: 70ch; }
|
||||
app-plotly-chart { --plot-height: 360px; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.table-scroll { overflow: auto; max-height: 28rem; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
@@ -1,112 +0,0 @@
|
||||
// What this module covers: the screening route component: when it loads, the seven requests it makes, what it draws for
|
||||
// each view and period, and its empty, error and incompatible states. The model and the figure have their own spec
|
||||
// (`screening-route.spec.ts`).
|
||||
// Fixtures: `payload`, synthetic C3r /datos shaped like /cacu/indicadores/<id>/datos; `ChartStub` stands for the chart.
|
||||
import { Component, input } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadorScreeningRoute } from './indicador-screening-route';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { ROUTE_IDS } from './screening-route';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); }
|
||||
|
||||
const row = (periodo: string, n: number, q1: number, mediana: number, q3: number, suprimido = 0) =>
|
||||
({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido, unidad: 'dias' });
|
||||
const MEDIANAS: Record<string, number> = {
|
||||
cacu_eu_tiempo_reporte: 7.9, cacu_dias_toma_colposcopia: 35.7, cacu_dias_resultado_colposcopia: 27.8, cacu_dias_toma_biopsia: 52.1,
|
||||
cacu_dias_colposcopia_biopsia: 16.4, cacu_dias_toma_diagnostico: 18.4, cacu_dias_biopsia_diagnostico: 12.8,
|
||||
};
|
||||
const payload = (id: string, suprimido = 0): IndicadorDatos => ({
|
||||
id, contrato: 'C3r', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'], version: '1',
|
||||
filas: [row('2025-S1', 100, 3, MEDIANAS[id] + 1, MEDIANAS[id] + 9, suprimido), row('2025-S2', 120, 4, MEDIANAS[id], MEDIANAS[id] + 8, suprimido)],
|
||||
});
|
||||
|
||||
describe('Ruta del tamizaje: componente', () => {
|
||||
let f: ReturnType<typeof TestBed.createComponent<IndicadorScreeningRoute>>;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorScreeningRoute], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorScreeningRoute, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
f = TestBed.createComponent(IndicadorScreeningRoute);
|
||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('tema', 'claro');
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.match(() => true); http.verify(); });
|
||||
// The shared request queue runs a few at a time: answer in waves until nothing is left.
|
||||
function responder(entrega: (id: string) => IndicadorDatos = id => payload(id)) {
|
||||
const vistos: string[] = [];
|
||||
for (;;) {
|
||||
const pendientes = http.match(r => r.url.endsWith('/datos'));
|
||||
if (!pendientes.length) return vistos;
|
||||
for (const r of pendientes) { const id = r.request.url.split('/').at(-2)!; vistos.push(id); r.flush(entrega(id)); }
|
||||
f.detectChanges();
|
||||
}
|
||||
}
|
||||
const charts = () => f.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
|
||||
it('carga diferida; pide las siete medidas; dibuja una gráfica y cambia de vista y de periodo sin otra petición', () => {
|
||||
// Pins down: nothing is requested while hidden, each of the seven measures is requested once, the view and the period
|
||||
// are chosen without new requests, and the theme redraws the same data. Fails if the region loads before it is
|
||||
// visible, a measure is missing or repeated, or a control triggers a request.
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
f.componentRef.setInput('visible', true); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('loading');
|
||||
expect(responder().sort()).toEqual([...ROUTE_IDS].sort());
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
expect(charts()).toHaveLength(1);
|
||||
expect(charts()[0].figure()).toBe(f.componentInstance.figure());
|
||||
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeUndefined();
|
||||
f.componentInstance.selectView('steps'); f.detectChanges();
|
||||
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeDefined();
|
||||
f.componentInstance.selectPeriod('2025-S1'); f.detectChanges();
|
||||
expect(f.componentInstance.model()!.period).toBe('2025-S1');
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.figure()!.layout['paper_bgcolor']).toBe('#081839');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('la tabla de valores publicados dice la mediana de cada evento y el estado si no hay caja', () => {
|
||||
// Fails if the table drops an event or shows a suppressed box as a number.
|
||||
f.detectChanges();
|
||||
responder(id => (id === 'cacu_dias_toma_biopsia' ? payload(id, 1) : payload(id)));
|
||||
const text = f.nativeElement.querySelector('table').textContent as string;
|
||||
expect(text).toContain('Resultado de citología');
|
||||
expect(text).toContain('mediana 35.7');
|
||||
expect(text).toContain('Suprimido');
|
||||
});
|
||||
it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => {
|
||||
// Fails if an empty route draws a chart or hides the reason.
|
||||
f.detectChanges();
|
||||
responder(id => payload(id, 1));
|
||||
expect(f.componentInstance.status()).toBe('empty');
|
||||
expect(charts()).toHaveLength(0);
|
||||
expect(f.nativeElement.textContent).toContain('No hay tiempos publicados');
|
||||
});
|
||||
it('un fallo del servicio se anuncia como error y reintentar vuelve a pedir', () => {
|
||||
// Fails if an error leaves a stale chart, hides the alert, or retry does not request again.
|
||||
f.detectChanges();
|
||||
http.match(r => r.url.endsWith('/datos'))[0].flush({}, { status: 500, statusText: 'Server Error' });
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('error');
|
||||
expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
expect(charts()).toHaveLength(0);
|
||||
http.match(() => true); // the other requests of the first try were cancelled with it
|
||||
f.componentInstance.retry(); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('loading');
|
||||
expect(responder().length).toBe(ROUTE_IDS.length);
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('datos de otro contrato quedan incompatibles y no se dibujan', () => {
|
||||
// Fails if a payload that is not a duration is drawn as one.
|
||||
f.detectChanges();
|
||||
responder(id => (id === 'cacu_dias_toma_biopsia' ? { ...payload(id), contrato: 'C1' } : payload(id)));
|
||||
expect(f.componentInstance.status()).toBe('incompatible');
|
||||
expect(charts()).toHaveLength(0);
|
||||
expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,86 +0,0 @@
|
||||
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { forkJoin, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { etiquetaPeriodo } from './indicadores-historico-figures';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { ROUTE_IDS, RouteIncompatible, RouteView, routeCellText, routeFigure, routeHasData, routeModel } from './screening-route';
|
||||
|
||||
/** Days along the screening route, from the sample to each event, as horizontal bars: cumulative or step by step. */
|
||||
@Component({
|
||||
selector: 'app-indicador-screening-route',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
templateUrl: './indicador-screening-route.html',
|
||||
styleUrl: './indicador-screening-route.scss',
|
||||
})
|
||||
export class IndicadorScreeningRoute {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly tipo = input<TipoPeriodo>('semestre');
|
||||
/** The measures load once the region is visible. */
|
||||
readonly visible = input(true);
|
||||
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
readonly message = signal('');
|
||||
readonly view = signal<RouteView>('cumulative');
|
||||
readonly requestedPeriod = signal<string | undefined>(undefined);
|
||||
private readonly payloads = signal<Record<string, IndicadorDatos> | undefined>(undefined);
|
||||
readonly model = computed(() => {
|
||||
const data = this.payloads();
|
||||
return data ? routeModel(data, this.tipo(), this.requestedPeriod()) : undefined;
|
||||
});
|
||||
readonly figure = computed(() => {
|
||||
const model = this.model();
|
||||
return model && routeHasData(model) ? routeFigure(model, this.view(), this.tema()) : undefined;
|
||||
});
|
||||
readonly periodLabel = etiquetaPeriodo;
|
||||
readonly cellText = routeCellText;
|
||||
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private subscription?: Subscription;
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const dominio = this.dominio(), tipo = this.tipo();
|
||||
if (!this.visible()) { this.status.set('deferred'); return; }
|
||||
untracked(() => this.load(dominio, tipo));
|
||||
});
|
||||
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
|
||||
}
|
||||
|
||||
retry() { this.load(this.dominio(), this.tipo()); }
|
||||
selectPeriod(period: string) { this.requestedPeriod.set(period); }
|
||||
selectView(view: RouteView) { this.view.set(view); }
|
||||
|
||||
private load(dominio: Dominio, tipo: TipoPeriodo) {
|
||||
this.subscription?.unsubscribe();
|
||||
this.payloads.set(undefined);
|
||||
this.status.set('loading');
|
||||
const requests = Object.fromEntries(ROUTE_IDS.map(id => [id, this.snapshots.datos(dominio, id, tipo)]));
|
||||
this.subscription = forkJoin(requests).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: data => {
|
||||
try {
|
||||
const model = routeModel(data, tipo, this.requestedPeriod());
|
||||
this.payloads.set(data);
|
||||
this.status.set(routeHasData(model) ? 'ready' : 'empty');
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => this.failure(error),
|
||||
});
|
||||
}
|
||||
|
||||
private failure(error: unknown) {
|
||||
this.payloads.set(undefined);
|
||||
this.message.set(error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof RouteIncompatible ? error.message : httpMessage(error));
|
||||
this.status.set(error instanceof RouteIncompatible || (error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError))
|
||||
? 'incompatible' : 'error');
|
||||
}
|
||||
}
|
||||
@@ -1,223 +0,0 @@
|
||||
// What this module covers: CaCu's compositions as the page reads them from FHIR once the Measure publishes category
|
||||
// groups and the reports their crossed strata: the groups, the rows by stratum (codes, captions, explicit zeros, totals),
|
||||
// the contract errors that must never become zeros, the EU7 view by follow-up status and the histopathological
|
||||
// confirmation, a period without units, and that measures without groups (CaMa's) read unchanged.
|
||||
// Fixtures: `fixtures/cacu_fhir_measures.json` (the Measure bundle `GET /cacu/fhir/Measure` returns with the groups
|
||||
// declared) and `fixtures/cacu_fhir_reportes_estratos.json` (real `GET /cacu/fhir/MeasureReport` answers of EU7 and the
|
||||
// confirmation for 2025-S2, with units, and 2021-S1, without; synthetic data of the isolated installation, N_CACU=300).
|
||||
import { Bundle, resources } from './fhir';
|
||||
import { categorias, datosDeReportes, gruposDeCategoria, indicadorDeMeasure, Measure, Report } from './indicadores-fhir';
|
||||
import { barras, dona, modelo } from './indicadores-eu7-escenario';
|
||||
import { donaConfirmacion, modeloConfirmacion } from './indicadores-confirmacion-citologia';
|
||||
import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import measuresData from './fixtures/cacu_fhir_measures.json';
|
||||
import reportsData from './fixtures/cacu_fhir_reportes_estratos.json';
|
||||
import camaData from './fixtures/cama_fhir_measures.json';
|
||||
|
||||
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
|
||||
const measure = (id: string) => measures.find(m => m.id === id)!;
|
||||
const answers = reportsData as unknown as Record<string, Bundle>;
|
||||
const reports = (key: string) => resources(answers[key], 'MeasureReport') as Report[];
|
||||
const EU7 = 'CACU-EU7', CONF = 'CACU-CONFIRMACION-CITOLOGIA';
|
||||
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
|
||||
type Fila = Record<string, unknown>;
|
||||
const n = (filas: Fila[], estrato: string | null, categoria: string) =>
|
||||
filas.filter(f => f['estrato'] === estrato && f['categoria'] === categoria).reduce((s, f) => s + (f['n'] as number), 0);
|
||||
|
||||
describe('Grupos de categoría publicados por la Measure', () => {
|
||||
it('EU7 y la confirmación leen el grupo de cada categoría y los nombres de los grupos, en su orden', () => {
|
||||
// Pins down: the optional `grupo` inside each `categoria` and the `categoria-grupo` captions reach the page as the
|
||||
// EU7 and confirmation views read them; «Sin biopsia aún» keeps no group. Fails if either is dropped or reordered.
|
||||
expect(Object.fromEntries(Object.entries(categorias(measure(EU7))).map(([c, v]) => [c, v.grupo]))).toEqual({
|
||||
NORMAL: 'NO_ANORMAL', 'ASC-US': 'ANORMAL', LIEBG: 'ANORMAL', 'ASC-H': 'ANORMAL', LIEAG: 'ANORMAL', CIS: 'ANORMAL', SIN_DATO: 'SIN_DATO' });
|
||||
expect(Object.entries(gruposDeCategoria(measure(EU7)))).toEqual([
|
||||
['NO_ANORMAL', 'Sin anomalía'], ['ANORMAL', 'Anormal'], ['SIN_DATO', 'Sin dato']]);
|
||||
expect(categorias(measure(CONF))['SIN_BIOPSIA'].grupo).toBeNull();
|
||||
expect(gruposDeCategoria(measure(CONF))).toEqual({ NO_ANORMAL: 'Menor que LIEAG', ANORMAL: 'LIEAG o más', SIN_DATO: 'Biopsia sin grado' });
|
||||
});
|
||||
|
||||
it('una Measure sin grupos se lee como antes: sin grupo por categoría y sin grupos de categoría', () => {
|
||||
// Pins down: groups are opt-in. CaMa's Measures declare none, so every category keeps `grupo: null` and the data
|
||||
// carry no `grupos_de_categoria`. Fails if reading the new extensions changes what CaMa's views receive.
|
||||
const cama = resources(camaData as unknown as Bundle, 'Measure') as Measure[];
|
||||
for (const m of cama) {
|
||||
expect(Object.values(categorias(m)).every(c => c.grupo === null), m.id).toBe(true);
|
||||
expect(gruposDeCategoria(m), m.id).toEqual({});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Composiciones por estrato desde el estratificador cruzado', () => {
|
||||
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre');
|
||||
const porEstatus = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' });
|
||||
|
||||
it('cada estrato tiene una fila por categoría declarada, con su código y su etiqueta, y ceros explícitos', () => {
|
||||
// Pins down: one row per (status, category), the status code as the value and its caption from the report, and a
|
||||
// zero for every cell FHIR doesn't list (the report is complete). Fails if a cell goes missing or a code is replaced.
|
||||
const valores = porEstatus['valores_estrato'] as string[];
|
||||
expect(valores.length).toBeGreaterThan(0);
|
||||
expect(porEstatus.filas.length).toBe(valores.length * Object.keys(porEstatus['categorias'] as object).length);
|
||||
expect((porEstatus['etiquetas_estrato'] as Record<string, string>)['PRE_COLPOSCOPIA']).toBe('Pre colposcopia');
|
||||
const listadas = (reports('eu7_2025S2')[0].group![0].stratifier as { code: unknown[]; stratum: unknown[] }[])
|
||||
.find(s => s.code.length === 2 && JSON.stringify(s.code[0]).includes('estatus_seguimiento'))!.stratum.length;
|
||||
expect(porEstatus.filas.filter(f => f['n'] === 0).length).toBe(porEstatus.filas.length - listadas);
|
||||
expect(porEstatus.filas.every(f => f['suprimido'] === 0 && f['grupo'] === 'TOTAL')).toBe(true);
|
||||
});
|
||||
|
||||
it('los conteos por estrato suman los de la distribución general, categoría por categoría y en total', () => {
|
||||
// Pins down: the strata partition the period's units (112 patients in 2025-S2) and each category adds up across
|
||||
// them; the per-stratum totals are published. Fails if the crossed stratifier is read with a shift or a loss.
|
||||
const totales = porEstatus['totales_estrato'] as { n: number }[];
|
||||
expect(totales.reduce((s, t) => s + t.n, 0)).toBe(112);
|
||||
for (const categoria of Object.keys(general['categorias'] as object)) {
|
||||
const porEstratos = (porEstatus['valores_estrato'] as string[]).reduce((s, e) => s + n(porEstatus.filas, e, categoria), 0);
|
||||
expect(porEstratos, categoria).toBe(n(general.filas, null, categoria));
|
||||
}
|
||||
const porEdad = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'grupo_edad' });
|
||||
expect((porEdad['totales_estrato'] as { n: number }[]).reduce((s, t) => s + t.n, 0)).toBe(112);
|
||||
expect((porEdad['etiquetas_estrato'] as Record<string, string>)['25-34']).toBe('25-34');
|
||||
});
|
||||
|
||||
it('una celda que falta, una categoría no declarada o un estratificador ausente son errores de contrato, no ceros', () => {
|
||||
// Pins down: what can't be read as a complete partition fails loudly: cells that no longer add up to the units, a
|
||||
// category the Measure doesn't declare, and a period with units but without the crossed stratifier. Fails if any
|
||||
// of them is silently turned into a zero.
|
||||
const sinCelda = clone(reports('eu7_2025S2'));
|
||||
const cruzado = sinCelda[0].group![0].stratifier!.find(s => Array.isArray(s.code) && s.code.length === 2) as unknown as { stratum: unknown[] };
|
||||
cruzado.stratum.shift();
|
||||
expect(() => datosDeReportes(measure(EU7), sinCelda, 'semestre', { estrato: 'estatus_seguimiento' }))
|
||||
.toThrowError('Los conteos por estrato no suman las unidades del periodo');
|
||||
const ajena = clone(reports('eu7_2025S2'));
|
||||
const celda = (ajena[0].group![0].stratifier!.find(s => Array.isArray(s.code) && s.code.length === 2) as unknown as
|
||||
{ stratum: { component: { value: { coding: { code: string }[] } }[] }[] }).stratum[0];
|
||||
celda.component[1].value.coding[0].code = 'GLANDULAR';
|
||||
expect(() => datosDeReportes(measure(EU7), ajena, 'semestre', { estrato: 'estatus_seguimiento' }))
|
||||
.toThrowError('Categoría no declarada en el estrato');
|
||||
const sinCruce = clone(reports('eu7_2025S2'));
|
||||
sinCruce[0].group![0].stratifier = sinCruce[0].group![0].stratifier!.slice(0, 1);
|
||||
expect(() => datosDeReportes(measure(EU7), sinCruce, 'semestre', { estrato: 'estatus_seguimiento' }))
|
||||
.toThrowError('Dimensión no admitida');
|
||||
});
|
||||
|
||||
it('un periodo sin unidades no tiene filas por estrato y no es un error', () => {
|
||||
// Pins down: 2021-S1 has no patients; its report has nothing to cross, so the stratified data carry the period but
|
||||
// no rows, and the general distribution is all zeros. Fails if an empty period is read as an error or as data.
|
||||
const vacio = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre', { estrato: 'estatus_seguimiento' });
|
||||
expect(vacio.periodos).toEqual(['2021-S1']);
|
||||
expect(vacio.filas).toEqual([]);
|
||||
const generalVacio = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre');
|
||||
expect(generalVacio.filas.every(f => f['n'] === 0)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vistas propias de CaCu con los datos de FHIR', () => {
|
||||
it('EU7: el modelo por escenario se construye y la dona y las barras tienen datos', () => {
|
||||
// Pins down: with the groups and the rows by follow-up status, EU7's coordinated view builds its model (112
|
||||
// patients in groups Anormal / Sin anomalía, «Sin dato» apart) and both figures have traces. Fails if the view
|
||||
// falls back to «incompatible» with the data FHIR publishes.
|
||||
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
|
||||
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||
const m = modelo(general, escenarios, '2025-S2');
|
||||
expect(m.vacio).toBe(false);
|
||||
expect(m.grupos.map(g => g.etiqueta)).toEqual(['Sin anomalía', 'Anormal']);
|
||||
expect(m.escenarios.map(e => e.etiqueta)).toContain('Pre colposcopia');
|
||||
expect(dona(m, {}, 'claro').data.length).toBeGreaterThan(0);
|
||||
expect(barras(m, {}, 'claro').data.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('EU7: el texto emergente de cada sector de la dona nombra la categoría, los pacientes y el porcentaje', () => {
|
||||
// Pins down: both rings carry one pre-formatted hover text per sector («2 pacientes, 2.1 % del total con
|
||||
// resultado» for LIEAG, 2 of the 95 patients with a result) and their template reads it by name. A pie wraps
|
||||
// `customdata` in an extra array, so a template that indexes it printed «2,2.1 pacientes, - %». Fails if the
|
||||
// template goes back to indexing `customdata` or a sector loses its text.
|
||||
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
|
||||
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||
const m = modelo(general, escenarios, '2025-S2');
|
||||
const anillos = dona(m, {}, 'claro').data.filter(t => t['name'] === 'grupos' || t['name'] === 'categorias');
|
||||
expect(anillos.length).toBe(2);
|
||||
for (const anillo of anillos) {
|
||||
expect(anillo['hovertemplate']).not.toContain('customdata');
|
||||
expect(anillo['hovertemplate']).toContain('%{hovertext}');
|
||||
expect((anillo['hovertext'] as string[]).length).toBe((anillo['values'] as number[]).length);
|
||||
}
|
||||
const exterior = anillos.find(t => t['name'] === 'categorias')!;
|
||||
const etiquetas = exterior['labels'] as string[], textos = exterior['hovertext'] as string[];
|
||||
expect(m.total).toBe(95);
|
||||
expect(textos[etiquetas.indexOf('LIEAG')]).toBe('2 pacientes, 2.1 % del total con resultado');
|
||||
expect(textos.every(t => /^\d+ pacientes, \d+(\.\d)? % del total con resultado$/.test(t))).toBe(true);
|
||||
});
|
||||
|
||||
it('EU7: un periodo sin pacientes es un periodo vacío, no una respuesta incompatible', () => {
|
||||
// Pins down: for 2021-S1 FHIR publishes the general distribution as explicit zeros and no scenario; the view reads
|
||||
// it as empty. A positive count without scenarios is still rejected. Fails if an empty period shows
|
||||
// «incompatible», or if a real mismatch is hidden as empty.
|
||||
const general = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre') as IndicadorDatos;
|
||||
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||
const m = modelo(general, escenarios, '2021-S1');
|
||||
expect(m.vacio).toBe(true);
|
||||
expect(m.escenarios).toEqual([]);
|
||||
const conPacientes = clone(general);
|
||||
conPacientes.filas[0]['n'] = 3;
|
||||
expect(() => modelo(conPacientes, escenarios, '2021-S1')).toThrow(/No hay escenarios que correspondan/);
|
||||
});
|
||||
|
||||
it('EU7: el mismo reporte servido en dos respuestas es una sola procedencia aunque cambie la hora de la respuesta', () => {
|
||||
// Pins down: the view asks for the general and the stratified data in two requests; the WebApi serves the same
|
||||
// stored report (same id and cut-off) with each response's own `date`. That is one provenance; without report ids,
|
||||
// a different generation time still means different reports. Fails if the view rejects FHIR's two responses of one
|
||||
// report, or accepts two anonymous answers generated apart.
|
||||
const segunda = clone(reports('eu7_2025S2'));
|
||||
segunda[0].date = '2099-01-01T00:00:00Z';
|
||||
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
|
||||
const escenarios = datosDeReportes(measure(EU7), segunda, 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||
expect(modelo(general, escenarios, '2025-S2').vacio).toBe(false);
|
||||
const anonimo = (d: IndicadorDatos) => ({ ...d, reportes: (d['reportes'] as Fila[]).map(r => ({ ...r, report_id: null })) }) as IndicadorDatos;
|
||||
expect(() => modelo(anonimo(general), anonimo(escenarios), '2025-S2')).toThrow(/reportes distintos/);
|
||||
});
|
||||
|
||||
it('confirmación: la tabla por citología y los dos grupos de grados se construyen', () => {
|
||||
// Pins down: the confirmation by cytology result builds its table from the crossed stratifier (6 patients in
|
||||
// 2025-S2), with its two groups and LIEAG's as the base view, and «Sin biopsia aún» / «Biopsia sin grado»
|
||||
// apart. Fails if the view can't read FHIR's groups or strata.
|
||||
const datos = datosDeReportes(measure(CONF), reports('confirmacion_2025S2'), 'semestre', { estrato: 'citologia_alto_grado' }) as IndicadorDatos;
|
||||
const m = modeloConfirmacion(datos, '2025-S2');
|
||||
expect(m.vacio).toBe(false);
|
||||
expect(m.grupos.map(g => g.etiqueta)).toEqual(['Menor que LIEAG', 'LIEAG o más']);
|
||||
expect(m.base).toBe('ANORMAL');
|
||||
expect(m.aparte.map(a => a.id).sort()).toEqual(['SIN_BIOPSIA', 'SIN_DATO']);
|
||||
expect((datos['totales_estrato'] as { n: number }[]).reduce((s, t) => s + t.n, 0)).toBe(6);
|
||||
});
|
||||
|
||||
it('confirmación: el texto emergente de cada sector de la dona nombra el grado, las mujeres con biopsia y el porcentaje', () => {
|
||||
// Pins down: both rings carry one pre-formatted hover text per sector («3 mujeres con biopsia, 75.0 %» for the
|
||||
// grades LIEAG o más… of the 4 women with a biopsy in 2025-S2) and their template reads it by name, because a pie
|
||||
// wraps `customdata` in an extra array and indexing it printed «3,75.0 % mujeres con biopsia, -». Fails if the
|
||||
// template goes back to indexing `customdata` or a sector loses its text.
|
||||
const datos = datosDeReportes(measure(CONF), reports('confirmacion_2025S2'), 'semestre', { estrato: 'citologia_alto_grado' }) as IndicadorDatos;
|
||||
const m = modeloConfirmacion(datos, '2025-S2');
|
||||
const anillos = donaConfirmacion(m, { grupo: m.base }, 'claro').data.filter(t => t['name'] === 'grupos' || t['name'] === 'categorias');
|
||||
expect(anillos.length).toBe(2);
|
||||
for (const anillo of anillos) {
|
||||
expect(anillo['hovertemplate']).not.toContain('customdata');
|
||||
expect(anillo['hovertemplate']).toContain('%{hovertext}');
|
||||
expect((anillo['hovertext'] as string[]).length).toBe((anillo['values'] as number[]).length);
|
||||
}
|
||||
const exterior = anillos.find(t => t['name'] === 'categorias')!;
|
||||
const etiquetas = exterior['labels'] as string[], textos = exterior['hovertext'] as string[];
|
||||
expect(textos[etiquetas.indexOf('LIEAG (CIN 2 y 3)')]).toBe('3 mujeres con biopsia, 75.0 %');
|
||||
expect(textos.every(t => /^\d+ mujeres con biopsia, \d+(\.\d)? %$/.test(t))).toBe(true);
|
||||
});
|
||||
|
||||
it('la compuerta de EU7 usa los estratos que declara la Measure y no activa filtros para otras composiciones', () => {
|
||||
// Pins down: EU7 declares `estatus_seguimiento`, so its view opens without local filters; the stratified
|
||||
// capabilities of the generic figure panel stay empty for every CaCu and CaMa measure. Fails if the gate is lost
|
||||
// or if filters appear for compositions that never had them.
|
||||
const eu7 = indicadorDeMeasure(measure(EU7));
|
||||
expect(declaraEstrato(eu7, 'estatus_seguimiento')).toBe(true);
|
||||
expect(declaraEstrato(indicadorDeMeasure(measure(CONF)), 'estatus_seguimiento')).toBe(false);
|
||||
expect(declaraEstrato(indicadorDeMeasure(measure('CACU-EU13')), 'estatus_seguimiento')).toBe(false);
|
||||
const cama = resources(camaData as unknown as Bundle, 'Measure') as Measure[];
|
||||
for (const item of [...measures, ...cama].map(indicadorDeMeasure)) expect(stratifiedCapabilities(item), item.id).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,167 +0,0 @@
|
||||
// What this module covers: how CaCu's FHIR measures reach the indicator page: the page's id of each measure, and what the
|
||||
// initial-period anchor (`cacu_eu7`) makes of a C2 Measure that publishes, or does not publish, its category labels.
|
||||
// The Measure and the report are synthetic and minimal: the shape of `GET /cacu/fhir/Measure` and `/MeasureReport`.
|
||||
import { Bundle, resources } from './fhir';
|
||||
import { Measure, Report, datosDeReportes, indicadorDeMeasure, indicadorId } from './indicadores-fhir';
|
||||
import { c2Figure } from './indicadores-c2-adapter';
|
||||
import { FigureSelection } from './indicadores.models';
|
||||
import measuresData from './fixtures/cacu_fhir_measures.json';
|
||||
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
|
||||
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { historicoFigura } from './indicadores-historico-figures';
|
||||
|
||||
const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition';
|
||||
const ENDPOINT = ['CACU-CONFIRMACION-CITOLOGIA', 'CACU-DIAS-TOMA-DIAGNOSTICO', 'CACU-EU-TIEMPO-REPORTE', 'CACU-EU13', 'CACU-EU7',
|
||||
'CACU-RIESGO-BANDA', 'IND1'];
|
||||
const etiqueta = (codigo: string, texto: string, color: string) => ({ url: `${STRUCTURE}/categoria`, extension: [
|
||||
{ url: 'codigo', valueCode: codigo }, { url: 'etiqueta', valueString: texto }, { url: 'color', valueString: color }] });
|
||||
const eu7 = (extra: object[]): Measure => ({
|
||||
resourceType: 'Measure', id: 'CACU-EU7', version: '0.3.3', title: 'Distribución de resultados citológicos',
|
||||
subjectCodeableConcept: { coding: [{ code: 'paciente' }] },
|
||||
extension: [{ url: `${STRUCTURE}/contrato`, valueCode: 'C2' }, { url: `${STRUCTURE}/tipos-periodo`, valueCode: 'semestre' }, ...extra],
|
||||
group: [{ code: { coding: [{ code: 'TOTAL' }] }, population: [], stratifier: [{ code: [{ coding: [{ code: 'resultado' }] }], stratum: [] }] }],
|
||||
} as unknown as Measure);
|
||||
const reporte = (): Report => ({
|
||||
resourceType: 'MeasureReport', id: 'CACU-EU7-1', period: { start: '2025-07-01', end: '2025-12-31' },
|
||||
group: [{ code: { coding: [{ code: 'TOTAL' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 12 }],
|
||||
stratifier: [{ code: [{ coding: [{ code: 'resultado' }] }], stratum: [
|
||||
{ value: { coding: [{ code: 'NORMAL' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 8 }] },
|
||||
{ value: { coding: [{ code: 'ASC-US' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 3 }] },
|
||||
{ value: { coding: [{ code: 'SIN_DATO' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 1 }] },
|
||||
] }] }],
|
||||
} as unknown as Report);
|
||||
const aplicado: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 0 };
|
||||
const ancla = KPI_BY_DOMAIN.cacu[0];
|
||||
|
||||
describe('Identificadores de CaCu entre FHIR y la página', () => {
|
||||
it('cada medida que publica el WebApi tiene el id de minúsculas que usa la página y ninguno se repite', () => {
|
||||
// Pins down: the table covers the seven measures `GET /cacu/fhir/Measure` lists and the ids are unique. Fails if a
|
||||
// measure is published without a correspondence (it would come back as `CACU_X`, which no card matches) or two
|
||||
// measures collapse into one page id.
|
||||
const ids = ENDPOINT.map(indicadorId);
|
||||
expect(ids.sort()).toEqual(['cacu_confirmacion_citologia', 'cacu_dias_toma_diagnostico', 'cacu_eu13', 'cacu_eu7',
|
||||
'cacu_eu_tiempo_reporte', 'cacu_riesgo_banda', 'ind1']);
|
||||
expect(ENDPOINT.every(id => Object.hasOwn(CACU_MEASURE_IDS, id))).toBe(true);
|
||||
});
|
||||
|
||||
it('los ids que la página busca (ancla, tiempos, confirmación) existen entre los publicados', () => {
|
||||
// Pins down: the page's own constants (the KPI definitions of CaCu, the confirmation card's id and the result-time KPI)
|
||||
// are values of the table. Fails if the page renames one of them without the table: the catalog would keep `CACU_EU7`
|
||||
// while the page looks for `cacu_eu7`, and no initial period would be searched.
|
||||
const publicados = Object.values(CACU_MEASURE_IDS);
|
||||
for (const id of [...KPI_BY_DOMAIN.cacu.map(k => k.id), CACU_RESULTADO_KPI.id, ID_CONFIRMACION, 'cacu_eu7']) {
|
||||
expect(publicados).toContain(id);
|
||||
}
|
||||
});
|
||||
|
||||
it('el catálogo de una medida de CaCu lleva el id de la página y sus figuras', () => {
|
||||
// Pins down: the catalog entry takes the page id and the `figuras` the Measure publishes. Fails if the mapper stops
|
||||
// using the CaCu table or drops the figures.
|
||||
const item = indicadorDeMeasure(eu7([{ url: `${STRUCTURE}/figuras`, valueString: 'fig_c2_donas' },
|
||||
{ url: `${STRUCTURE}/figuras`, valueString: 'fig_c2_barras' }]));
|
||||
expect(item.id).toBe('cacu_eu7');
|
||||
expect(item.figuras).toEqual(['fig_c2_donas', 'fig_c2_barras']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('El ancla de CaCu con y sin etiquetas de categoría publicadas', () => {
|
||||
it('con etiquetas, los conteos del periodo son filas y el ancla muestra el total', () => {
|
||||
// Pins down: a C2 Measure that publishes its categories gives one row per category and the anchor KPI the sum
|
||||
// (12 patients), so the initial-period search can stop on the period. Fails if the rows stop following the Measure's
|
||||
// categories or the anchor no longer accepts a CaCu partition.
|
||||
const measure = eu7([etiqueta('NORMAL', 'Normal', '#9DBFE3'), etiqueta('ASC-US', 'ASC-US', '#2F6DB3'),
|
||||
etiqueta('SIN_DATO', 'Sin dato', '#C9CDD2')]);
|
||||
const datos = datosDeReportes(measure, [reporte()], 'semestre');
|
||||
expect(datos.filas.map(f => [f['categoria'], f['n']])).toEqual([['NORMAL', 8], ['ASC-US', 3], ['SIN_DATO', 1]]);
|
||||
const resultado = kpiResult(datos, ancla, 'cacu', aplicado);
|
||||
expect(resultado.state).toBe('Disponible');
|
||||
expect(resultado.value).toBe(12);
|
||||
});
|
||||
|
||||
it('sin etiquetas, el mismo reporte no deja filas y el ancla no encuentra periodo', () => {
|
||||
// Pins down the failure the Measure without `categoria` causes: the report counts 12 patients, but with no declared
|
||||
// category there is no row, so the anchor reads «Sin filas utilizables» and the initial period stays empty. Fails
|
||||
// if the page starts inventing categories from the report (it must keep asking the Measure).
|
||||
const datos = datosDeReportes(eu7([]), [reporte()], 'semestre');
|
||||
expect(datos.filas).toEqual([]);
|
||||
expect(kpiResult(datos, ancla, 'cacu', aplicado).state).toBe('Sin filas utilizables');
|
||||
});
|
||||
});
|
||||
|
||||
// `fixtures/cacu_fhir_measures.json` is the Measure bundle `GET /cacu/fhir/Measure` returns from the dbt definitions once
|
||||
// CaCu declares its figures and category labels (WebApi with the figures and labels declared in Transformation); the reports are built
|
||||
// from the categories each Measure declares, as the WebApi would count them.
|
||||
const publicadas = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
|
||||
const medida = (id: string) => publicadas.find(m => m.id === id)!;
|
||||
const declaradas = (m: Measure) => (m.extension ?? []).filter(e => e.url.endsWith('/categoria'))
|
||||
.map(e => e.extension!.find(x => x.url === 'codigo')!.valueCode!);
|
||||
const codigo = (c: string) => ({ coding: [{ code: c }] });
|
||||
const reporteDe = (m: Measure, conteos: number[]): Report => ({
|
||||
resourceType: 'MeasureReport', id: `${m.id}-1`, period: { start: '2025-07-01', end: '2025-12-31' },
|
||||
group: [{ code: codigo('TOTAL'), population: [{ code: codigo('initial-population'), count: conteos.reduce((a, b) => a + b, 0) }],
|
||||
stratifier: [{ code: [codigo('categoria')], stratum: declaradas(m).map((c, i) => ({
|
||||
value: codigo(c), population: [{ code: codigo('initial-population'), count: conteos[i] }] })) }] }],
|
||||
} as unknown as Report);
|
||||
|
||||
describe('Las medidas de CaCu como las publica el WebApi con figuras y etiquetas declaradas', () => {
|
||||
it('el catálogo ofrece las figuras que cada contrato sabe dibujar y deja sin ellas las que aún no', () => {
|
||||
// Pins down: C2 measures offer the donut and the bars, the two C3r the box plot, and the C1 and the risk bands none
|
||||
// yet (no declared figure the renderer supports). Fails if a CaCu measure loses its figures or gains one that was not
|
||||
// checked against the renderer.
|
||||
const figuras = Object.fromEntries(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m).figuras]));
|
||||
expect(figuras).toEqual({
|
||||
cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_toma_diagnostico: ['fig_c3r_caja'],
|
||||
cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'],
|
||||
cacu_riesgo_banda: [], ind1: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('con las etiquetas publicadas, el ancla muestra el total y el donut y las barras se dibujan', () => {
|
||||
// Pins down the whole chain for the anchor: published categories -> rows -> «Pacientes evaluadas» total (16) ->
|
||||
// supported C2 donut and bars. Fails if the page cannot read what the WebApi publishes for CaCu's distribution.
|
||||
const eu7 = medida('CACU-EU7');
|
||||
const datos = datosDeReportes(eu7, [reporteDe(eu7, [8, 3, 2, 1, 1, 0, 1])], 'semestre');
|
||||
const resultado = kpiResult(datos, ancla, 'cacu', aplicado);
|
||||
expect(resultado).toMatchObject({ state: 'Disponible', value: 16 });
|
||||
for (const figura of ['fig_c2_donas', 'fig_c2_barras']) {
|
||||
const dibujo = c2Figure(datos, { dominio: 'cacu', indicador: 'cacu_eu7', figura, tipoPeriodo: 'semestre', tema: 'claro',
|
||||
periodos: ['2025-S2'] } as unknown as FigureSelection);
|
||||
expect(dibujo.status).toBe('supported');
|
||||
}
|
||||
});
|
||||
|
||||
it('un C1 publicado con su intervalo de Wilson llena la banda del histórico, en porcentaje', () => {
|
||||
// Pins down: the `ic-bajo` and `ic-alto` of a proportion's score (proportions) reach the rows as percentages and
|
||||
// the history trend draws them as its band. Fails if the bounds are read unconverted or dropped.
|
||||
const eu13 = medida('CACU-EU13');
|
||||
const cuenta = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
|
||||
const reporte13 = { resourceType: 'MeasureReport', id: 'CACU-EU13-1', period: { start: '2025-01-01', end: '2025-06-30' },
|
||||
group: [{ code: { coding: [{ code: 'principal' }] }, population: [cuenta('initial-population', 4), cuenta('denominator', 4), cuenta('numerator', 1)],
|
||||
measureScore: { value: 0.25, extension: [{ url: `${STRUCTURE}/ic-bajo`, valueDecimal: 0.0456 }, { url: `${STRUCTURE}/ic-alto`, valueDecimal: 0.6994 }] } }] } as unknown as Report;
|
||||
const datos = datosDeReportes(eu13, [reporte13], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ valor: 25, ic_bajo: 4.6, ic_alto: 69.9 });
|
||||
const banda = (historicoFigura(datos, 'claro').figure as unknown as { data: { name: string; y: number[] }[] }).data[0];
|
||||
expect(banda.name).toBe('Intervalo de confianza');
|
||||
expect(banda.y).toEqual([69.9, 4.6]);
|
||||
});
|
||||
|
||||
it('un C1 de CaCu cuyo grupo se llama principal dibuja su tendencia en el histórico', () => {
|
||||
// Pins down: the WebApi names the group of a proportion `principal`; the page reads it as `total`, the group the
|
||||
// history trend draws, for CaCu as for CaMa. Fails if the rows keep the group `principal` and the trend comes out
|
||||
// empty, with its period listed as having no data.
|
||||
const cuenta = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
|
||||
for (const id of ['CACU-EU13', 'IND1']) {
|
||||
const medida13 = medida(id);
|
||||
const reporte = { resourceType: 'MeasureReport', id: id + '-1', period: { start: '2025-01-01', end: '2025-06-30' },
|
||||
group: [{ code: { coding: [{ code: 'principal' }] }, population: [cuenta('initial-population', 4), cuenta('denominator', 4), cuenta('numerator', 1)],
|
||||
measureScore: { value: 0.25 } }] } as unknown as Report;
|
||||
const datos = datosDeReportes(medida13, [reporte], 'semestre');
|
||||
expect(datos.filas[0]['grupo']).toBe('total');
|
||||
const figura = historicoFigura(datos, 'claro');
|
||||
expect((figura.figure as unknown as { data: { y: number[] }[] }).data[1].y).toEqual([25]);
|
||||
expect(figura.sinDato).toEqual([]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
// How CaCu's FHIR measures map onto what the indicator page reads: the page's id of each measure.
|
||||
//
|
||||
// The WebApi names a measure `CACU-EU7`, `CACU-CONFIRMACION-CITOLOGIA` or `IND1`; the page, its KPI definitions, the
|
||||
// initial-period anchor and the cards that have a view of their own (`cacu_eu7`, `cacu_confirmacion_citologia`, the
|
||||
// time pair) all use the lower-case ids below. The generic rule would give `CACU_EU7`, which none of them matches, so
|
||||
// the correspondence is explicit, as CaMa's is, and a measure outside it keeps the generic rule.
|
||||
export const CACU_MEASURE_IDS: Readonly<Record<string, string>> = {
|
||||
'CACU-CONFIRMACION-CITOLOGIA': 'cacu_confirmacion_citologia',
|
||||
'CACU-DIAS-BIOPSIA-DIAGNOSTICO': 'cacu_dias_biopsia_diagnostico',
|
||||
'CACU-DIAS-COLPOSCOPIA-BIOPSIA': 'cacu_dias_colposcopia_biopsia',
|
||||
'CACU-DIAS-RESULTADO-COLPOSCOPIA': 'cacu_dias_resultado_colposcopia',
|
||||
'CACU-DIAS-TOMA-BIOPSIA': 'cacu_dias_toma_biopsia',
|
||||
'CACU-DIAS-TOMA-COLPOSCOPIA': 'cacu_dias_toma_colposcopia',
|
||||
'CACU-DIAS-TOMA-DIAGNOSTICO': 'cacu_dias_toma_diagnostico',
|
||||
'CACU-EU-TIEMPO-REPORTE': 'cacu_eu_tiempo_reporte',
|
||||
'CACU-EU13': 'cacu_eu13',
|
||||
'CACU-EU7': 'cacu_eu7',
|
||||
'CACU-RIESGO-BANDA': 'cacu_riesgo_banda',
|
||||
'IND1': 'ind1',
|
||||
};
|
||||
@@ -50,10 +50,10 @@ describe('Identificadores de CaMa entre FHIR y la página', () => {
|
||||
});
|
||||
|
||||
it('el id de una medida de otro dominio sigue la regla general', () => {
|
||||
// Pins down: only CaMa's table maps CaMa's measures, and TEA's keep `-` to `_` (CaCu has a table of its own, see
|
||||
// indicadores-cacu-fhir.spec.ts). Fails if CaMa's table captures ids of other domains or the generic rule changes.
|
||||
// Pins down: only CaMa's measures use the table; TEA's and CaCu's keep `-` to `_`. Fails if the table captures
|
||||
// ids of other domains or the generic rule changes.
|
||||
expect(indicadorId('M21-diagnosticados-con-eeg')).toBe('M21_diagnosticados_con_eeg');
|
||||
expect(Object.hasOwn(CAMA_MEASURE_IDS, 'CACU-EU7')).toBe(false);
|
||||
expect(indicadorId('CACU-EU7')).toBe('CACU_EU7');
|
||||
});
|
||||
|
||||
it('el catálogo lleva contrato, figuras y periodos de cada medida', () => {
|
||||
|
||||
@@ -228,18 +228,17 @@ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
|
||||
const interior = m.grupos.map(g => g.grados.reduce((s, c) => s + m.totales[c]!, 0));
|
||||
const exterior = m.grados.map(g => m.totales[g.id]!);
|
||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
|
||||
// A pie wraps `customdata` in one more array in its hover template, so the text is formatted per point instead.
|
||||
const hover = { hovertemplate: '%{label}<br>%{hovertext}<extra></extra>' };
|
||||
const hoverText = (values: number[]) => values.map(n => `${miles(n)} mujeres con biopsia, ${shareText(n, total)}`);
|
||||
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} mujeres con biopsia, %{customdata[1]}<extra></extra>' };
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
|
||||
text: [`<b>${miles(k)}</b><br>de ${miles(total)} con biopsia`], textfont: { size: 16, color: p.text },
|
||||
marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), hovertext: hoverText(interior),
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior),
|
||||
marker: { colors: m.grupos.map(g => rgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||
labels: m.grados.map(g => escapar(g.etiqueta)), hovertext: hoverText(exterior),
|
||||
labels: m.grados.map(g => escapar(g.etiqueta)), customdata: custom(exterior),
|
||||
marker: { colors: m.grados.map(g => rgba(g.color, activos.has(g.id) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
|
||||
@@ -119,12 +119,8 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
||||
return active[0];
|
||||
};
|
||||
const rg = reporte(general), re = reporte(porEscenario);
|
||||
// With a report id on both sides, the report is identified by it and its cut-off and versions: a FHIR report's
|
||||
// `date` (`generado_en`) is when the answer was served, so the same stored report served twice differs only there.
|
||||
// Without ids, the generation time is still part of the provenance.
|
||||
const identificados = rg?.['report_id'] != null && re?.['report_id'] != null;
|
||||
const procedencia = ['report_id', 'fecha_corte', ...(identificados ? [] : ['generado_en']), 'kit_version', 'toml_sha', 'parametros_sha'];
|
||||
if (!!rg !== !!re || (rg && re && procedencia.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.');
|
||||
if (!!rg !== !!re || (rg && re && ['report_id', 'fecha_corte', 'generado_en', 'kit_version', 'toml_sha', 'parametros_sha']
|
||||
.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.');
|
||||
if (new Set(orden.values()).size !== orden.size) return fail('Orden de categorías EU7 duplicado.');
|
||||
// Missing rows remain unavailable. Catalog order is used only for the accessible
|
||||
// list of missing categories; a partial distribution is never drawn as a donut.
|
||||
@@ -149,20 +145,17 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
||||
return { id, etiqueta: etiquetas[id] as string, celdas: cells, estado: estadoEscenario,
|
||||
den: estadoEscenario === 'Publicado' ? suma(categorias.map(c => cells[c.id])) : null };
|
||||
});
|
||||
// A period without patients may publish its general distribution as explicit zeros (FHIR's complete report) and no
|
||||
// scenario at all: that's an empty period, not a mismatch. A null or positive count without scenarios still is one.
|
||||
const generalEnCeros = g.size > 0 && [...g.values()].every(row => row['n'] === 0);
|
||||
// Compare only fully published sums. Never derive a hidden value by subtraction.
|
||||
if (escenarios.length) {
|
||||
for (const c of cats) {
|
||||
const total = suma(escenarios.map(s => s.celdas[c.id]));
|
||||
if (celdas[c.id].n !== null && total !== null && celdas[c.id].n !== total) return fail('La distribución por escenario difiere de la general.');
|
||||
}
|
||||
} else if (g.size && !generalEnCeros) return fail('No hay escenarios que correspondan a los datos generales.');
|
||||
} else if (g.size) return fail('No hay escenarios que correspondan a los datos generales.');
|
||||
if (!g.size && e.size) return fail('Hay escenarios sin datos generales correspondientes.');
|
||||
return { periodo, categorias, grupos, celdas, escenarios, sinDato: celdas[SIN_DATO],
|
||||
sinDatoEtiqueta: cats.find(c => c.id === SIN_DATO)!.etiqueta,
|
||||
total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size || (generalEnCeros && !escenarios.length),
|
||||
total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size,
|
||||
notas: [...new Set([...(general.notas ?? []), ...(porEscenario.notas ?? [])])] };
|
||||
}
|
||||
const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo);
|
||||
@@ -200,20 +193,19 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
||||
};
|
||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text',
|
||||
insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' };
|
||||
// A pie wraps `customdata` in one more array in its hover template, so the text is formatted per point instead.
|
||||
const hover = { hovertemplate: '%{label}<br>%{hovertext}<extra></extra>' };
|
||||
const hoverText = (values: number[]) => values.map(n => `${miles(n)} pacientes, ${percentNumber(100 * n / m.total!)} % del total con resultado`);
|
||||
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % del total con resultado<extra></extra>' };
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), percentNumber(100 * n / m.total!)]);
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
|
||||
text: [`<b>${miles(centro)}</b><br>${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text },
|
||||
marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
|
||||
textfont: { color: '#FFFFFF' }, hovertext: hoverText(interior),
|
||||
textfont: { color: '#FFFFFF' }, customdata: custom(interior),
|
||||
marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||
labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true),
|
||||
textfont: { size: 11 }, hovertext: hoverText(exterior),
|
||||
textfont: { size: 11 }, customdata: custom(exterior),
|
||||
marker: { colors: m.categorias.map(c => rgba(c.color, sel.categoria && c.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||
], layout: { autosize: true, height: 440, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
CAMA_MEASURE_IDS, CATEGORIA_HISTOPATOLOGIA_PAGINA, esMedidaCama, ESTRATO_BIRADS_PAGINA, ETIQUETA_CATEGORIA_NO_DECLARADA, GRUPO_PRINCIPAL_FHIR,
|
||||
GRUPO_PRINCIPAL_PAGINA, GRUPOS_HISTOPATOLOGIA_PAGINA,
|
||||
} from './indicadores-cama-fhir';
|
||||
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
|
||||
|
||||
// The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical
|
||||
// sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked
|
||||
@@ -41,8 +40,8 @@ const POPULATION_GROUP: Record<string, string> = {
|
||||
};
|
||||
|
||||
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use; CaMa's measures
|
||||
// and CaCu's have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`, `CACU-EU7` -> `cacu_eu7`).
|
||||
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? CACU_MEASURE_IDS[measureId] ?? measureId.replace(/-/g, '_');
|
||||
// have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`).
|
||||
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? measureId.replace(/-/g, '_');
|
||||
const stratifierCode = (s: Stratifier) => code(Array.isArray(s.code) ? s.code[0] : s.code);
|
||||
// Age groups travel as `16_23`; the page names them `16-23`.
|
||||
export const estratoValor = (value: string) => /^\d+_\d+$/.test(value) ? value.replace('_', '-') : value;
|
||||
@@ -56,24 +55,11 @@ function decimal(score: Score | undefined, name: string): number | null {
|
||||
return typeof value === 'number' ? value : null;
|
||||
}
|
||||
const round1 = (value: number) => Math.round(value * 10) / 10;
|
||||
// A proportion's bounds travel as proportions; the rows hold percentages, like `valor`.
|
||||
const percent = (value: number | null) => value === null ? null : round1(value * 100);
|
||||
|
||||
// A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's,
|
||||
// keeps every category ungrouped.
|
||||
export function categorias(measure: Measure): Record<string, Categoria> {
|
||||
return Object.fromEntries(extensions(measure, 'categoria').flatMap(e => {
|
||||
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
|
||||
return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null,
|
||||
grupo: extension(e, 'grupo')?.valueCode ?? null }]] : [];
|
||||
}));
|
||||
}
|
||||
// The groups a composition's categories belong to (`categoria-grupo`: code and caption), in the Measure's order; empty
|
||||
// when the Measure declares none.
|
||||
export function gruposDeCategoria(measure: Measure): Record<string, string> {
|
||||
return Object.fromEntries(extensions(measure, 'categoria-grupo').flatMap(e => {
|
||||
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
|
||||
return codigo && etiqueta ? [[codigo, etiqueta]] : [];
|
||||
return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null, grupo: null }]] : [];
|
||||
}));
|
||||
}
|
||||
function contrato(measure: Measure): string {
|
||||
@@ -148,7 +134,7 @@ function proporcion(populations: Population[] | undefined, score: Score | undefi
|
||||
return {
|
||||
suprimido: 0, numerador, denominador,
|
||||
valor: typeof score?.value === 'number' ? round1(score.value * 100) : null,
|
||||
ic_bajo: percent(decimal(score, 'ic-bajo')), ic_alto: percent(decimal(score, 'ic-alto')),
|
||||
ic_bajo: decimal(score, 'ic-bajo'), ic_alto: decimal(score, 'ic-alto'),
|
||||
n_sin_evento: numerador !== null && denominador !== null ? denominador - numerador : null,
|
||||
n_excluido: count(populations, 'denominator-exclusion') ?? 0,
|
||||
};
|
||||
@@ -207,34 +193,6 @@ function cruceDeHistopatologia(group: Group, estrato: string): Map<string, numbe
|
||||
return celdas;
|
||||
}
|
||||
|
||||
// A composition (C2) by one of its strata, from the report's stratifier that crosses the stratum with the category
|
||||
// (`[estrato, categoria]`, as the WebApi publishes it): each stratum value with its caption, and each cell's count.
|
||||
// FHIR lists only the cells that have units and the report is complete, so a cell it doesn't list is a zero; a stratum
|
||||
// value nobody falls in isn't listed at all. A report with no units has no cell to cross. A missing component, a
|
||||
// category the Measure doesn't declare, a repeated cell or cells that don't add up to the period's units are contract
|
||||
// errors, never a silent zero. FHIR publishes no suppression marker, so nothing here is read as suppressed.
|
||||
function cruceDeComposicion(group: Group, estrato: string, declaradas: readonly string[]) {
|
||||
const unidades = count(group.population, 'initial-population');
|
||||
const valores = new Map<string, string>(), celdas = new Map<string, number>();
|
||||
const stratifier = group.stratifier?.find(s => Array.isArray(s.code) && s.code.length === 2 && code(s.code[0]) === estrato);
|
||||
if (!stratifier && unidades === 0) return { valores, celdas };
|
||||
if (!stratifier) throw new Error('Dimensión no admitida');
|
||||
let suma = 0;
|
||||
for (const stratum of stratifier.stratum ?? []) {
|
||||
const del = stratum.component?.find(c => code(c.code) === estrato), cat = stratum.component?.find(c => code(c.code) !== estrato);
|
||||
const valor = code(del?.value), categoria = code(cat?.value), n = stratum.population?.[0]?.count;
|
||||
if (!valor || !categoria || typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0) throw new Error('Celda del estrato incompleta');
|
||||
if (!declaradas.includes(categoria)) throw new Error('Categoría no declarada en el estrato');
|
||||
const e = estratoValor(valor), clave = `${e}|${categoria}`;
|
||||
if (celdas.has(clave)) throw new Error('Celda del estrato repetida');
|
||||
if (!valores.has(e)) valores.set(e, display(del!.value) ?? e);
|
||||
celdas.set(clave, n);
|
||||
suma += n;
|
||||
}
|
||||
if (unidades !== null && suma !== unidades) throw new Error('Los conteos por estrato no suman las unidades del periodo');
|
||||
return { valores, celdas };
|
||||
}
|
||||
|
||||
// The `/datos` answer for `measure`, from one report per period.
|
||||
export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos {
|
||||
const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id);
|
||||
@@ -242,8 +200,6 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
||||
const extras = kind === 'C2' && cama ? categoriasNoDeclaradas(reports, declaradas) : new Map<string, string>();
|
||||
// The histopathological result by BI-RADS asked by its stratum is read as a matrix of the page's codes (see above).
|
||||
const cruzado = kind === 'C2' && estrato !== undefined && CAMA_MEASURE_IDS[measure.id ?? ''] === 'cama_histopatologia_birads';
|
||||
// Any other composition asked by a stratum is read from its crossed stratifier (`cruceDeComposicion`).
|
||||
const porEstrato = kind === 'C2' && estrato !== undefined && !cruzado;
|
||||
const cats: Record<string, Categoria> = cruzado
|
||||
? Object.fromEntries(Object.entries(declaradas).map(([codigo, c]) => {
|
||||
const m = CATEGORIA_HISTOPATOLOGIA_PAGINA[codigo];
|
||||
@@ -253,10 +209,10 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
||||
: { ...declaradas,
|
||||
...Object.fromEntries([...extras].map(([categoria, etiqueta]) => [categoria, { etiqueta, color: null, grupo: null }])) };
|
||||
const totales: Record<string, unknown>[] = [];
|
||||
// The page names the primary group of a proportion `total`; the WebApi names it `principal`.
|
||||
// CaMa's page names the primary group of a proportion `total`; the WebApi names it `principal`.
|
||||
const nombre = (codigo: string | undefined) => {
|
||||
const grupo = codigo ?? 'TOTAL';
|
||||
return kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
|
||||
return cama && kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
|
||||
};
|
||||
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
|
||||
const id = nombre(code(g.code));
|
||||
@@ -285,21 +241,6 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (porEstrato) {
|
||||
const declaradasEnOrden = Object.keys(cats);
|
||||
const { valores: delPeriodo, celdas } = cruceDeComposicion(group, estrato!, declaradasEnOrden);
|
||||
for (const [e, etiqueta] of delPeriodo) {
|
||||
let total = 0;
|
||||
declaradasEnOrden.forEach((categoria, orden) => {
|
||||
const n = celdas.get(`${e}|${categoria}`) ?? 0;
|
||||
total += n;
|
||||
filas.push({ periodo, grupo, estrato: e, categoria, n, orden, suprimido: 0 });
|
||||
});
|
||||
totales.push({ periodo, grupo, estrato: e, n: total, suprimido: 0 });
|
||||
if (!valores.has(e)) valores.set(e, etiqueta);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (kind === 'C2') {
|
||||
const strata = group.stratifier?.[0]?.stratum ?? [];
|
||||
const counts = new Map(strata.map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
|
||||
@@ -339,10 +280,10 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
||||
periodos,
|
||||
estrato: estrato ?? null,
|
||||
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }),
|
||||
...(cruzado || porEstrato ? { totales_estrato: totales } : {}),
|
||||
...(cruzado ? { totales_estrato: totales } : {}),
|
||||
grupos,
|
||||
categorias: cats,
|
||||
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : gruposDeCategoria(measure),
|
||||
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : {},
|
||||
notas: [],
|
||||
reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))),
|
||||
filas,
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
// Covers CaCu's history tab: its fixed list of indicators, in order, with a pending panel for each one the catalog
|
||||
// does not publish. Catalogs are synthetic, shaped like /cacu/indicadores; the tab stays inactive, so nothing is
|
||||
// requested.
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { HISTORICO_CACU, IndicadoresHistorico } from './indicadores-historico';
|
||||
import { Indicador } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
|
||||
const item = (id: string, contrato: string): Indicador => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
|
||||
|
||||
describe('Histórico de CaCu', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresHistorico>>, http: HttpTestingController;
|
||||
function montar(catalog: Indicador[]) {
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: vi.fn() } }] });
|
||||
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('catalog', catalog);
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', false);
|
||||
fixture.detectChanges();
|
||||
}
|
||||
afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); });
|
||||
const paneles = () => [...(fixture.nativeElement as HTMLElement).querySelectorAll('article.panel')] as HTMLElement[];
|
||||
|
||||
it('lista los seis indicadores en orden y deja pendientes los que el catálogo no publica', () => {
|
||||
// Pins down: the tab shows the fixed list, not the whole catalog, so the risk bands stay out and an indicator
|
||||
// the catalog lacks keeps its place as a pending panel. Fails if the list changes, or the catalog's order or
|
||||
// extra measures leak into the tab.
|
||||
montar([item('cacu_riesgo_banda', 'C2'), item('ind1', 'C1'), item('cacu_eu13', 'C1')]);
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(e => e.titulo));
|
||||
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
|
||||
expect(pendientes).toEqual(['Distribución de resultados citológicos', 'Tasa de confirmación histopatológica',
|
||||
'Días de la toma de la citología a su resultado', 'Tiempo de tamizaje a diagnóstico']);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
// Covers the history tab in the page: it exists for TEA, CaMa and CaCu, sits between Resumen and Seguimiento, and its
|
||||
// Covers the history tab in the page: it exists for CaMa only, sits between Resumen and Seguimiento, and its
|
||||
// panel loads nothing until it is opened. Catalogs are synthetic, shaped like /<dominio>/indicadores.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
@@ -38,13 +38,12 @@ describe('Pestaña Histórico', () => {
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
http.expectNone(request => request.url.startsWith('/cama/analisis'));
|
||||
});
|
||||
it('cacu tiene Histórico pero no Análisis epidemiológico', () => {
|
||||
// Fails if CaCu loses its history tab or gains CaMa's analysis tab.
|
||||
it('cacu no tiene la pestaña Histórico', () => {
|
||||
// Fails if the history tab of TEA or CaMa leaks into CaCu.
|
||||
abrir('cama', []);
|
||||
abrir('cacu', [item('cacu_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
expect(tabs()).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).toBeNull();
|
||||
});
|
||||
it('tea tiene Histórico pero no Análisis epidemiológico', () => {
|
||||
abrir('cama', []);
|
||||
|
||||
@@ -36,18 +36,6 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
||||
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
|
||||
];
|
||||
|
||||
// CaCu's history, built like CaMa's: a fixed list, with the same pending panel for what the catalog does not publish.
|
||||
// The risk bands are left out until their batches are readable.
|
||||
export const HISTORICO_CACU: readonly { id: string; titulo: string }[] = [
|
||||
{ id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos' },
|
||||
{ id: 'ind1', titulo: 'Pacientes con citología anómala' },
|
||||
{ id: 'cacu_eu13', titulo: 'Tasa de detección histopatológica' },
|
||||
{ id: 'cacu_confirmacion_citologia', titulo: 'Tasa de confirmación histopatológica' },
|
||||
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado' },
|
||||
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico' },
|
||||
];
|
||||
const HISTORICO_FIJO: Readonly<Partial<Record<string, readonly { id: string; titulo: string }[]>>> = { cama: HISTORICO_CAMA, cacu: HISTORICO_CACU };
|
||||
|
||||
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
|
||||
function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] {
|
||||
const pasos = TIEMPOS.map(id => paneles.find(p => p.item.id === id));
|
||||
@@ -183,11 +171,9 @@ export class IndicadoresHistorico {
|
||||
readonly catalog = input.required<readonly Indicador[]>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly active = input(false);
|
||||
// The indicators the tab draws: a domain's fixed list, where the catalog publishes it; the whole catalog elsewhere.
|
||||
private readonly publicados = computed(() => {
|
||||
const fijo = HISTORICO_FIJO[this.dominio()];
|
||||
return fijo ? fijo.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)) : this.catalog();
|
||||
});
|
||||
// The indicators the tab draws: CaMa's fixed list, where the catalog publishes it; the whole catalog elsewhere.
|
||||
private readonly publicados = computed(() => this.dominio() === 'cama'
|
||||
? HISTORICO_CAMA.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)) : this.catalog());
|
||||
// Only the granularities some indicator publishes; monthly first when there is one.
|
||||
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.publicados().some(item => item.tipos_periodo.includes(tipo))));
|
||||
readonly elegido = signal<TipoPeriodo | undefined>(undefined);
|
||||
@@ -255,10 +241,9 @@ export class IndicadoresHistorico {
|
||||
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
|
||||
}
|
||||
};
|
||||
const fijo = HISTORICO_FIJO[this.dominio()];
|
||||
if (fijo) {
|
||||
if (this.dominio() === 'cama') {
|
||||
if (!this.publicados().length) return [];
|
||||
return fijo.map((entrada): Panel => {
|
||||
return HISTORICO_CAMA.map((entrada): Panel => {
|
||||
const item = this.catalog().find(i => i.id === entrada.id);
|
||||
return item ? { ...panelDe(item), item: { ...entrada, contrato: item.contrato } } : { item: entrada, estado: 'pendiente' };
|
||||
});
|
||||
|
||||
@@ -115,7 +115,6 @@
|
||||
<span>Incluye el periodo y los indicadores seleccionados. Elige «Guardar como PDF» en el cuadro de impresión.</span>
|
||||
</div>
|
||||
}
|
||||
@if (screeningRouteAvailable) { <app-indicador-screening-route [dominio]="dominio" [tema]="tema" /> }
|
||||
<div class="catalog-grid">
|
||||
@if (histopatologiaPendiente) { <app-indicador-histopatologia-pendiente /> }
|
||||
@for (item of searchResults().items; track cardIdentity(item)) {
|
||||
|
||||
@@ -20,8 +20,6 @@ import { esSocioConteos } from './indicadores-conteos-pareados';
|
||||
import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, KpiCardSlot, camaKpiCards } from './indicadores-kpi';
|
||||
import { TeaResumenPeriodo } from './tea-resumen-periodo';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadorScreeningRoute } from './indicador-screening-route';
|
||||
import { ROUTE_IDS, ROUTE_ONLY_IDS } from './screening-route';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
|
||||
import { identityElementId, indicatorIdentity } from './indicadores-identities';
|
||||
@@ -54,13 +52,13 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, IndicadorScreeningRoute],
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
export class IndicadoresPage {
|
||||
get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; }
|
||||
get conHistorico() { return this.dominio === 'tea' || this.dominio === 'cama' || this.dominio === 'cacu'; }
|
||||
get conHistorico() { return this.dominio === 'tea' || this.dominio === 'cama'; }
|
||||
get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; }
|
||||
readonly activeSection = signal<DashboardSection>('resumen');
|
||||
readonly fichaPacienteAbierta = signal(false);
|
||||
@@ -336,10 +334,6 @@ export class IndicadoresPage {
|
||||
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
|
||||
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
|
||||
}
|
||||
// CaCu's screening route chart, once the catalog publishes every measure it reads.
|
||||
get screeningRouteAvailable() {
|
||||
return this.dominio === 'cacu' && ROUTE_IDS.every(id => this.catalog().some(item => item.id === id));
|
||||
}
|
||||
// How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them.
|
||||
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
|
||||
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
|
||||
@@ -369,10 +363,8 @@ export class IndicadoresPage {
|
||||
// Stable presentation order. Pins no longer reorder the summary.
|
||||
readonly catalogOrder = computed(() => {
|
||||
const catalog = this.catalog();
|
||||
// The route chart draws its own measures: they get no card of their own once it is there.
|
||||
const route = this.screeningRouteAvailable ? ROUTE_ONLY_IDS : [];
|
||||
return this.dominio === 'cacu'
|
||||
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7' && !route.includes(item.id))]
|
||||
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
|
||||
: this.dominio === 'cama' ? this.cardsDeCama(catalog)
|
||||
: catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
|
||||
});
|
||||
|
||||
@@ -163,7 +163,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
|
||||
http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar();
|
||||
expect(e.page.seleccionSeguimiento()).toBeUndefined();
|
||||
expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(
|
||||
['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
|
||||
dominio === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
|
||||
expect(e.root.querySelector('#panel-analisis')).toBeNull();
|
||||
}
|
||||
e.page.changeDominio('cama'); e.harness.detectChanges();
|
||||
|
||||
@@ -11,7 +11,7 @@ describe('Regresión del mapeo FHIR en CaCu y TEA', () => {
|
||||
it('las 16 medidas se mapean igual que antes: ids, catálogo, ficha y filas de datos', () => {
|
||||
// Pins down: ids, catalog entries, sheets and data rows of CaCu's seven and TEA's nine measures, over real reports,
|
||||
// equal the recorded ones; an error counts as a result too. Fails if a change meant for CaMa (its id table, its
|
||||
// undeclared categories, its sheet code) reaches another domain. If the new result is the right one,
|
||||
// group name, its undeclared categories, its sheet code) reaches another domain. If the new result is the right one,
|
||||
// regenerate the recorded mapping and say why in the change.
|
||||
const actual = mapeoDeCacuYTea({ indicadorId, indicadorDeMeasure, metadatosDeMeasure, datosDeReportes });
|
||||
expect(Object.keys(actual)).toEqual(Object.keys(esperado));
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
// What this module covers: the screening route chart in CaCu's page: it appears only when the catalog publishes the seven
|
||||
// measures it reads, and then those measures that nothing else draws lose their own cards. Catalogs are synthetic,
|
||||
// shaped like /cacu/indicadores.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { Dominio } from './indicadores.models';
|
||||
import { ROUTE_IDS, ROUTE_ONLY_IDS } from './screening-route';
|
||||
|
||||
const item = (id: string, contrato = 'C3r') => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] });
|
||||
|
||||
describe('Ruta del tamizaje: página de CaCu', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
|
||||
function abrir(domain: Dominio, catalog: unknown[]) {
|
||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges();
|
||||
http.match(() => true);
|
||||
}
|
||||
const ruta = () => fixture.nativeElement.querySelector('app-indicador-screening-route');
|
||||
const tarjetas = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(d => (d.componentInstance as IndicadorCatalogCard).indicador.id);
|
||||
|
||||
it('con las siete medidas publicadas aparece la gráfica y sus medidas exclusivas no tienen tarjeta', () => {
|
||||
// Pins down: the chart replaces the cards of the five measures only it draws, while the cytology's and the diagnosis'
|
||||
// keep theirs. Fails if the chart stops appearing, or a measure it draws also shows as a card.
|
||||
abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.map(id => item(id))]);
|
||||
expect(ruta()).not.toBeNull();
|
||||
const ids = tarjetas();
|
||||
for (const id of ROUTE_ONLY_IDS) expect(ids).not.toContain(id);
|
||||
expect(ids).toContain('cacu_eu_tiempo_reporte');
|
||||
expect(ids).toContain('cacu_eu7');
|
||||
});
|
||||
it('si el catálogo no publica alguna de las siete, no hay gráfica y las medidas conservan sus tarjetas', () => {
|
||||
// Fails if the chart appears with a measure missing, or the cards of the others disappear anyway.
|
||||
abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.filter(id => id !== 'cacu_dias_toma_biopsia').map(id => item(id))]);
|
||||
expect(ruta()).toBeNull();
|
||||
const ids = tarjetas();
|
||||
for (const id of ROUTE_ONLY_IDS.filter(id => id !== 'cacu_dias_toma_biopsia')) expect(ids).toContain(id);
|
||||
});
|
||||
it('las otras áreas no la tienen', () => {
|
||||
// Fails if the CaCu chart leaks into TEA or CaMa.
|
||||
abrir('cama', [item('cama_eu38a'), ...ROUTE_IDS.map(id => item(id))]);
|
||||
expect(ruta()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -39,9 +39,9 @@ describe('Secciones compartidas por dominio', () => {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
|
||||
const root = harness.routeNativeElement!;
|
||||
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||
// TEA, CaMa and CaCu have Histórico; CaMa labels Seguimiento as Análisis de Riesgos.
|
||||
// TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos; CaCu keeps its three.
|
||||
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']
|
||||
: ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'];
|
||||
: domain === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
|
||||
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
|
||||
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
|
||||
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
|
||||
|
||||
@@ -10,13 +10,6 @@ export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] {
|
||||
&& typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0
|
||||
&& f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : [];
|
||||
}
|
||||
// Whether a composition declares `estrato` among its strata: the catalog from FHIR carries the Measure's declared strata
|
||||
// (`estratos`) and no local filters. Only views that read one fixed stratum use it (CaCu's EU7 by follow-up status);
|
||||
// it doesn't turn on stratified figures or filters for other C2 measures.
|
||||
export function declaraEstrato(item: Indicador, estrato: DimensionEstrato): boolean {
|
||||
const declarados = (item as Indicador & { estratos?: unknown }).estratos;
|
||||
return item.contrato === 'C2' && Array.isArray(declarados) && declarados.includes(estrato);
|
||||
}
|
||||
export interface StratifiedCell { category: string; stratum: string; value: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
||||
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}): { figure: PlotlyFigure; cells: StratifiedCell[] } {
|
||||
if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period
|
||||
|
||||
@@ -39,7 +39,7 @@ const finito = (v: unknown): v is number => typeof v === 'number' && Number.isFi
|
||||
const conteo = (v: unknown): v is number => finito(v) && Number.isSafeInteger(v) && v >= 0;
|
||||
const fail = (message: string): never => { throw new TiemposIncompatibles(message); };
|
||||
|
||||
export function caja(fila: Record<string, unknown> | undefined): Caja {
|
||||
function caja(fila: Record<string, unknown> | undefined): Caja {
|
||||
if (!fila) return { estado: 'No disponible' };
|
||||
if (fila['suprimido'] === 1) return { estado: 'Suprimido' };
|
||||
const { n, q1, mediana, q3 } = fila;
|
||||
|
||||
@@ -38,7 +38,13 @@
|
||||
<mat-card-content>
|
||||
<ul>
|
||||
@for (item of placeholders; track item.key) {
|
||||
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><span>{{ prognosisUnavailable }}</span></li>
|
||||
@if (item.key === 'recurrence' && p.idField === 'pac_id') {
|
||||
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><app-cama-recurrencia [pacId]="+p.patientId" /></li>
|
||||
} @else if (item.key === 'survival' && p.idField === 'pac_id') {
|
||||
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><app-cama-supervivencia [pacId]="+p.patientId" /></li>
|
||||
} @else {
|
||||
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><span>{{ prognosisUnavailable }}</span></li>
|
||||
}
|
||||
}
|
||||
</ul>
|
||||
<p class="availability">{{ recommendationsUnavailable }}</p>
|
||||
|
||||
@@ -3,17 +3,19 @@ import { downloadBlob, exportFilename } from '../../export/download-file';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { CamaRecurrencia } from './cama-recurrencia';
|
||||
import { CamaSupervivencia } from './cama-supervivencia';
|
||||
import {
|
||||
CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
|
||||
} from './cama-patient.models';
|
||||
|
||||
/**
|
||||
* Individual record of a CaMa follow-up patient. It shows only what the follow-up list carries; recurrence,
|
||||
* survival and prognostic factors are placeholders until a validated model supplies them.
|
||||
* Individual record of a CaMa follow-up patient: what the follow-up list carries and, in its prognosis card, the recurrence and
|
||||
* survival figures of the clinical scenarios the patient belongs to.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-patient-card',
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule],
|
||||
imports: [CamaRecurrencia, CamaSupervivencia, MatButtonModule, MatCardModule, MatIconModule],
|
||||
templateUrl: './cama-patient-card.html',
|
||||
styleUrl: './cama-patient-card.scss',
|
||||
})
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { PlotlyFigure } from '../../indicadores.models';
|
||||
import { RecurrenciaFigura } from './cama-recurrencia.models';
|
||||
|
||||
const decimales = new Intl.NumberFormat('es-MX');
|
||||
const finitos = (valores: (number | null)[]) => valores.filter((v): v is number => v !== null && Number.isFinite(v));
|
||||
|
||||
/**
|
||||
* The figure the doctors read: Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull (dotted past the
|
||||
* follow-up), and the combined estimate at each horizon with its bootstrap interval.
|
||||
*/
|
||||
export function figuraRecurrencia(figura: RecurrenciaFigura): PlotlyFigure {
|
||||
const km = figura.km;
|
||||
const seguimiento = km.months[km.months.length - 1];
|
||||
const combinado = figura.points.COMB;
|
||||
const tiempos = figura.weibull.t;
|
||||
const dentro = tiempos.map(t => t <= seguimiento);
|
||||
const trazo = (S: (number | null)[], dentroDelSeguimiento: boolean) =>
|
||||
S.map((v, i) => (dentro[i] === dentroDelSeguimiento || (!dentroDelSeguimiento && tiempos[i] === seguimiento) ? v : null));
|
||||
const todos = [...finitos(km.low), ...finitos(km.high), ...finitos(combinado.low), ...finitos(combinado.high),
|
||||
...finitos(figura.weibull.S), ...finitos(figura.weibull_fractional.S)];
|
||||
const minimo = Math.min(...todos), maximo = Math.max(...todos), margen = (maximo - minimo) * 0.06;
|
||||
const horizontes = figura.horizons_months;
|
||||
const S = combinado.S.map(v => v ?? NaN);
|
||||
return {
|
||||
data: [
|
||||
{ x: km.months, y: km.low, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false },
|
||||
{ x: km.months, y: km.high, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, fill: 'tonexty',
|
||||
fillcolor: 'rgba(154,165,177,0.3)', hoverinfo: 'skip', showlegend: false },
|
||||
{ x: km.months, y: km.S, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 2, color: '#222222' },
|
||||
name: 'Kaplan-Meier (IC 95 % Greenwood)' },
|
||||
{ x: tiempos, y: trazo(figura.weibull.S, true), type: 'scatter', mode: 'lines', line: { width: 3, color: '#1f77b4' }, name: 'Weibull' },
|
||||
{ x: tiempos, y: trazo(figura.weibull.S, false), type: 'scatter', mode: 'lines', line: { width: 2, color: '#1f77b4', dash: 'dot' },
|
||||
hoverinfo: 'skip', showlegend: false },
|
||||
{ x: tiempos, y: trazo(figura.weibull_fractional.S, true), type: 'scatter', mode: 'lines',
|
||||
line: { width: 3, color: '#d1495b', dash: 'dash' }, name: 'Weibull fraccional' },
|
||||
{ x: tiempos, y: trazo(figura.weibull_fractional.S, false), type: 'scatter', mode: 'lines', line: { width: 2, color: '#d1495b', dash: 'dot' },
|
||||
hoverinfo: 'skip', showlegend: false },
|
||||
{ x: horizontes, y: S, type: 'scatter', mode: 'markers',
|
||||
marker: { symbol: 'diamond', size: 12, color: '#6a3d9a', line: { color: '#ffffff', width: 1 } },
|
||||
error_y: { type: 'data', symmetric: false, array: combinado.high.map((v, i) => (v ?? NaN) - S[i]),
|
||||
arrayminus: combinado.low.map((v, i) => S[i] - (v ?? NaN)), color: '#6a3d9a', thickness: 2, width: 5 },
|
||||
name: 'LR + HBN combinado (IC 95 % bootstrap)' },
|
||||
],
|
||||
layout: {
|
||||
title: { text: `${figura.escenario}<br>${figura.cohorte_nombre} · n=${decimales.format(figura.n)}, recaídas=${decimales.format(figura.recaidas)}`,
|
||||
font: { size: 15 } },
|
||||
xaxis: { title: { text: 'Meses desde el diagnóstico' }, range: [0, figura.months_max + 0.8], dtick: 12, zeroline: false },
|
||||
yaxis: { title: { text: 'Libre de recaída S(t)' }, range: [Math.max(0, minimo - margen), Math.min(1.005, maximo + margen)] },
|
||||
legend: { x: 0.01, y: 0.01, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,0)' },
|
||||
margin: { l: 70, r: 20, t: 70, b: 60 },
|
||||
hovermode: 'x unified',
|
||||
},
|
||||
config: { responsive: true, displaylogo: false },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
@switch (estado()) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Cargando escenarios de recurrencia" /> }
|
||||
@case ('sin-modelo') { <p class="availability">No hay una cohorte armada para el análisis de recurrencia.</p> }
|
||||
@case ('error') { <p class="availability" role="alert">No se pudieron cargar los escenarios de recurrencia.</p> }
|
||||
@default {
|
||||
@if (!postratamiento()) {
|
||||
<p class="availability">El análisis de recurrencia es para pacientes que ya terminaron su tratamiento.</p>
|
||||
} @else {
|
||||
@if (deLaPaciente().length) {
|
||||
<mat-button-toggle-group class="scenarios" aria-label="Escenario clínico de la paciente" [value]="elegido()?.cohorte + '|' + elegido()?.escenario"
|
||||
(change)="elegirDePaciente($event.value)">
|
||||
@for (e of deLaPaciente(); track e.cohorte + e.escenario) {
|
||||
<mat-button-toggle [value]="e.cohorte + '|' + e.escenario">{{ nombreCohorte(e.cohorte) }} · {{ e.escenario }}</mat-button-toggle>
|
||||
}
|
||||
</mat-button-toggle-group>
|
||||
} @else {
|
||||
<p class="availability">La paciente no pertenece a ninguno de los escenarios clínicos del modelo. Elige uno del menú.</p>
|
||||
}
|
||||
<div class="menu">
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Cohorte</mat-label>
|
||||
<mat-select [value]="cohorteDelMenu()" (selectionChange)="elegirCohorte($event.value)">
|
||||
@for (c of cohortes(); track c.id) { <mat-option [value]="c.id">{{ c.nombre }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Escenario</mat-label>
|
||||
<mat-select [value]="elegido()?.escenario" (selectionChange)="elegir(cohorteDelMenu(), $event.value)">
|
||||
@for (e of escenariosDelMenu(); track e.nombre) { <mat-option [value]="e.nombre">{{ e.nombre }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
}
|
||||
@if (calculando()) { <mat-progress-bar mode="indeterminate" aria-label="Calculando figura" /> }
|
||||
@if (figura(); as f) { <app-plotly-chart [figure]="f" [showNotes]="false" label="Curva de recurrencia del escenario clínico" /> }
|
||||
@if (mensaje(); as texto) { <p class="availability" role="status">{{ texto }}</p> }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/** The recurrence analysis as `/cama/recurrencia` gives it: the scenarios of each cohort, a scenario's figure and a patient's scenarios. */
|
||||
export interface RecurrenciaEscenario { nombre: string; condiciones: Record<string, string[]>; n: number; recaidas: number; dibujable: boolean }
|
||||
export interface RecurrenciaCohorte { id: string; nombre: string; estado: 'calculando' | 'listo' | 'error'; error: string | null; escenarios: RecurrenciaEscenario[] }
|
||||
export interface RecurrenciaEscenarios { build: number; horizontes: number[]; cohortes: RecurrenciaCohorte[] }
|
||||
export interface RecurrenciaDePaciente { build: number; pac_id: number; postratamiento: boolean; escenarios: { cohorte: string; escenario: string }[] }
|
||||
|
||||
export interface RecurrenciaFigura {
|
||||
cohorte: string;
|
||||
cohorte_nombre: string;
|
||||
escenario: string;
|
||||
n: number;
|
||||
recaidas: number;
|
||||
horizons_months: number[];
|
||||
months_max: number;
|
||||
bootstrap_replicas: number;
|
||||
km: { months: number[]; S: number[]; low: number[]; high: number[] };
|
||||
weibull: { t: number[]; S: (number | null)[] };
|
||||
weibull_fractional: { t: number[]; S: (number | null)[] };
|
||||
points: { COMB: { S: (number | null)[]; low: (number | null)[]; high: (number | null)[] } };
|
||||
}
|
||||
export type RecurrenciaRespuestaFigura = { estado: 'calculando' } | { estado: 'listo'; figura: RecurrenciaFigura };
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number');
|
||||
|
||||
export function recurrenciaEscenarios(v: unknown): RecurrenciaEscenarios {
|
||||
if (!record(v) || typeof v['build'] !== 'number' || !numbers(v['horizontes']) || !Array.isArray(v['cohortes'])
|
||||
|| !v['cohortes'].every(c => record(c) && typeof c['id'] === 'string' && typeof c['nombre'] === 'string' && Array.isArray(c['escenarios']))) {
|
||||
throw new Error('Respuesta de escenarios de recurrencia inválida');
|
||||
}
|
||||
return v as unknown as RecurrenciaEscenarios;
|
||||
}
|
||||
|
||||
export function recurrenciaDePaciente(v: unknown): RecurrenciaDePaciente {
|
||||
if (!record(v) || typeof v['postratamiento'] !== 'boolean' || !Array.isArray(v['escenarios'])
|
||||
|| !v['escenarios'].every(e => record(e) && typeof e['cohorte'] === 'string' && typeof e['escenario'] === 'string')) {
|
||||
throw new Error('Respuesta de recurrencia de la paciente inválida');
|
||||
}
|
||||
return v as unknown as RecurrenciaDePaciente;
|
||||
}
|
||||
|
||||
export function recurrenciaFigura(v: unknown): RecurrenciaFigura {
|
||||
if (!record(v) || typeof v['escenario'] !== 'string' || typeof v['cohorte'] !== 'string' || typeof v['n'] !== 'number'
|
||||
|| typeof v['recaidas'] !== 'number' || !numbers(v['horizons_months']) || !record(v['km']) || !numbers(v['km']['months'])
|
||||
|| !numbers(v['km']['S']) || !record(v['weibull']) || !record(v['weibull_fractional']) || !record(v['points'])) {
|
||||
throw new Error('Respuesta de figura de recurrencia inválida');
|
||||
}
|
||||
return v as unknown as RecurrenciaFigura;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
:host { display: block; min-width: 0; --plot-height: 420px; }
|
||||
.scenarios { display: flex; flex-wrap: wrap; margin-bottom: 0.75rem; }
|
||||
.menu { display: flex; flex-wrap: wrap; gap: 0.75rem; margin: 0.75rem 0; }
|
||||
.availability { margin: 0; }
|
||||
@@ -0,0 +1,29 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams, HttpResponse } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import {
|
||||
recurrenciaDePaciente, recurrenciaEscenarios, recurrenciaFigura, RecurrenciaRespuestaFigura,
|
||||
} from './cama-recurrencia.models';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CamaRecurrenciaService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** The scenarios of each cohort, with their size and whether they have enough recurrences to be drawn. */
|
||||
escenarios() {
|
||||
return this.http.get<unknown>('/cama/recurrencia/escenarios').pipe(map(recurrenciaEscenarios));
|
||||
}
|
||||
|
||||
/** The scenarios a patient's covariates meet, in each cohort; empty for a patient who is not after treatment. */
|
||||
deLaPaciente(pacId: number) {
|
||||
return this.http.get<unknown>(`/cama/recurrencia/pacientes/${pacId}`).pipe(map(recurrenciaDePaciente));
|
||||
}
|
||||
|
||||
/** The figure of one scenario; `calculando` while the cohort's models are being computed. */
|
||||
figura(cohorte: string, escenario: string) {
|
||||
const params = new HttpParams().set('cohorte', cohorte).set('escenario', escenario);
|
||||
return this.http.get<unknown>('/cama/recurrencia/figura', { params, observe: 'response' }).pipe(
|
||||
map((r: HttpResponse<unknown>): RecurrenciaRespuestaFigura =>
|
||||
r.status === 202 ? { estado: 'calculando' } : { estado: 'listo', figura: recurrenciaFigura(r.body) }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { Component, computed, DestroyRef, effect, inject, input, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { forkJoin, Subscription, timer } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from '../../indicadores.models';
|
||||
import { figuraRecurrencia } from './cama-recurrencia-figura';
|
||||
import { RecurrenciaCohorte } from './cama-recurrencia.models';
|
||||
import { CamaRecurrenciaService } from './cama-recurrencia.service';
|
||||
|
||||
const ESPERA_CALCULO_MS = 5000;
|
||||
|
||||
/**
|
||||
* A patient's recurrence: the clinical scenarios her covariates meet and, from a menu, any scenario of either cohort, with the
|
||||
* figure of the one chosen, computed over the live cohort.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-recurrencia',
|
||||
imports: [MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
templateUrl: './cama-recurrencia.html',
|
||||
styleUrl: './cama-recurrencia.scss',
|
||||
})
|
||||
export class CamaRecurrencia {
|
||||
readonly pacId = input.required<number>();
|
||||
readonly estado = signal<'cargando' | 'listo' | 'sin-modelo' | 'error'>('cargando');
|
||||
readonly postratamiento = signal(false);
|
||||
readonly cohortes = signal<RecurrenciaCohorte[]>([]);
|
||||
readonly deLaPaciente = signal<{ cohorte: string; escenario: string }[]>([]);
|
||||
readonly elegido = signal<{ cohorte: string; escenario: string } | null>(null);
|
||||
readonly figura = signal<PlotlyFigure | null>(null);
|
||||
readonly calculando = signal(false);
|
||||
readonly mensaje = signal<string | null>(null);
|
||||
private readonly menuCohorte = signal<string | null>(null);
|
||||
readonly cohorteDelMenu = computed(() => this.menuCohorte() ?? this.elegido()?.cohorte ?? this.cohortes()[0]?.id ?? '');
|
||||
readonly escenariosDelMenu = computed(() =>
|
||||
this.cohortes().find(c => c.id === this.cohorteDelMenu())?.escenarios.filter(e => e.dibujable) ?? []);
|
||||
private readonly servicio = inject(CamaRecurrenciaService);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private pedido?: Subscription;
|
||||
|
||||
constructor() {
|
||||
effect(() => this.cargar(this.pacId()));
|
||||
}
|
||||
|
||||
nombreCohorte(id: string) { return this.cohortes().find(c => c.id === id)?.nombre ?? id; }
|
||||
|
||||
private cargar(pacId: number) {
|
||||
this.estado.set('cargando'); this.limpiar(); this.elegido.set(null); this.menuCohorte.set(null);
|
||||
forkJoin({ menu: this.servicio.escenarios(), paciente: this.servicio.deLaPaciente(pacId) })
|
||||
.pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
||||
next: ({ menu, paciente }) => {
|
||||
this.cohortes.set(menu.cohortes);
|
||||
this.postratamiento.set(paciente.postratamiento);
|
||||
this.deLaPaciente.set(paciente.escenarios);
|
||||
this.estado.set('listo');
|
||||
if (paciente.postratamiento && paciente.escenarios.length) this.elegir(paciente.escenarios[0].cohorte, paciente.escenarios[0].escenario);
|
||||
},
|
||||
error: (e: { status?: number }) => this.estado.set(e?.status === 404 ? 'sin-modelo' : 'error'),
|
||||
});
|
||||
}
|
||||
|
||||
private limpiar() { this.figura.set(null); this.mensaje.set(null); this.calculando.set(false); this.pedido?.unsubscribe(); }
|
||||
|
||||
elegirDePaciente(clave: string) { const [cohorte, ...resto] = clave.split('|'); this.elegir(cohorte, resto.join('|')); }
|
||||
|
||||
elegirCohorte(cohorte: string) { this.menuCohorte.set(cohorte); this.elegido.set(null); this.limpiar(); }
|
||||
|
||||
elegir(cohorte: string, escenario: string) {
|
||||
this.limpiar();
|
||||
this.elegido.set({ cohorte, escenario }); this.menuCohorte.set(cohorte); this.calculando.set(true);
|
||||
const vigente = () => this.elegido()?.cohorte === cohorte && this.elegido()?.escenario === escenario;
|
||||
const pedir = () => {
|
||||
this.pedido = this.servicio.figura(cohorte, escenario).subscribe({
|
||||
next: r => {
|
||||
if (!vigente()) return;
|
||||
if (r.estado === 'calculando') {
|
||||
this.mensaje.set('Calculando los modelos de la cohorte; la figura aparecerá en cuanto estén listos.');
|
||||
this.pedido = timer(ESPERA_CALCULO_MS).subscribe(() => { if (vigente()) pedir(); });
|
||||
return;
|
||||
}
|
||||
this.calculando.set(false); this.mensaje.set(null); this.figura.set(figuraRecurrencia(r.figura));
|
||||
},
|
||||
error: (e: { status?: number }) => {
|
||||
if (!vigente()) return;
|
||||
this.calculando.set(false);
|
||||
this.mensaje.set(e?.status === 404 ? 'El escenario tiene pocas recaídas para dibujar su curva.' : 'No se pudo calcular la figura. Intenta nuevamente.');
|
||||
},
|
||||
});
|
||||
};
|
||||
pedir();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { PlotlyFigure } from '../../indicadores.models';
|
||||
import { SupervivenciaFigura } from './cama-supervivencia.models';
|
||||
|
||||
const decimales = new Intl.NumberFormat('es-MX');
|
||||
|
||||
/**
|
||||
* The figure the doctors read: Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull, and the
|
||||
* LR + HBN combined survival at each horizon with its bootstrap interval.
|
||||
*/
|
||||
export function figuraSupervivencia(figura: SupervivenciaFigura): PlotlyFigure {
|
||||
const meses = figura.months ?? [];
|
||||
const km = figura.km!;
|
||||
const curvas = figura.curve_months ?? [];
|
||||
const combinados = figura.points.filter(p => p.model === 'COMB');
|
||||
const alcance = curvas.length ? curvas[curvas.length - 1] : meses[meses.length - 1];
|
||||
const todos = [...km.lo, ...km.hi, ...combinados.flatMap(p => [p.low, p.high]), ...(figura.weibull?.S ?? []), ...(figura.fractional?.S ?? [])]
|
||||
.filter(v => Number.isFinite(v));
|
||||
const minimo = Math.min(...todos), maximo = Math.max(...todos), margen = (maximo - minimo) * 0.06;
|
||||
return {
|
||||
data: [
|
||||
{ x: meses, y: km.lo, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false },
|
||||
{ x: meses, y: km.hi, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, fill: 'tonexty', fillcolor: 'rgba(154,165,177,0.3)',
|
||||
hoverinfo: 'skip', showlegend: false },
|
||||
{ x: meses, y: km.S, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 2, color: '#222222' },
|
||||
name: 'Kaplan-Meier (IC 95 % Greenwood)' },
|
||||
{ x: curvas, y: figura.weibull!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#1f77b4' }, name: 'Weibull' },
|
||||
{ x: curvas, y: figura.fractional!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#d1495b', dash: 'dash' },
|
||||
name: 'Weibull fraccional' },
|
||||
{ x: combinados.map(p => p.months), y: combinados.map(p => p.S), type: 'scatter', mode: 'markers',
|
||||
marker: { symbol: 'diamond', size: 12, color: '#6a3d9a', line: { color: '#ffffff', width: 1 } },
|
||||
error_y: { type: 'data', symmetric: false, array: combinados.map(p => p.high - p.S), arrayminus: combinados.map(p => p.S - p.low),
|
||||
color: '#6a3d9a', thickness: 2, width: 5 },
|
||||
name: 'LR + HBN combinado (IC 95 % bootstrap)' },
|
||||
],
|
||||
layout: {
|
||||
title: { text: `${figura.scenario}<br>n=${decimales.format(figura.members)}, fallecidos=${decimales.format(figura.deaths)}`, font: { size: 15 } },
|
||||
xaxis: { title: { text: 'Meses desde el diagnóstico' }, range: [0, alcance + 0.8], dtick: 3, zeroline: false },
|
||||
yaxis: { title: { text: 'Supervivencia S(t)' }, range: [Math.max(0, minimo - margen), Math.min(1.005, maximo + margen)] },
|
||||
legend: { x: 0.01, y: 0.01, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,0)' },
|
||||
margin: { l: 70, r: 20, t: 70, b: 60 },
|
||||
hovermode: 'x unified',
|
||||
},
|
||||
config: { responsive: true, displaylogo: false },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
@switch (estado()) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Cargando escenarios de supervivencia" /> }
|
||||
@case ('sin-modelo') { <p class="availability">No hay un modelo de supervivencia en producción.</p> }
|
||||
@case ('error') { <p class="availability" role="alert">No se pudieron cargar los escenarios de supervivencia.</p> }
|
||||
@case ('sin-escenarios') { <p class="availability">La paciente no pertenece a ninguno de los escenarios clínicos del modelo.</p> }
|
||||
@default {
|
||||
@if (escenarios().length > 1) {
|
||||
<mat-button-toggle-group class="scenarios" aria-label="Escenario clínico" [value]="elegido()" (change)="elegir($event.value)">
|
||||
@for (nombre of escenarios(); track nombre) { <mat-button-toggle [value]="nombre">{{ nombre }}</mat-button-toggle> }
|
||||
</mat-button-toggle-group>
|
||||
}
|
||||
@if (cargandoFigura()) { <mat-progress-bar mode="indeterminate" aria-label="Calculando figura" /> }
|
||||
@if (figura(); as f) { <app-plotly-chart [figure]="f" [showNotes]="false" label="Curva de supervivencia del escenario clínico" /> }
|
||||
@if (sinDibujo(); as mensaje) { <p class="availability" role="status">{{ mensaje }}</p> }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/** The survival figure of one clinical scenario, as `GET /cama/supervivencia/figura` gives it. */
|
||||
export interface SupervivenciaPunto { model: 'LR' | 'HBN' | 'COMB'; months: number; S: number; low: number; high: number }
|
||||
|
||||
export interface SupervivenciaFigura {
|
||||
scenario: string;
|
||||
members: number;
|
||||
deaths: number;
|
||||
drawable: boolean;
|
||||
horizons: number[];
|
||||
months?: number[];
|
||||
km?: { S: number[]; lo: number[]; hi: number[] };
|
||||
curve_months?: number[];
|
||||
weibull?: { k: number; S: number[] };
|
||||
fractional?: { k: number; alpha: number; beta: number; S: number[] };
|
||||
points: SupervivenciaPunto[];
|
||||
}
|
||||
|
||||
export interface SupervivenciaEscenarios { model_version: string; build: number; pac_id: number; scenarios: string[] }
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number');
|
||||
|
||||
export function supervivenciaEscenarios(v: unknown): SupervivenciaEscenarios {
|
||||
if (!record(v) || !Array.isArray(v['scenarios']) || !v['scenarios'].every(s => typeof s === 'string')
|
||||
|| typeof v['model_version'] !== 'string' || typeof v['pac_id'] !== 'number') {
|
||||
throw new Error('Respuesta de escenarios de supervivencia inválida');
|
||||
}
|
||||
return v as unknown as SupervivenciaEscenarios;
|
||||
}
|
||||
|
||||
export function supervivenciaFigura(v: unknown): SupervivenciaFigura {
|
||||
if (!record(v) || typeof v['scenario'] !== 'string' || typeof v['members'] !== 'number' || typeof v['deaths'] !== 'number'
|
||||
|| typeof v['drawable'] !== 'boolean' || !numbers(v['horizons']) || !Array.isArray(v['points'])) {
|
||||
throw new Error('Respuesta de figura de supervivencia inválida');
|
||||
}
|
||||
if (v['drawable']) {
|
||||
const km = v['km'], w = v['weibull'], f = v['fractional'];
|
||||
if (!numbers(v['months']) || !numbers(v['curve_months']) || !record(km) || !numbers(km['S']) || !numbers(km['lo']) || !numbers(km['hi'])
|
||||
|| !record(w) || !numbers(w['S']) || !record(f) || !numbers(f['S'])) throw new Error('Figura de supervivencia incompleta');
|
||||
}
|
||||
return v as unknown as SupervivenciaFigura;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
:host { display: block; min-width: 0; --plot-height: 420px; }
|
||||
.scenarios { display: flex; flex-wrap: wrap; margin-bottom: 0.75rem; }
|
||||
.availability { margin: 0; }
|
||||
@@ -0,0 +1,20 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { supervivenciaEscenarios, supervivenciaFigura } from './cama-supervivencia.models';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CamaSupervivenciaService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** The scenarios a patient belongs to, from her variables over the timeline. */
|
||||
escenarios(pacId: number) {
|
||||
return this.http.get<unknown>(`/cama/supervivencia/pacientes/${pacId}`).pipe(map(supervivenciaEscenarios));
|
||||
}
|
||||
|
||||
/** The figure of one scenario over the production model and the live cohort. */
|
||||
figura(escenario: string) {
|
||||
const params = new HttpParams().set('escenario', escenario);
|
||||
return this.http.get<unknown>('/cama/supervivencia/figura', { params }).pipe(map(supervivenciaFigura));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Component, DestroyRef, effect, inject, input, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from '../../indicadores.models';
|
||||
import { figuraSupervivencia } from './cama-supervivencia-figura';
|
||||
import { CamaSupervivenciaService } from './cama-supervivencia.service';
|
||||
|
||||
/**
|
||||
* A patient's survival: the clinical scenarios she belongs to and the figure of the one chosen, computed over the model in
|
||||
* production and the live cohort.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-supervivencia',
|
||||
imports: [MatButtonToggleModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './cama-supervivencia.html',
|
||||
styleUrl: './cama-supervivencia.scss',
|
||||
})
|
||||
export class CamaSupervivencia {
|
||||
readonly pacId = input.required<number>();
|
||||
readonly estado = signal<'cargando' | 'listo' | 'sin-escenarios' | 'sin-modelo' | 'error'>('cargando');
|
||||
readonly escenarios = signal<string[]>([]);
|
||||
readonly elegido = signal<string | null>(null);
|
||||
readonly figura = signal<PlotlyFigure | null>(null);
|
||||
readonly cargandoFigura = signal(false);
|
||||
readonly sinDibujo = signal<string | null>(null);
|
||||
private readonly servicio = inject(CamaSupervivenciaService);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private pedido?: Subscription;
|
||||
|
||||
constructor() {
|
||||
effect(() => this.cargar(this.pacId()));
|
||||
}
|
||||
|
||||
private cargar(pacId: number) {
|
||||
this.estado.set('cargando'); this.figura.set(null); this.sinDibujo.set(null); this.elegido.set(null);
|
||||
this.servicio.escenarios(pacId).pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
||||
next: respuesta => {
|
||||
this.escenarios.set(respuesta.scenarios);
|
||||
if (!respuesta.scenarios.length) { this.estado.set('sin-escenarios'); return; }
|
||||
this.estado.set('listo');
|
||||
this.elegir(respuesta.scenarios[0]);
|
||||
},
|
||||
error: (e: { status?: number }) => this.estado.set(e?.status === 404 ? 'sin-modelo' : 'error'),
|
||||
});
|
||||
}
|
||||
|
||||
elegir(escenario: string) {
|
||||
this.elegido.set(escenario); this.figura.set(null); this.sinDibujo.set(null); this.cargandoFigura.set(true);
|
||||
this.pedido?.unsubscribe();
|
||||
this.pedido = this.servicio.figura(escenario).subscribe({
|
||||
next: f => {
|
||||
this.cargandoFigura.set(false);
|
||||
if (this.elegido() !== escenario) return;
|
||||
if (f.drawable) this.figura.set(figuraSupervivencia(f));
|
||||
else this.sinDibujo.set(`El escenario tiene ${f.members} pacientes y ${f.deaths} fallecidos: son pocos para dibujar su curva.`);
|
||||
},
|
||||
error: () => { this.cargandoFigura.set(false); this.sinDibujo.set('No se pudo calcular la figura. Intenta nuevamente.'); },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -8,33 +8,13 @@
|
||||
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
|
||||
@case ('disponible') {
|
||||
<p class="simulated-label" id="riesgo-simulado">Información simulada · Entorno DEV · Sin evaluación clínica</p>
|
||||
@if (lectura.datos.cohorte; as cohorte) {
|
||||
<h5>Cohorte</h5>
|
||||
<dl class="metadata">
|
||||
<div><dt>Definición de cohorte</dt><dd>{{ cohorte.url }}</dd></div>
|
||||
<div><dt>Versión de cohorte</dt><dd>{{ cohorte.version }}</dd></div>
|
||||
<div><dt>Fecha índice</dt><dd>{{ cohorte.fecha_indice }}</dd></div>
|
||||
</dl>
|
||||
<details>
|
||||
<summary>Variables del modelo PIMM</summary>
|
||||
<p class="availability">Códigos técnicos del modelo; no constituyen un diagnóstico.</p>
|
||||
<dl class="metadata">
|
||||
<div><dt>tipo_censura</dt><dd>{{ cohorte.tipo_censura ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>c (estado basal)</dt><dd>{{ cohorte.c ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>l (años desde índice)</dt><dd>{{ cohorte.l ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>r (años desde índice)</dt><dd>{{ cohorte.r ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>pap_0 (citología índice)</dt><dd>{{ cohorte.pap_0 ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>hpv_0 (VPH índice)</dt><dd>{{ cohorte.hpv_0 ?? 'No disponible' }}</dd></div>
|
||||
</dl>
|
||||
</details>
|
||||
} @else {
|
||||
<p role="status">Sin membresía en la cohorte vigente.</p>
|
||||
}
|
||||
@if (lectura.datos.riesgo; as riesgo) {
|
||||
@let riesgo = lectura.datos.riesgo;
|
||||
<h5>Modelo y evaluación</h5>
|
||||
<dl class="metadata">
|
||||
<div><dt>Modelo</dt><dd>{{ riesgo.modelo_nombre }}</dd></div>
|
||||
<div><dt>Versión del modelo</dt><dd>{{ riesgo.modelo_version }}</dd></div>
|
||||
<div><dt>Fecha índice</dt><dd>{{ riesgo.fecha_indice }}</dd></div>
|
||||
<div><dt>Desenlace</dt><dd>{{ riesgo.desenlace_texto ?? riesgo.desenlace }}</dd></div>
|
||||
<div><dt>Evaluado en (UTC)</dt><dd>{{ riesgo.evaluado_en }}</dd></div>
|
||||
<div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
|
||||
</dl>
|
||||
@@ -46,7 +26,6 @@
|
||||
<th scope="col">Horizonte (años)</th>
|
||||
<th scope="col">Probabilidad (%)</th>
|
||||
<th scope="col">Intervalo de confianza (%)</th>
|
||||
<th scope="col">Estado de evaluación</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
@for (h of riesgo.horizontes; track h.horizonte_anios) {
|
||||
@@ -54,14 +33,12 @@
|
||||
<th scope="row">{{ h.horizonte_anios }}</th>
|
||||
<td class="percentage">{{ h.probabilidad * 100 | number:'1.0-4' }} %</td>
|
||||
<td class="interval">@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }</td>
|
||||
<td>{{ h.estado === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
|
||||
} @else { <p role="status">Sin riesgo disponible: no hay lote vigente.</p> }
|
||||
}
|
||||
}
|
||||
<p class="recommendations">Recomendaciones no disponibles.</p>
|
||||
|
||||
@@ -1,46 +1,39 @@
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
export type EstadoEvaluacionCacu = 'preliminary' | 'final';
|
||||
export type TipoCensuraCacu = 'prevalente' | 'incidente' | 'izquierda' | 'derecha' | 'derechaBasal' | 'no_informativo';
|
||||
|
||||
export interface CohorteRiesgoCacu {
|
||||
url: string;
|
||||
version: string;
|
||||
fecha_indice: string;
|
||||
tipo_censura: TipoCensuraCacu | null;
|
||||
c: number | null;
|
||||
l: number | null;
|
||||
r: number | null;
|
||||
pap_0: string | null;
|
||||
hpv_0: string | null;
|
||||
}
|
||||
|
||||
export interface HorizonteRiesgoCacu {
|
||||
/** Years from the risk's index date: the length of the prediction's `whenPeriod`; 0 is the immediate risk. */
|
||||
horizonte_anios: number;
|
||||
/** Transport values remain probabilities in [0, 1], never percentages. */
|
||||
probabilidad: number;
|
||||
ic_bajo?: number | null;
|
||||
ic_alto?: number | null;
|
||||
estado: EstadoEvaluacionCacu;
|
||||
}
|
||||
|
||||
/** The view of one FHIR `RiskAssessment` (`GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`). */
|
||||
export interface LoteRiesgoCacu {
|
||||
lote_id: number;
|
||||
/** The resource's id, `<lote_id>-<pac_id>`. */
|
||||
id: string;
|
||||
modelo_nombre: string;
|
||||
modelo_version: string;
|
||||
/** The model's index date for this patient (the predictions' `whenPeriod.start`): the horizons count from it. */
|
||||
fecha_indice: string;
|
||||
evaluado_en: string;
|
||||
estado_lote: EstadoEvaluacionCacu;
|
||||
/** The prediction's outcome code (e.g. `cin2_mas`) and its display. */
|
||||
desenlace: string;
|
||||
desenlace_texto: string | null;
|
||||
horizontes: HorizonteRiesgoCacu[];
|
||||
}
|
||||
|
||||
/** DEV-only contract from cacu_riesgo_paciente.md, 2026-10-28. */
|
||||
/** DEV-only: the patient's current `RiskAssessment`, from a `searchset` Bundle tagged `simulado`. */
|
||||
export interface RiesgoPacienteCacu {
|
||||
simulado: true;
|
||||
cohorte: CohorteRiesgoCacu | null;
|
||||
riesgo: LoteRiesgoCacu | null;
|
||||
riesgo: LoteRiesgoCacu;
|
||||
}
|
||||
|
||||
/** `null` when the patient has no risk data. */
|
||||
/** The raw FHIR answer (a Bundle), or `null` when the patient has no risk data. */
|
||||
export interface PacienteRiesgoProvider {
|
||||
obtener(pacId: string): Observable<unknown>;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
||||
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
|
||||
import { inject, InjectionToken } from '@angular/core';
|
||||
import { catchError, of, throwError } from 'rxjs';
|
||||
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
|
||||
|
||||
// The risk batches are keyed by `pac_id`, the identifier a follow-up row carries as `pac_id`; a 404 is a patient without risk data.
|
||||
// The patient's risk is a FHIR `RiskAssessment` searched by `subject=Patient/<pac_id>`, the identifier a follow-up row
|
||||
// carries as `pac_id`; an empty Bundle (or a 404) is a patient without risk data.
|
||||
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
|
||||
providedIn: 'root', factory: () => {
|
||||
const http = inject(HttpClient);
|
||||
return {
|
||||
obtener: (pacId: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe(
|
||||
obtener: (pacId: string) => http.get<unknown>('/cacu/fhir/RiskAssessment', {
|
||||
params: new HttpParams().set('subject', `Patient/${pacId}`),
|
||||
}).pipe(
|
||||
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
|
||||
),
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
|
||||
import { of, Subject, throwError } from 'rxjs';
|
||||
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { prediccion, riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
|
||||
describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
@@ -22,10 +22,10 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
TestBed.inject(HttpTestingController).verify();
|
||||
});
|
||||
|
||||
it('pide el riesgo por el pac_id de los lotes a la WebApi y trata un 404 como no disponible', () => {
|
||||
it('pide el RiskAssessment FHIR de la paciente por su pac_id y trata un 404 como no disponible', () => {
|
||||
const f = setup(), root: HTMLElement = f.nativeElement;
|
||||
TestBed.inject(HttpTestingController).expectOne('/cacu/pacientes/42/riesgo')
|
||||
.flush({ error: 'no existe' }, { status: 404, statusText: 'Not Found' });
|
||||
TestBed.inject(HttpTestingController).expectOne('/cacu/fhir/RiskAssessment?subject=Patient/42')
|
||||
.flush({ resourceType: 'OperationOutcome' }, { status: 404, statusText: 'Not Found' });
|
||||
f.detectChanges();
|
||||
expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(root.textContent).toContain('Recomendaciones no disponibles');
|
||||
@@ -33,27 +33,33 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => {
|
||||
it('un Bundle vacío es una paciente sin riesgo confirmado', () => {
|
||||
const f = setup({ obtener: () => of({ resourceType: 'Bundle', type: 'searchset', total: 0 }) });
|
||||
expect(f.nativeElement.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(f.nativeElement.querySelector('table')).toBeNull();
|
||||
});
|
||||
|
||||
it('renderiza el ejemplo contractual, metadatos y porcentajes sin alterar los datos', () => {
|
||||
const data = riesgoCacuEjemplo(), obtener = vi.fn(() => of(data));
|
||||
data.riesgo!.horizontes[1].estado = 'preliminary';
|
||||
const baseline = structuredClone(data);
|
||||
const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith('42');
|
||||
expect(root.querySelectorAll('thead th')).toHaveLength(4);
|
||||
expect(root.querySelectorAll('thead th')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
|
||||
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']);
|
||||
expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %');
|
||||
expect(root.textContent).toContain('Final (final)');
|
||||
expect(root.textContent).toContain('Preliminar (preliminary)');
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', 'cacu/cohorte_vigilancia', '0.2.0', '2023-04-15', 'incidente', 'ASC-US', 'POSITIVO']) {
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', '2026-06-01', 'CIN2+ por biopsia']) {
|
||||
expect(root.textContent).toContain(value);
|
||||
}
|
||||
// The record no longer shows the cohort's internals (its definition, version or model variables).
|
||||
expect(root.textContent).not.toMatch(/cohorte_vigilancia|Variables del modelo|tipo_censura/);
|
||||
expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-simulado');
|
||||
expect(root.querySelector('#riesgo-simulado')!.textContent).toContain('Información simulada · Entorno DEV');
|
||||
expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/);
|
||||
// Internal batch key stays in the contract, never in a UI label.
|
||||
expect(root.textContent).not.toContain('lote_id');
|
||||
// The resource id (batch and patient) stays in the contract, never in a UI label.
|
||||
expect(root.textContent).not.toMatch(/lote_id|12-42/);
|
||||
expect(data).toEqual(baseline);
|
||||
});
|
||||
|
||||
@@ -67,17 +73,15 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(getComputedStyle(scroll).maxWidth).toBe('100%');
|
||||
expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem');
|
||||
expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky');
|
||||
expect(root.querySelector('details summary')!.textContent).toBe('Variables del modelo PIMM');
|
||||
expect(root.textContent).toContain('no constituyen un diagnóstico');
|
||||
});
|
||||
|
||||
it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => {
|
||||
const data = riesgoCacuEjemplo();
|
||||
data.riesgo!.estado_lote = 'preliminary';
|
||||
data.riesgo!.horizontes = [
|
||||
{ horizonte_anios: 0.5, probabilidad: 0, ic_bajo: 0, ic_alto: 0, estado: 'preliminary' },
|
||||
{ horizonte_anios: 8, probabilidad: 1, ic_bajo: null, ic_alto: 1, estado: 'final' },
|
||||
{ horizonte_anios: 12.25, probabilidad: 0.00123, estado: 'final' },
|
||||
data.entry[0].resource.status = 'preliminary';
|
||||
data.entry[0].resource.prediction = [
|
||||
prediccion(0, '2026-06-01', '2026-12-01', [0, 0]),
|
||||
prediccion(1, '2026-06-01', '2034-06-01'),
|
||||
prediccion(0.00123, '2026-06-01', '2038-09-01'),
|
||||
];
|
||||
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
|
||||
expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']);
|
||||
@@ -86,31 +90,9 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(root.textContent).toContain('Preliminar (preliminary)');
|
||||
});
|
||||
|
||||
it('preserva variables nulas y el cero basal sin convertirlos en hallazgos', () => {
|
||||
it.each([[[]], [[{ code: 'real' }]], [undefined]])('no expone una respuesta no simulada (%j)', tag => {
|
||||
const data = riesgoCacuEjemplo();
|
||||
data.cohorte = { ...data.cohorte!, c: 0, l: null, r: null, pap_0: null, hpv_0: null, tipo_censura: null };
|
||||
const f = setup({ obtener: () => of(data) });
|
||||
const valores = [...f.nativeElement.querySelectorAll('details dd')].map((d: any) => d.textContent);
|
||||
expect(valores).toEqual(['No disponible', '0', 'No disponible', 'No disponible', 'No disponible', 'No disponible']);
|
||||
expect(f.nativeElement.textContent).not.toMatch(/undefined|null/);
|
||||
});
|
||||
|
||||
it.each(['cohorte', 'riesgo', 'horizontes', 'ambos'])('distingue ausencia de %s', caso => {
|
||||
const data = riesgoCacuEjemplo();
|
||||
if (caso === 'cohorte' || caso === 'ambos') data.cohorte = null;
|
||||
if (caso === 'riesgo' || caso === 'ambos') data.riesgo = null;
|
||||
if (caso === 'horizontes') data.riesgo!.horizontes = [];
|
||||
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
|
||||
if (!data.cohorte) expect(root.textContent).toContain('Sin membresía en la cohorte vigente');
|
||||
if (!data.riesgo) expect(root.textContent).toContain('Sin riesgo disponible: no hay lote vigente');
|
||||
if (caso === 'horizontes') expect(root.textContent).toContain('Sin horizontes evaluados');
|
||||
if (caso !== 'cohorte') expect(root.querySelector('table')).toBeNull();
|
||||
expect(root.textContent).toContain('Información simulada');
|
||||
expect(root.textContent).toContain('Recomendaciones no disponibles');
|
||||
});
|
||||
|
||||
it.each([false, 'true', undefined])('no expone una respuesta no simulada (%s)', simulado => {
|
||||
const data = { ...riesgoCacuEjemplo(), simulado };
|
||||
if (tag === undefined) delete data.entry[0].resource.meta; else data.entry[0].resource.meta.tag = tag;
|
||||
const f = setup({ obtener: () => of(data) });
|
||||
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(f.nativeElement.textContent).not.toContain('modelo-cacu');
|
||||
@@ -118,7 +100,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
});
|
||||
|
||||
it('rechaza probabilidades inválidas sin presentar parcialmente la cohorte', () => {
|
||||
const data = riesgoCacuEjemplo(); data.riesgo!.horizontes[0].probabilidad = 12;
|
||||
const data = riesgoCacuEjemplo(); data.entry[0].resource.prediction[0].probabilityDecimal = 12;
|
||||
const f = setup({ obtener: () => of(data) });
|
||||
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(f.nativeElement.querySelectorAll('table, dl')).toHaveLength(0);
|
||||
@@ -134,14 +116,14 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
it('aísla estado y fixture entre instancias sin reutilizar información', () => {
|
||||
const source = new Subject<unknown>(), f = setup({ obtener: () => source });
|
||||
const data = riesgoCacuEjemplo(); source.next(data); f.detectChanges();
|
||||
data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges();
|
||||
data.entry[0].resource.prediction[0].probabilityDecimal = 1; f.detectChanges();
|
||||
expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %');
|
||||
f.destroy();
|
||||
const otra = TestBed.createComponent(PacienteRiesgoTabla);
|
||||
otra.componentRef.setInput('pacId', '43'); otra.detectChanges();
|
||||
expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual');
|
||||
expect(otra.nativeElement.querySelector('table')).toBeNull();
|
||||
expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08);
|
||||
expect(riesgoCacuEjemplo().entry[0].resource.prediction[0].probabilityDecimal).toBe(0.08);
|
||||
otra.destroy(); expect(source.observed).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -14,8 +14,10 @@ export class PacienteRiesgoState {
|
||||
readonly pacId = signal<string | null | undefined>(undefined);
|
||||
readonly estado = toSignal(toObservable(this.pacId).pipe(
|
||||
switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe(
|
||||
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
|
||||
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
|
||||
map((respuesta): PacienteRiesgoEstado => {
|
||||
const datos = respuesta === null ? null : riesgoPacienteResponse(respuesta, id);
|
||||
return datos === null ? { tipo: 'no-disponible' } : { tipo: 'disponible', datos };
|
||||
}),
|
||||
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
|
||||
startWith(CARGANDO),
|
||||
)),
|
||||
|
||||
@@ -1,20 +1,51 @@
|
||||
import { RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
|
||||
/** TEST ONLY. Exact external contract example; never belongs to the selected patient. */
|
||||
export function riesgoCacuEjemplo(): RiesgoPacienteCacu {
|
||||
const CS = 'https://isssteleon.org/fhir/CodeSystem';
|
||||
export const INTERVALO = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
|
||||
|
||||
/** A FHIR prediction: probability `p` from `inicio` to `fin`, with its interval when given. */
|
||||
export function prediccion(p: number, inicio: string, fin: string, ic?: [number, number]): any {
|
||||
return {
|
||||
outcome: { coding: [{ system: `${CS}/desenlace`, code: 'cin2_mas', display: 'CIN2+ por biopsia' }] },
|
||||
probabilityDecimal: p, whenPeriod: { start: inicio, end: fin },
|
||||
...(ic ? { extension: [{ url: INTERVALO, valueRange: { low: { value: ic[0] }, high: { value: ic[1] } } }] } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** TEST ONLY. The external contract example: a `searchset` Bundle with patient 42's current `RiskAssessment`, as
|
||||
* `GET /cacu/fhir/RiskAssessment?subject=Patient/42` answers it; never belongs to the selected patient. */
|
||||
export function riesgoCacuEjemplo(): any {
|
||||
return {
|
||||
resourceType: 'Bundle', type: 'searchset', total: 1,
|
||||
entry: [{
|
||||
fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/12-42',
|
||||
resource: {
|
||||
resourceType: 'RiskAssessment', id: '12-42', status: 'final',
|
||||
meta: { tag: [{ system: `${CS}/etiqueta`, code: 'simulado', display: 'Datos simulados' }] },
|
||||
subject: { reference: 'Patient/42' }, occurrenceDateTime: '2026-10-01T00:00:00Z',
|
||||
method: { coding: [{ system: `${CS}/modelo`, code: 'modelo-cacu', version: '2.1.0' }] },
|
||||
prediction: [
|
||||
prediccion(0.08, '2026-06-01', '2027-06-01', [0.05, 0.12]),
|
||||
prediccion(0.21, '2026-06-01', '2029-06-01', [0.15, 0.28]),
|
||||
prediccion(0.34, '2026-06-01', '2031-06-01', [0.26, 0.44]),
|
||||
],
|
||||
},
|
||||
search: { mode: 'match' },
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
/** TEST ONLY. What the record shows from `riesgoCacuEjemplo()`. */
|
||||
export function riesgoCacuVista(): RiesgoPacienteCacu {
|
||||
return {
|
||||
simulado: true,
|
||||
cohorte: {
|
||||
url: 'cacu/cohorte_vigilancia', version: '0.2.0', fecha_indice: '2023-04-15',
|
||||
tipo_censura: 'incidente', c: 0, l: 0.164, r: 0.548, pap_0: 'ASC-US', hpv_0: 'POSITIVO',
|
||||
},
|
||||
riesgo: {
|
||||
lote_id: 12, modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0',
|
||||
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final',
|
||||
id: '12-42', modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', fecha_indice: '2026-06-01',
|
||||
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', desenlace: 'cin2_mas', desenlace_texto: 'CIN2+ por biopsia',
|
||||
horizontes: [
|
||||
{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12, estado: 'final' },
|
||||
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28, estado: 'final' },
|
||||
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44, estado: 'final' },
|
||||
{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 },
|
||||
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28 },
|
||||
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,121 +1,89 @@
|
||||
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { prediccion, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing';
|
||||
import { riesgoPacienteResponse, tieneIntervalo } from './paciente-riesgo.validation';
|
||||
import { TipoCensuraCacu } from './paciente-riesgo.models';
|
||||
|
||||
describe('RIESGO-CACU-02: frontera del contrato DEV', () => {
|
||||
it('conserva todos los campos del ejemplo externo y copia los objetos', () => {
|
||||
const recurso = (v: any) => v.entry[0].resource;
|
||||
|
||||
describe('RIESGO-CACU-02: frontera del contrato FHIR RiskAssessment (DEV)', () => {
|
||||
it('lee el Bundle searchset en la vista de la ficha y no comparte objetos con la entrada', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
const salida = riesgoPacienteResponse(entrada);
|
||||
expect(salida).toEqual(entrada);
|
||||
salida.riesgo!.horizontes[0].probabilidad = 0;
|
||||
salida.cohorte!.c = -999;
|
||||
const salida = riesgoPacienteResponse(entrada, '42')!;
|
||||
expect(salida).toEqual(riesgoCacuVista());
|
||||
salida.riesgo.horizontes[0].probabilidad = 0;
|
||||
expect(entrada).toEqual(riesgoCacuEjemplo());
|
||||
});
|
||||
|
||||
it('admite campos aditivos sin eliminarlos ni renombrarlos', () => {
|
||||
const entrada = { ...riesgoCacuEjemplo(), futuro: { estado: null } };
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
it('un Bundle vacío es una paciente sin riesgo confirmado, con o sin `entry`', () => {
|
||||
expect(riesgoPacienteResponse({ resourceType: 'Bundle', type: 'searchset', total: 0 })).toBeNull();
|
||||
expect(riesgoPacienteResponse({ resourceType: 'Bundle', type: 'searchset', total: 0, entry: [] })).toBeNull();
|
||||
});
|
||||
|
||||
it.each(['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo', null])(
|
||||
'preserva tipo_censura %s sin inferir etiquetas clínicas', tipo => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.cohorte!.tipo_censura = tipo as TipoCensuraCacu | null;
|
||||
expect(riesgoPacienteResponse(entrada).cohorte!.tipo_censura).toBe(tipo);
|
||||
},
|
||||
);
|
||||
|
||||
it('preserva los nulos independientes y el sentinel basal del contrato', () => {
|
||||
it('el horizonte sale del whenPeriod; el inmediato es un periodo de un día', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.cohorte = { ...entrada.cohorte!, tipo_censura: null, c: -999, l: null, r: null, pap_0: null, hpv_0: null };
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
entrada.riesgo = null;
|
||||
entrada.cohorte.c = null;
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
entrada.cohorte = null;
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual({ simulado: true, cohorte: null, riesgo: null });
|
||||
recurso(entrada).prediction = [prediccion(0.02, '2026-06-01', '2026-06-01'), prediccion(0.4, '2026-06-01', '2034-06-01')];
|
||||
expect(riesgoPacienteResponse(entrada)!.riesgo.horizontes.map(h => h.horizonte_anios)).toEqual([0, 8]);
|
||||
});
|
||||
|
||||
it('no impone dependencia entre cohorte nullable y riesgo nullable', () => {
|
||||
it('ordena las predicciones por horizonte y admite campos aditivos de FHIR', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.cohorte = null;
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
recurso(entrada).prediction.reverse();
|
||||
recurso(entrada).note = [{ text: 'simulado' }];
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(riesgoCacuVista());
|
||||
});
|
||||
|
||||
it.each([[], [2.5], [0, 0.5, 7, 12]])('acepta horizontes dinámicos/parciales/vacíos %j', (...anios: number[]) => {
|
||||
it.each([[undefined], [[]], [[{ url: 'otra', valueString: 'x' }]]])('sin extensión de intervalo no fabrica límites (%j)', ext => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.riesgo!.horizontes = anios.map((horizonte_anios, i) => ({
|
||||
horizonte_anios, probabilidad: i % 2, estado: i % 2 ? 'preliminary' : 'final',
|
||||
}));
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{}, { ic_bajo: null, ic_alto: null }, { ic_bajo: 0, ic_alto: null },
|
||||
{ ic_bajo: null, ic_alto: 1 }, { ic_bajo: 0 }, { ic_alto: 1 },
|
||||
])('conserva IC incompletos sin generar límites: %j', limites => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.riesgo!.horizontes = [{ horizonte_anios: 2, probabilidad: 0.5, estado: 'preliminary', ...limites }];
|
||||
const salida = riesgoPacienteResponse(entrada);
|
||||
expect(salida).toEqual(entrada);
|
||||
expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(false);
|
||||
const p = recurso(entrada).prediction[0];
|
||||
if (ext === undefined) delete p.extension; else p.extension = ext;
|
||||
const h = riesgoPacienteResponse(entrada)!.riesgo.horizontes[0];
|
||||
expect([h.ic_bajo, h.ic_alto]).toEqual([null, null]);
|
||||
expect(tieneIntervalo(h)).toBe(false);
|
||||
});
|
||||
|
||||
it.each([0, 1])('acepta probabilidad y límites extremos %s sin convertir el transporte a porcentaje', p => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.riesgo!.estado_lote = 'preliminary';
|
||||
entrada.riesgo!.horizontes = [{ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p, estado: 'preliminary' }];
|
||||
const salida = riesgoPacienteResponse(entrada);
|
||||
expect(salida).toEqual(entrada);
|
||||
expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(true);
|
||||
recurso(entrada).status = 'preliminary';
|
||||
recurso(entrada).prediction = [prediccion(p, '2026-06-01', '2030-06-01', [p, p])];
|
||||
const salida = riesgoPacienteResponse(entrada)!;
|
||||
expect(salida.riesgo.estado_lote).toBe('preliminary');
|
||||
expect(salida.riesgo.horizontes[0]).toEqual({ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p });
|
||||
expect(tieneIntervalo(salida.riesgo.horizontes[0])).toBe(true);
|
||||
});
|
||||
|
||||
const invalidos: [string, (v: any) => void][] = [
|
||||
['no simulado', v => v.simulado = false],
|
||||
['simulado string', v => v.simulado = 'true'],
|
||||
['sin simulado', v => delete v.simulado],
|
||||
['sin cohorte', v => delete v.cohorte],
|
||||
['sin riesgo', v => delete v.riesgo],
|
||||
['cohorte lista', v => v.cohorte = []],
|
||||
['URL ajena', v => v.cohorte.url = 'otra'],
|
||||
['versión ausente', v => delete v.cohorte.version],
|
||||
['fecha inválida', v => v.cohorte.fecha_indice = '2026-02-30'],
|
||||
['enum PIMM desconocido', v => v.cohorte.tipo_censura = 'diagnostico'],
|
||||
['basal string', v => v.cohorte.c = '0'],
|
||||
['variable no finita', v => v.cohorte.l = Infinity],
|
||||
['variable omitida', v => delete v.cohorte.r],
|
||||
['pap no textual', v => v.cohorte.pap_0 = 5],
|
||||
['hpv no textual', v => v.cohorte.hpv_0 = false],
|
||||
['lote fraccionario', v => v.riesgo.lote_id = 1.5],
|
||||
['lote string', v => v.riesgo.lote_id = '12'],
|
||||
['modelo omitido', v => delete v.riesgo.modelo_nombre],
|
||||
['versión no textual', v => v.riesgo.modelo_version = 2],
|
||||
['evaluación fecha imposible', v => v.riesgo.evaluado_en = '2026-02-30T00:00:00Z'],
|
||||
['evaluación sin UTC', v => v.riesgo.evaluado_en = '2026-10-01T00:00:00-06:00'],
|
||||
['hora inválida', v => v.riesgo.evaluado_en = '2026-10-01T25:00:00Z'],
|
||||
['estado lote desconocido', v => v.riesgo.estado_lote = 'confirmado'],
|
||||
['sin horizontes', v => delete v.riesgo.horizontes],
|
||||
['horizontes nulos', v => v.riesgo.horizontes = null],
|
||||
['horizonte nulo', v => v.riesgo.horizontes[0] = null],
|
||||
['horizonte string', v => v.riesgo.horizontes[0].horizonte_anios = '1'],
|
||||
['horizonte no finito', v => v.riesgo.horizontes[0].horizonte_anios = NaN],
|
||||
['horizontes desordenados', v => v.riesgo.horizontes.reverse()],
|
||||
['horizontes repetidos', v => v.riesgo.horizontes[1].horizonte_anios = 1],
|
||||
['probabilidad negativa', v => v.riesgo.horizontes[0].probabilidad = -0.01],
|
||||
['probabilidad mayor a uno', v => v.riesgo.horizontes[0].probabilidad = 1.01],
|
||||
['probabilidad string', v => v.riesgo.horizontes[0].probabilidad = '0.08'],
|
||||
['probabilidad nula', v => v.riesgo.horizontes[0].probabilidad = null],
|
||||
['probabilidad no finita', v => v.riesgo.horizontes[0].probabilidad = NaN],
|
||||
['estado horizonte inválido', v => v.riesgo.horizontes[0].estado = 'FINAL'],
|
||||
['IC bajo inválido', v => v.riesgo.horizontes[0].ic_bajo = -0.01],
|
||||
['IC alto inválido', v => v.riesgo.horizontes[0].ic_alto = 1.01],
|
||||
['IC string', v => v.riesgo.horizontes[0].ic_alto = '0.12'],
|
||||
['IC invertido', v => Object.assign(v.riesgo.horizontes[0], { ic_bajo: 0.12, ic_alto: 0.05 })],
|
||||
['IC fuera de probabilidad', v => v.riesgo.horizontes[0].ic_alto = 0.07],
|
||||
['no es Bundle', v => v.resourceType = 'RiskAssessment'],
|
||||
['Bundle no searchset', v => v.type = 'collection'],
|
||||
['sin total', v => delete v.total],
|
||||
['entry no lista', v => v.entry = {}],
|
||||
['recurso ajeno', v => recurso(v).resourceType = 'Observation'],
|
||||
['no simulado', v => delete recurso(v).meta],
|
||||
['etiqueta ajena', v => recurso(v).meta.tag[0].code = 'real'],
|
||||
['sin id', v => delete recurso(v).id],
|
||||
['estado desconocido', v => recurso(v).status = 'amended'],
|
||||
['estado anulado', v => recurso(v).status = 'entered-in-error'],
|
||||
['otra paciente', v => recurso(v).subject.reference = 'Patient/43'],
|
||||
['sujeto no paciente', v => recurso(v).subject.reference = 'Group/42'],
|
||||
['evaluación sin UTC', v => recurso(v).occurrenceDateTime = '2026-10-01T00:00:00-06:00'],
|
||||
['evaluación fecha imposible', v => recurso(v).occurrenceDateTime = '2026-02-30T00:00:00Z'],
|
||||
['sin modelo', v => delete recurso(v).method],
|
||||
['modelo sin versión', v => delete recurso(v).method.coding[0].version],
|
||||
['sin predicciones', v => recurso(v).prediction = []],
|
||||
['predicción nula', v => recurso(v).prediction[0] = null],
|
||||
['sin desenlace', v => delete recurso(v).prediction[0].outcome],
|
||||
['probabilidad string', v => recurso(v).prediction[0].probabilityDecimal = '0.08'],
|
||||
['probabilidad mayor a uno', v => recurso(v).prediction[0].probabilityDecimal = 1.01],
|
||||
['probabilidad negativa', v => recurso(v).prediction[0].probabilityDecimal = -0.01],
|
||||
['sin periodo', v => delete recurso(v).prediction[0].whenPeriod],
|
||||
['periodo con fecha imposible', v => recurso(v).prediction[0].whenPeriod.end = '2027-02-30'],
|
||||
['periodo invertido', v => recurso(v).prediction[0].whenPeriod.end = '2025-06-01'],
|
||||
['dos fechas índice', v => recurso(v).prediction[1].whenPeriod.start = '2026-07-01'],
|
||||
['horizontes repetidos', v => recurso(v).prediction[1].whenPeriod.end = '2027-06-01'],
|
||||
['IC invertido', v => recurso(v).prediction[0].extension[0].valueRange = { low: { value: 0.12 }, high: { value: 0.05 } }],
|
||||
['IC fuera de probabilidad', v => recurso(v).prediction[0].extension[0].valueRange.high.value = 0.07],
|
||||
['IC string', v => recurso(v).prediction[0].extension[0].valueRange.high.value = '0.12'],
|
||||
];
|
||||
it.each(invalidos)('rechaza %s sin coerción ni datos parciales', (_, mutar) => {
|
||||
const entrada = riesgoCacuEjemplo(); mutar(entrada);
|
||||
expect(() => riesgoPacienteResponse(entrada)).toThrow('Respuesta de riesgo individual DEV inválida');
|
||||
expect(() => riesgoPacienteResponse(entrada, '42')).toThrow('Respuesta de riesgo individual DEV inválida');
|
||||
});
|
||||
it.each([null, undefined, [], 0, 'respuesta'])('rechaza cuerpo inválido %j', entrada => {
|
||||
expect(() => riesgoPacienteResponse(entrada)).toThrow();
|
||||
|
||||
@@ -1,54 +1,104 @@
|
||||
import { isoDate } from '../cacu-seguimiento.models';
|
||||
import { HorizonteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
import { HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
const nullableNumber = (v: unknown) => v === null || finite(v);
|
||||
const nullableText = (v: unknown) => v === null || typeof v === 'string';
|
||||
const text = (v: unknown) => typeof v === 'string';
|
||||
const estado = (v: unknown) => v === 'preliminary' || v === 'final';
|
||||
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
|
||||
const estado = (v: unknown): v is 'preliminary' | 'final' => v === 'preliminary' || v === 'final';
|
||||
const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1;
|
||||
const censuras = ['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo'];
|
||||
const DAYS_PER_YEAR = 365.25;
|
||||
const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
|
||||
const SIMULATED = 'simulado';
|
||||
|
||||
function utcTimestamp(v: unknown) {
|
||||
function utcTimestamp(v: unknown): v is string {
|
||||
return typeof v === 'string'
|
||||
&& /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|\+00:00)$/.test(v)
|
||||
&& isoDate(v.slice(0, 10)) && Number.isFinite(Date.parse(v));
|
||||
}
|
||||
|
||||
function cohorteValida(v: unknown) {
|
||||
return v === null || record(v)
|
||||
&& v['url'] === 'cacu/cohorte_vigilancia' && text(v['version']) && isoDate(v['fecha_indice'])
|
||||
&& (v['tipo_censura'] === null || censuras.includes(v['tipo_censura'] as string))
|
||||
&& nullableNumber(v['c']) && nullableNumber(v['l']) && nullableNumber(v['r'])
|
||||
&& nullableText(v['pap_0']) && nullableText(v['hpv_0']);
|
||||
function invalid(): never {
|
||||
throw new Error('Respuesta de riesgo individual DEV inválida');
|
||||
}
|
||||
|
||||
function horizonteValido(v: unknown) {
|
||||
if (!record(v) || !finite(v['horizonte_anios']) || !probability(v['probabilidad']) || !estado(v['estado'])) return false;
|
||||
for (const key of ['ic_bajo', 'ic_alto']) {
|
||||
if (Object.hasOwn(v, key) && v[key] !== null && !probability(v[key])) return false;
|
||||
/** Years between two ISO dates, to two decimals: a prediction's horizon from its `whenPeriod`. */
|
||||
function years(start: string, end: string): number {
|
||||
const days = (Date.parse(`${end}T00:00:00Z`) - Date.parse(`${start}T00:00:00Z`)) / 86_400_000;
|
||||
return Math.round(days / DAYS_PER_YEAR * 100) / 100;
|
||||
}
|
||||
|
||||
function interval(prediction: Record<string, unknown>): { ic_bajo: number | null; ic_alto: number | null } {
|
||||
const extensions = prediction['extension'];
|
||||
if (extensions === undefined) return { ic_bajo: null, ic_alto: null };
|
||||
if (!Array.isArray(extensions)) invalid();
|
||||
const found = extensions.find(e => record(e) && e['url'] === INTERVAL);
|
||||
if (found === undefined) return { ic_bajo: null, ic_alto: null };
|
||||
const range = found['valueRange'];
|
||||
const low = record(range) && record(range['low']) ? range['low']['value'] : undefined;
|
||||
const high = record(range) && record(range['high']) ? range['high']['value'] : undefined;
|
||||
if (!probability(low) || !probability(high) || low > high) invalid();
|
||||
return { ic_bajo: low, ic_alto: high };
|
||||
}
|
||||
|
||||
function horizon(prediction: unknown, start: string | undefined): { horizonte: HorizonteRiesgoCacu; start: string } {
|
||||
if (!record(prediction) || !probability(prediction['probabilityDecimal'])) invalid();
|
||||
const period = prediction['whenPeriod'];
|
||||
if (!record(period) || !isoDate(period['start']) || !isoDate(period['end'])) invalid();
|
||||
const from = period['start'] as string, to = period['end'] as string;
|
||||
if (start !== undefined && from !== start) invalid(); // one index date per patient
|
||||
const h = years(from, to);
|
||||
if (h < 0) invalid();
|
||||
const ic = interval(prediction);
|
||||
const p = prediction['probabilityDecimal'];
|
||||
if (ic.ic_bajo !== null && ic.ic_alto !== null && !(ic.ic_bajo <= p && p <= ic.ic_alto)) invalid();
|
||||
return { horizonte: { horizonte_anios: h, probabilidad: p, ...ic }, start: from };
|
||||
}
|
||||
|
||||
function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu {
|
||||
if (!record(v) || v['resourceType'] !== 'RiskAssessment' || !text(v['id']) || !estado(v['status'])
|
||||
|| !utcTimestamp(v['occurrenceDateTime'])) invalid();
|
||||
const subject = v['subject'];
|
||||
if (!record(subject) || !text(subject['reference']) || !subject['reference'].startsWith('Patient/')
|
||||
|| (pacId !== null && subject['reference'] !== `Patient/${pacId}`)) invalid();
|
||||
const method = v['method'];
|
||||
const model = record(method) && Array.isArray(method['coding']) ? method['coding'][0] : undefined;
|
||||
if (!record(model) || !text(model['code']) || !text(model['version'])) invalid();
|
||||
const predictions = v['prediction'];
|
||||
if (!Array.isArray(predictions) || predictions.length === 0) invalid();
|
||||
let start: string | undefined;
|
||||
const horizontes: HorizonteRiesgoCacu[] = [];
|
||||
for (const prediction of predictions) {
|
||||
const found = horizon(prediction, start);
|
||||
start = found.start;
|
||||
horizontes.push(found.horizonte);
|
||||
}
|
||||
// Missing/null endpoints are preserved. A complete interval must contain the probability.
|
||||
return !(probability(v['ic_bajo']) && probability(v['ic_alto']))
|
||||
|| v['ic_bajo'] <= v['probabilidad'] && v['probabilidad'] <= v['ic_alto'];
|
||||
horizontes.sort((a, b) => a.horizonte_anios - b.horizonte_anios);
|
||||
if (horizontes.some((h, i) => i > 0 && horizontes[i - 1].horizonte_anios === h.horizonte_anios)) invalid();
|
||||
const outcome = record(predictions[0]) && record(predictions[0]['outcome']) && Array.isArray(predictions[0]['outcome']['coding'])
|
||||
? predictions[0]['outcome']['coding'][0] : undefined;
|
||||
if (!record(outcome) || !text(outcome['code'])) invalid();
|
||||
return {
|
||||
id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string,
|
||||
fecha_indice: start!, evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final',
|
||||
desenlace: outcome['code'] as string, desenlace_texto: text(outcome['display']) ? outcome['display'] : null,
|
||||
horizontes,
|
||||
};
|
||||
}
|
||||
|
||||
function riesgoValido(v: unknown) {
|
||||
if (v === null) return true;
|
||||
if (!record(v) || !Number.isSafeInteger(v['lote_id']) || !text(v['modelo_nombre']) || !text(v['modelo_version'])
|
||||
|| !utcTimestamp(v['evaluado_en']) || !estado(v['estado_lote']) || !Array.isArray(v['horizontes'])) return false;
|
||||
const horizontes = v['horizontes'];
|
||||
return horizontes.every(horizonteValido)
|
||||
&& horizontes.every((h, i) => i === 0 || horizontes[i - 1]['horizonte_anios'] < h['horizonte_anios']);
|
||||
function simulated(resource: Record<string, unknown>): boolean {
|
||||
const meta = resource['meta'];
|
||||
return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED);
|
||||
}
|
||||
|
||||
/** Validate at the boundary. Reject real data, coercions and malformed fields; retain additive fields. */
|
||||
export function riesgoPacienteResponse(v: unknown): RiesgoPacienteCacu {
|
||||
if (!record(v) || v['simulado'] !== true || !cohorteValida(v['cohorte']) || !riesgoValido(v['riesgo'])) {
|
||||
throw new Error('Respuesta de riesgo individual DEV inválida');
|
||||
}
|
||||
return structuredClone(v) as unknown as RiesgoPacienteCacu;
|
||||
/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`, tagged `simulado` (DEV only).
|
||||
* `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and malformed fields. */
|
||||
export function riesgoPacienteResponse(v: unknown, pacId: string | null = null): RiesgoPacienteCacu | null {
|
||||
if (!record(v) || v['resourceType'] !== 'Bundle' || v['type'] !== 'searchset' || !finite(v['total'])) invalid();
|
||||
const entries = v['entry'] ?? [];
|
||||
if (!Array.isArray(entries)) invalid();
|
||||
if (entries.length === 0) return null;
|
||||
const resource = record(entries[0]) ? entries[0]['resource'] : undefined;
|
||||
if (!record(resource) || !simulated(resource)) invalid();
|
||||
return { simulado: true, riesgo: riskAssessment(structuredClone(resource), pacId) };
|
||||
}
|
||||
|
||||
/** Presentation helper: an incomplete interval must never become a fabricated range. */
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
// What this module covers: the screening route chart's model and figure. The model turns the seven C3r payloads of the
|
||||
// route (days from the sample and days from the previous event, per event) into one row per event for a period, and
|
||||
// chains the steps one after another; the figure draws them as horizontal bars of days.
|
||||
// Fixtures: `payload`, synthetic C3r /datos shaped like the WebApi's, with the values of the chart's mockup: a
|
||||
// cytology result at 7.9 days, a colposcopy at 35.7, a biopsy result at 52.1 and a diagnosis after it at 64.9.
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { C2_PALETTE } from './indicadores-c2-palette';
|
||||
import { drawnRows, ROUTE_IDS, routeCellText, routeFigure, routeHasData, routeModel, RouteIncompatible } from './screening-route';
|
||||
|
||||
type Box = [number, number, number, number];
|
||||
const row = (periodo: string, [n, q1, mediana, q3]: Box, extra: Record<string, unknown> = {}) =>
|
||||
({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido: 0, unidad: 'dias', ...extra });
|
||||
const payload = (id: string, filas: Record<string, unknown>[], periodos = ['2025-S1', '2025-S2']): IndicadorDatos =>
|
||||
({ id, contrato: 'C3r', tipo_periodo: 'semestre', periodos, filas, version: '1' });
|
||||
const S2: Record<string, Box> = {
|
||||
cacu_eu_tiempo_reporte: [4855, 4.9, 7.9, 12.2],
|
||||
cacu_dias_toma_colposcopia: [864, 22.2, 35.7, 55.4],
|
||||
cacu_dias_resultado_colposcopia: [864, 17, 27.8, 44],
|
||||
cacu_dias_toma_biopsia: [454, 32.4, 52.1, 80.8],
|
||||
cacu_dias_colposcopia_biopsia: [454, 10, 16.4, 26],
|
||||
cacu_dias_toma_diagnostico: [4999, 11.4, 18.4, 28.5],
|
||||
cacu_dias_biopsia_diagnostico: [454, 8, 12.8, 20],
|
||||
};
|
||||
function all(): Record<string, IndicadorDatos> {
|
||||
return Object.fromEntries(ROUTE_IDS.map(id => [id, payload(id, [row('2025-S1', [10, 1, 2, 3]), row('2025-S2', S2[id])])]));
|
||||
}
|
||||
const figure = (view: 'cumulative' | 'steps', data = all(), period?: string) => routeFigure(routeModel(data, 'semestre', period), view, 'claro');
|
||||
|
||||
describe('Ruta del tamizaje: modelo', () => {
|
||||
it('una fila por evento del periodo más reciente, con los pasos encadenados uno tras otro', () => {
|
||||
// Pins down: the newest period is the default and each step starts where the previous one ends (7.9 + 27.8 = 35.7,
|
||||
// + 16.4 = 52.1, + 12.8 = 64.9). Fails if the chain restarts at zero or follows another order.
|
||||
const m = routeModel(all(), 'semestre');
|
||||
expect(m.periods).toEqual(['2025-S2', '2025-S1']);
|
||||
expect(m.period).toBe('2025-S2');
|
||||
expect(m.rows.map(r => r.step.id)).toEqual(['cytology', 'colposcopy', 'biopsy', 'diagnosis']);
|
||||
expect(m.rows.map(r => [r.start, r.end!.toFixed(1)])).toEqual([[0, '7.9'], [7.9, '35.7'], [35.7, '52.1'], [52.1, '64.9']]);
|
||||
expect(m.rows[1].fromSample).toEqual({ estado: 'Publicado', n: 864, q1: 22.2, mediana: 35.7, q3: 55.4 });
|
||||
});
|
||||
it('un periodo pedido y publicado se usa; uno que no existe cae al más reciente', () => {
|
||||
// Fails if a period nobody published is shown empty instead of falling back.
|
||||
expect(routeModel(all(), 'semestre', '2025-S1').period).toBe('2025-S1');
|
||||
expect(routeModel(all(), 'semestre', '2024-S1').period).toBe('2025-S2');
|
||||
});
|
||||
it('un paso suprimido o sin datos no se dibuja y la cadena sigue desde el último publicado', () => {
|
||||
// Pins down: nothing is drawn as zero and the next step starts at the last published end. Fails if a suppressed box
|
||||
// becomes a bar or leaves a gap in the chain.
|
||||
const d = all();
|
||||
d['cacu_dias_colposcopia_biopsia'] = payload('cacu_dias_colposcopia_biopsia', [row('2025-S2', [454, 10, 16.4, 26], { suprimido: 1 })]);
|
||||
const m = routeModel(d, 'semestre');
|
||||
expect(m.rows[2]).toMatchObject({ start: null, end: null });
|
||||
expect(m.rows[3].start!.toFixed(1)).toBe('35.7');
|
||||
expect(drawnRows(m, 'steps').map(r => r.step.id)).toEqual(['cytology', 'colposcopy', 'diagnosis']);
|
||||
d['cacu_dias_toma_biopsia'] = payload('cacu_dias_toma_biopsia', []);
|
||||
expect(drawnRows(routeModel(d, 'semestre'), 'cumulative').map(r => r.step.id)).toEqual(['cytology', 'colposcopy', 'diagnosis']);
|
||||
});
|
||||
it('rechaza datos de otro indicador, contrato, tipo de periodo o unidad, y dos totales por periodo', () => {
|
||||
// Fails if a payload that doesn't belong to the route is drawn as if it did.
|
||||
const con = (id: string, cambio: Partial<IndicadorDatos>) => ({ ...all(), [id]: { ...all()[id], ...cambio } });
|
||||
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { id: 'otro' }), 'semestre')).toThrow(RouteIncompatible);
|
||||
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { contrato: 'C1' }), 'semestre')).toThrow(RouteIncompatible);
|
||||
expect(() => routeModel(all(), 'mes')).toThrow(RouteIncompatible);
|
||||
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { filas: [row('2025-S2', S2['cacu_eu_tiempo_reporte'], { unidad: 'horas' })] }), 'semestre')).toThrow(RouteIncompatible);
|
||||
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { filas: [row('2025-S2', [1, 1, 1, 1]), row('2025-S2', [2, 2, 2, 2])] }), 'semestre')).toThrow(RouteIncompatible);
|
||||
const sinUno = all(); delete sinUno['cacu_dias_toma_biopsia'];
|
||||
expect(() => routeModel(sinUno, 'semestre')).toThrow(RouteIncompatible);
|
||||
});
|
||||
it('sin periodos publicados no hay nada que dibujar', () => {
|
||||
// Fails if an empty catalog throws or draws an empty bar.
|
||||
const vacio = Object.fromEntries(ROUTE_IDS.map(id => [id, payload(id, [], [])]));
|
||||
const m = routeModel(vacio, 'semestre');
|
||||
expect(m.period).toBeUndefined();
|
||||
expect(routeHasData(m)).toBe(false);
|
||||
expect(routeFigure(m, 'cumulative', 'claro')).toEqual({ data: [], layout: {} });
|
||||
});
|
||||
it('la celda de la tabla dice el estado si no hay caja publicada', () => {
|
||||
expect(routeCellText({ estado: 'Suprimido' })).toBe('Suprimido');
|
||||
expect(routeCellText(routeModel(all(), 'semestre').rows[0].fromSample)).toBe('n = 4,855, Q1 4.9, mediana 7.9, Q3 12.2 días');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Ruta del tamizaje: figura', () => {
|
||||
it('acumulado: barras horizontales hasta la mediana con el intervalo de Q1 a Q3 y el número de casos', () => {
|
||||
// Pins down: orientation, bar lengths, the asymmetric interval, the case counts in the labels and the first
|
||||
// event on top. Fails if the bars stop being horizontal or the interval stops being Q1 to Q3.
|
||||
const f = figure('cumulative');
|
||||
const trace = f.data[0] as Record<string, any>;
|
||||
expect(trace['type']).toBe('bar');
|
||||
expect(trace['orientation']).toBe('h');
|
||||
expect(trace['x']).toEqual([7.9, 35.7, 52.1, 18.4]);
|
||||
expect(trace['error_x'].array.map((v: number) => +v.toFixed(1))).toEqual([4.3, 19.7, 28.7, 10.1]);
|
||||
expect(trace['error_x'].arrayminus.map((v: number) => +v.toFixed(1))).toEqual([3, 13.5, 19.7, 7]);
|
||||
expect(trace['y'][0]).toBe('Resultado de citología<br>n = 4,855');
|
||||
expect(trace['y']).toHaveLength(4);
|
||||
expect((f.layout['yaxis'] as Record<string, unknown>)['autorange']).toBe('reversed');
|
||||
expect(JSON.stringify(f.data)).not.toContain('null');
|
||||
});
|
||||
it('por pasos: cada barra flota desde donde termina la anterior y la más lenta lleva el color', () => {
|
||||
// Pins down: `base` equals the chained starts, the length is the step's own median, the slowest step (colposcopy,
|
||||
// 27.8 days) is the only one in colour. Fails if the steps stop floating or the emphasis moves.
|
||||
const f = figure('steps');
|
||||
const trace = f.data[0] as Record<string, any>;
|
||||
expect(trace['base'].map((v: number) => +v.toFixed(1))).toEqual([0, 7.9, 35.7, 52.1]);
|
||||
expect(trace['x']).toEqual([7.9, 27.8, 16.4, 12.8]);
|
||||
expect(trace['text']).toEqual(['+7.9 d', '+27.8 d', '+16.4 d', '+12.8 d']);
|
||||
expect(trace['marker'].color).toEqual([C2_PALETTE.states.noData, C2_PALETTE.series[0], C2_PALETTE.states.noData, C2_PALETTE.states.noData]);
|
||||
expect(trace['y'][1]).toBe('Del resultado de citología a la colposcopía<br>n = 864');
|
||||
expect(trace['hovertemplate']).toContain('Hasta el día');
|
||||
});
|
||||
it('un paso sin caja se omite de la figura sin dejar huecos', () => {
|
||||
// Fails if an undrawn step keeps its label or leaves a null in the traces.
|
||||
const d = all();
|
||||
d['cacu_dias_toma_biopsia'] = payload('cacu_dias_toma_biopsia', [row('2025-S2', S2['cacu_dias_toma_biopsia'], { suprimido: 1 })]);
|
||||
const trace = figure('cumulative', d).data[0] as Record<string, any>;
|
||||
expect(trace['y']).toHaveLength(3);
|
||||
expect(trace['x']).toEqual([7.9, 35.7, 18.4]);
|
||||
});
|
||||
it('el tema oscuro cambia fondo y texto, no los datos', () => {
|
||||
const claro = figure('steps'), oscuro = routeFigure(routeModel(all(), 'semestre'), 'steps', 'oscuro');
|
||||
expect(oscuro.layout['paper_bgcolor']).toBe('#081839');
|
||||
expect(claro.layout['paper_bgcolor']).toBe('#FFFFFF');
|
||||
expect(oscuro.data[0]['x']).toEqual(claro.data[0]['x']);
|
||||
});
|
||||
});
|
||||
@@ -1,130 +0,0 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||
import { Caja, caja } from './indicadores-tiempos-pareados';
|
||||
|
||||
/**
|
||||
* The screening route as a chain of events timed from the sample: the cytology result, the colposcopy, the biopsy
|
||||
* result and the diagnosis. Each event has two C3r measures: the days from the sample and the days from the previous
|
||||
* event. The cytology's step is its own days from the sample.
|
||||
*/
|
||||
export interface RouteStep {
|
||||
id: 'cytology' | 'colposcopy' | 'biopsy' | 'diagnosis';
|
||||
label: string;
|
||||
stepLabel: string;
|
||||
sinceSample: string;
|
||||
sinceStep: string;
|
||||
}
|
||||
export const ROUTE_STEPS: readonly RouteStep[] = [
|
||||
{ id: 'cytology', label: 'Resultado de citología', stepLabel: 'Toma a resultado de citología',
|
||||
sinceSample: 'cacu_eu_tiempo_reporte', sinceStep: 'cacu_eu_tiempo_reporte' },
|
||||
{ id: 'colposcopy', label: 'Resultado de colposcopía', stepLabel: 'Del resultado de citología a la colposcopía',
|
||||
sinceSample: 'cacu_dias_toma_colposcopia', sinceStep: 'cacu_dias_resultado_colposcopia' },
|
||||
{ id: 'biopsy', label: 'Resultado de biopsia', stepLabel: 'De la colposcopía al resultado de biopsia',
|
||||
sinceSample: 'cacu_dias_toma_biopsia', sinceStep: 'cacu_dias_colposcopia_biopsia' },
|
||||
{ id: 'diagnosis', label: 'Diagnóstico', stepLabel: 'Del resultado de biopsia al diagnóstico',
|
||||
sinceSample: 'cacu_dias_toma_diagnostico', sinceStep: 'cacu_dias_biopsia_diagnostico' },
|
||||
];
|
||||
/** Every measure the chart reads, once each. */
|
||||
export const ROUTE_IDS: readonly string[] = [...new Set(ROUTE_STEPS.flatMap(s => [s.sinceSample, s.sinceStep]))];
|
||||
|
||||
/** The measures only this chart draws: the cytology's and the diagnosis' keep their own cards. */
|
||||
export const ROUTE_ONLY_IDS: readonly string[] = ROUTE_IDS.filter(id => id !== 'cacu_eu_tiempo_reporte' && id !== 'cacu_dias_toma_diagnostico');
|
||||
|
||||
export type RouteView = 'cumulative' | 'steps';
|
||||
export interface RouteRow {
|
||||
step: RouteStep;
|
||||
fromSample: Caja;
|
||||
fromPrevious: Caja;
|
||||
/** Where the step starts and ends on the days axis, when chained one after another; null without a published box. */
|
||||
start: number | null;
|
||||
end: number | null;
|
||||
}
|
||||
export interface RouteModel { period: string | undefined; periods: string[]; rows: RouteRow[]; }
|
||||
export class RouteIncompatible extends Error {}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const fail = (message: string): never => { throw new RouteIncompatible(message); };
|
||||
const NOT_AVAILABLE: Caja = { estado: 'No disponible' };
|
||||
|
||||
/** The seven C3r /datos payloads -> one row per event for a period, newest period first when none is requested. */
|
||||
export function routeModel(data: Record<string, IndicadorDatos>, tipo: TipoPeriodo, requested?: string): RouteModel {
|
||||
const boxes: Record<string, Record<string, Caja>> = {};
|
||||
for (const id of ROUTE_IDS) {
|
||||
const d = data[id];
|
||||
if (!d || d.id !== id || d.contrato !== 'C3r' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|
||||
|| new Set(d.periodos).size !== d.periodos.length) {
|
||||
fail('Los datos de tiempos no corresponden a los indicadores de la ruta del tamizaje.');
|
||||
}
|
||||
boxes[id] = {};
|
||||
for (const row of d.filas) {
|
||||
if (!record(row) || typeof row['periodo'] !== 'string' || !d.periodos.includes(row['periodo'])) fail('Fila C3r fuera de los periodos publicados.');
|
||||
if (row['grupo'] !== 'TOTAL' || row['estrato'] != null) continue;
|
||||
if (row['unidad'] !== undefined && row['unidad'] !== 'dias') fail('Unidad de tiempo distinta de días.');
|
||||
const period = row['periodo'] as string;
|
||||
if (boxes[id][period]) fail('Más de una fila total por periodo.');
|
||||
boxes[id][period] = caja(row);
|
||||
}
|
||||
}
|
||||
const periods = [...new Set(ROUTE_IDS.flatMap(id => data[id].periodos))].sort().reverse();
|
||||
const period = requested && periods.includes(requested) ? requested : periods[0];
|
||||
let cursor = 0;
|
||||
const rows = ROUTE_STEPS.map((step): RouteRow => {
|
||||
const fromSample = period ? boxes[step.sinceSample][period] ?? NOT_AVAILABLE : NOT_AVAILABLE;
|
||||
const fromPrevious = period ? boxes[step.sinceStep][period] ?? NOT_AVAILABLE : NOT_AVAILABLE;
|
||||
if (fromPrevious.estado !== 'Publicado') return { step, fromSample, fromPrevious, start: null, end: null };
|
||||
const start = cursor;
|
||||
cursor += fromPrevious.mediana!;
|
||||
return { step, fromSample, fromPrevious, start, end: cursor };
|
||||
});
|
||||
return { period, periods, rows };
|
||||
}
|
||||
|
||||
/** The rows with a published box for the view. */
|
||||
export function drawnRows(model: RouteModel, view: RouteView): RouteRow[] {
|
||||
return model.rows.filter(row => (view === 'cumulative' ? row.fromSample : row.fromPrevious).estado === 'Publicado');
|
||||
}
|
||||
export const routeHasData = (model: RouteModel) => drawnRows(model, 'cumulative').length > 0 || drawnRows(model, 'steps').length > 0;
|
||||
|
||||
const days = (v: number) => v.toLocaleString('es-MX', { maximumFractionDigits: 1 });
|
||||
const count = (v: number) => v.toLocaleString('es-MX');
|
||||
|
||||
/**
|
||||
* Horizontal bars of days. Cumulative: from the sample to each event, with the Q1 to Q3 range as the interval. Steps:
|
||||
* each step floats from where the previous one ends, and the slowest is the one in colour.
|
||||
*/
|
||||
export function routeFigure(model: RouteModel, view: RouteView, tema: Tema): PlotlyFigure {
|
||||
const t = c2Theme(tema);
|
||||
const rows = drawnRows(model, view);
|
||||
if (!rows.length) return { data: [], layout: {} };
|
||||
const base = { autosize: true, height: 360, showlegend: false, paper_bgcolor: t.background, plot_bgcolor: t.background, font: { color: t.text },
|
||||
margin: { t: 24, l: 150, r: 32, b: 56 } };
|
||||
const axes = {
|
||||
xaxis: { title: { text: 'Días' }, rangemode: 'tozero', gridcolor: t.grid, zeroline: false, fixedrange: true },
|
||||
yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true },
|
||||
};
|
||||
if (view === 'cumulative') {
|
||||
const boxes = rows.map(row => row.fromSample);
|
||||
return { data: [{
|
||||
type: 'bar', orientation: 'h', y: rows.map((row, i) => `${row.step.label}<br>n = ${count(boxes[i].n!)}`), x: boxes.map(b => b.mediana),
|
||||
marker: { color: C2_PALETTE.series[0] },
|
||||
error_x: { type: 'data', symmetric: false, color: t.text, thickness: 1.5, width: 6,
|
||||
array: boxes.map(b => b.q3! - b.mediana!), arrayminus: boxes.map(b => b.mediana! - b.q1!) },
|
||||
customdata: boxes.map(b => [count(b.n!), days(b.q1!), days(b.mediana!), days(b.q3!)]),
|
||||
hovertemplate: '%{y}<br>Mediana: %{customdata[2]} días<br>Q1 a Q3: %{customdata[1]} a %{customdata[3]} días<extra></extra>',
|
||||
}], layout: { ...base, ...axes }, config: { displayModeBar: false } };
|
||||
}
|
||||
const slowest = rows.reduce((best, row, i) => (row.fromPrevious.mediana! > rows[best].fromPrevious.mediana! ? i : best), 0);
|
||||
const boxes = rows.map(row => row.fromPrevious);
|
||||
return { data: [{
|
||||
type: 'bar', orientation: 'h', y: rows.map((row, i) => `${row.step.stepLabel}<br>n = ${count(boxes[i].n!)}`), x: boxes.map(b => b.mediana),
|
||||
base: rows.map(row => row.start),
|
||||
marker: { color: rows.map((_, i) => (i === slowest ? C2_PALETTE.series[0] : C2_PALETTE.states.noData)) },
|
||||
text: boxes.map(b => `+${days(b.mediana!)} d`), textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' }, cliponaxis: false,
|
||||
customdata: rows.map((row, i) => [count(boxes[i].n!), days(boxes[i].q1!), days(boxes[i].mediana!), days(boxes[i].q3!), days(row.end!)]),
|
||||
hovertemplate: '%{y}<br>Tramo: %{customdata[2]} días (Q1 a Q3: %{customdata[1]} a %{customdata[3]})<br>Hasta el día %{customdata[4]}<extra></extra>',
|
||||
}], layout: { ...base, ...axes }, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
export function routeCellText(box: Caja): string {
|
||||
return box.estado !== 'Publicado' ? box.estado : `n = ${count(box.n!)}, Q1 ${days(box.q1!)}, mediana ${days(box.mediana!)}, Q3 ${days(box.q3!)} días`;
|
||||
}
|
||||
Reference in New Issue
Block a user