Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fb54cfb188 | |||
| 4e9b25bd8f | |||
| 68e2930e65 | |||
| bb957ec6a4 | |||
| 02e28e624b | |||
| 08161db1c4 | |||
| fa029d69b8 | |||
| 67ae7f482f | |||
| 304c563845 | |||
| b53322ed72 |
@@ -7,19 +7,14 @@ const HISTOLOGIA: Readonly<Record<string, string>> = {
|
||||
BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ',
|
||||
CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido',
|
||||
};
|
||||
const ESCENARIOS: Readonly<Record<string, string>> = { POST_TRATAMIENTO: 'Post-tratamiento', EN_OBSERVACION: 'En observación' };
|
||||
|
||||
/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */
|
||||
export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo;
|
||||
/** «50-59» as «50 a 59 años». Any other text is returned as it came. */
|
||||
export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo;
|
||||
export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo;
|
||||
/** The patient's clinical scenario at the cut-off: «Post-tratamiento» or «En observación». */
|
||||
export const etiquetaEscenario = (codigo: string) => ESCENARIOS[codigo] ?? codigo;
|
||||
|
||||
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = {
|
||||
birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia, escenario_clinico: etiquetaEscenario,
|
||||
};
|
||||
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia };
|
||||
|
||||
/** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */
|
||||
export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo);
|
||||
|
||||
@@ -6,7 +6,7 @@ export interface Concept { coding?: Coding[]; text?: string }
|
||||
export interface Quantity { value?: number; unit?: string }
|
||||
export interface Extension {
|
||||
url: string;
|
||||
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number;
|
||||
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number; valueBoolean?: boolean;
|
||||
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
|
||||
extension?: Extension[];
|
||||
}
|
||||
|
||||
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,51 +80,14 @@
|
||||
"filas": []
|
||||
},
|
||||
"citologia_alto_grado": {
|
||||
"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": []
|
||||
"error": "Categoría no declarada en el estrato"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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",
|
||||
@@ -139,7 +102,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": {
|
||||
@@ -171,7 +134,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",
|
||||
@@ -239,9 +202,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",
|
||||
@@ -256,7 +219,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": {
|
||||
@@ -288,7 +251,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",
|
||||
@@ -356,9 +319,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",
|
||||
@@ -376,7 +339,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": {
|
||||
@@ -408,7 +371,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "CACU_EU13",
|
||||
"id": "cacu_eu13",
|
||||
"titulo": "Tasa de detección histopatológica",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
@@ -474,7 +437,7 @@
|
||||
]
|
||||
},
|
||||
"grupo_edad": {
|
||||
"id": "CACU_EU13",
|
||||
"id": "cacu_eu13",
|
||||
"titulo": "Tasa de detección histopatológica",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
@@ -592,7 +555,7 @@
|
||||
]
|
||||
},
|
||||
"estatus_seguimiento": {
|
||||
"id": "CACU_EU13",
|
||||
"id": "cacu_eu13",
|
||||
"titulo": "Tasa de detección histopatológica",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
@@ -652,9 +615,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",
|
||||
@@ -672,7 +635,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": {
|
||||
@@ -694,7 +657,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "CACU_EU7",
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.3.3",
|
||||
"contrato": "C2",
|
||||
@@ -733,91 +696,17 @@
|
||||
"filas": []
|
||||
},
|
||||
"grupo_edad": {
|
||||
"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": []
|
||||
"error": "Categoría no declarada en el estrato"
|
||||
},
|
||||
"estatus_seguimiento": {
|
||||
"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": []
|
||||
"error": "Categoría no declarada en el estrato"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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",
|
||||
@@ -831,7 +720,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": {
|
||||
@@ -853,7 +742,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",
|
||||
@@ -894,9 +783,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",
|
||||
@@ -911,7 +800,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": {
|
||||
@@ -943,7 +832,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "IND1",
|
||||
"id": "ind1",
|
||||
"titulo": "Pacientes con citología anómala",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
|
||||
@@ -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 { stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
|
||||
|
||||
@@ -101,7 +101,8 @@ 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) || !compatibility.compatible) {
|
||||
|| !(stratifiedCapabilities(this.indicador).includes(ESTRATO) || declaraEstrato(this.indicador, 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;
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
||||
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
|
||||
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
|
||||
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||
import { etiquetaDimension, MedidaEstrato, stratifiedBars, stratifiedCapabilities, StratifiedCell, StratumOption, stratumOptions } from './indicadores-stratified';
|
||||
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
|
||||
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||
import { c2GeneralSelection } from './indicadores-c2-general-selection';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
@@ -25,48 +25,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
selector: 'app-indicador-figure-panel',
|
||||
imports: [IndicadorFigureCard, MatTooltipModule],
|
||||
template: `
|
||||
<section class="figure-panel" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
|
||||
<section class="figure-panel" [attr.aria-labelledby]="titleId">
|
||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
|
||||
@if (sidebar) {
|
||||
<aside class="strata-sidebar" aria-label="Estratificación">
|
||||
<fieldset class="sidebar-group">
|
||||
<legend>Estratificar por</legend>
|
||||
<div class="sidebar-list" role="radiogroup" aria-label="Dimensión de la distribución">
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === ''" [class.active]="dimension === ''"
|
||||
(click)="changeDimension('')">Sin estratificar</button>
|
||||
@for (d of capabilities; track d) {
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
|
||||
[disabled]="!singlePeriod" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null"
|
||||
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
|
||||
}
|
||||
</div>
|
||||
</fieldset>
|
||||
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para estratificar.</p> }
|
||||
@if (dimension && estratos.length > 1) {
|
||||
<fieldset class="sidebar-group">
|
||||
<legend>Mostrar</legend>
|
||||
<p class="sidebar-status" role="status" aria-live="polite">{{ ocultos.size ? (estratos.length - ocultos.size) + ' de ' + estratos.length : 'Todos los valores' }}</p>
|
||||
<div class="sidebar-list" role="group" aria-label="Valores del estrato">
|
||||
@for (e of estratos; track e.valor) {
|
||||
<button type="button" class="stratum-toggle" [attr.aria-pressed]="!ocultos.has(e.valor)" [class.active]="!ocultos.has(e.valor)"
|
||||
[disabled]="!ocultos.has(e.valor) && ocultos.size === estratos.length - 1"
|
||||
(click)="toggleEstrato(e.valor)">{{ e.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<button type="button" class="sidebar-reset" [disabled]="!ocultos.size" (click)="mostrarTodos()">Mostrar todos</button>
|
||||
</fieldset>
|
||||
}
|
||||
@if (dimension) {
|
||||
<fieldset class="sidebar-group">
|
||||
<legend>Medida</legend>
|
||||
<div class="sidebar-list distribution-medida" role="radiogroup" aria-label="Medida por estrato">
|
||||
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
|
||||
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
}
|
||||
</aside>
|
||||
}
|
||||
<header class="panel-controls">
|
||||
<p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p>
|
||||
@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) {
|
||||
@@ -76,7 +36,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
{{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }}
|
||||
</span>
|
||||
}
|
||||
@if (figuraId === 'fig_c2_barras' && capabilities.length && !sidebar) {
|
||||
@if (figuraId === 'fig_c2_barras' && capabilities.length) {
|
||||
<fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null">
|
||||
<legend>Distribución</legend>
|
||||
<div class="distribution-toggle" role="radiogroup" aria-label="Tipo de distribución">
|
||||
@@ -89,16 +49,10 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
|
||||
@for (d of capabilities; track d) {
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
|
||||
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
|
||||
(click)="changeDimension(d)">{{ d === 'grupo_edad' ? 'Por grupo de edad' : 'Por estatus de seguimiento' }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@if (dimension) {
|
||||
<div class="distribution-dimensions distribution-medida" role="radiogroup" aria-label="Medida por estrato">
|
||||
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
|
||||
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
|
||||
</div>
|
||||
}
|
||||
</fieldset>
|
||||
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
|
||||
}
|
||||
@@ -117,8 +71,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
|
||||
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
|
||||
<details><summary>Valores publicados</summary>
|
||||
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th><th>Porcentaje del estrato</th></tr></thead><tbody>
|
||||
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td><td>{{ cell.percent === null ? '—' : cell.percent + ' %' }}</td></tr> }
|
||||
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th></tr></thead><tbody>
|
||||
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td></tr> }
|
||||
</tbody></table></div>
|
||||
</details>
|
||||
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
|
||||
@@ -163,30 +117,6 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
.donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; }
|
||||
.donut-periods button:disabled { opacity: .45; }
|
||||
.donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
/* Many stratifiers: a list beside the bars while the panel is wide, above them when it isn't. The rows stay
|
||||
shared with the neighbouring panel, so the bars line up with the donut. */
|
||||
:host { container-type: inline-size; }
|
||||
.figure-panel.with-sidebar { grid-template-columns: minmax(10rem, 13rem) minmax(0, 1fr); column-gap: var(--issste-space-4); }
|
||||
.with-sidebar > :not(.strata-sidebar) { grid-column: 2; }
|
||||
.strata-sidebar { grid-column: 1; grid-row: 1 / -1; align-self: start; position: sticky; top: var(--issste-header-clearance, 0);
|
||||
display: grid; gap: var(--issste-space-3); padding-block: var(--issste-space-3); min-width: 0; }
|
||||
.sidebar-group { margin: 0; padding: 0; border: 0; min-width: 0; }
|
||||
.sidebar-group legend { padding: 0; margin-bottom: .5rem; font-weight: 600; }
|
||||
.sidebar-list { display: grid; gap: .25rem; }
|
||||
.sidebar-list button, .sidebar-reset { min-height: 44px; width: 100%; padding: .5rem .75rem; text-align: start;
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface);
|
||||
color: var(--issste-text); font: inherit; overflow-wrap: anywhere; cursor: pointer; }
|
||||
.sidebar-list button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
|
||||
.sidebar-list .stratum-toggle:not(.active) { color: var(--issste-text-secondary); text-decoration: line-through; }
|
||||
.sidebar-list button:disabled, .sidebar-reset:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.sidebar-list button:focus-visible, .sidebar-reset:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
.sidebar-reset { margin-top: .5rem; }
|
||||
.sidebar-status { margin: 0 0 .5rem; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
|
||||
@container (max-width: 559px) {
|
||||
.figure-panel.with-sidebar { display: flex; flex-direction: column; }
|
||||
.strata-sidebar { position: static; }
|
||||
.sidebar-list { grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr)); }
|
||||
}
|
||||
.visually-hidden {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
|
||||
@@ -235,39 +165,7 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
|
||||
}
|
||||
dimension: DimensionEstrato | '' = '';
|
||||
readonly etiquetaDimension = etiquetaDimension;
|
||||
// Counts or each category's share of its stratum; an indicator can ask to open with the share.
|
||||
private medidaElegida?: MedidaEstrato;
|
||||
get medida(): MedidaEstrato { return this.medidaElegida ?? this.indicador.medida_estrato ?? 'conteo'; }
|
||||
changeMedida(medida: MedidaEstrato) {
|
||||
if (medida === this.medida) return;
|
||||
this.medidaElegida = medida;
|
||||
this.representStratified();
|
||||
}
|
||||
cells: StratifiedCell[] = [];
|
||||
/** More stratifiers than a row of buttons holds comfortably: they go in a list beside the bars. */
|
||||
get sidebar() { return this.figuraId === 'fig_c2_barras' && this.capabilities.length > 2; }
|
||||
estratos: StratumOption[] = [];
|
||||
ocultos = new Set<string>();
|
||||
toggleEstrato(valor: string) {
|
||||
const ocultos = new Set(this.ocultos);
|
||||
if (ocultos.has(valor)) ocultos.delete(valor);
|
||||
else if (ocultos.size < this.estratos.length - 1) ocultos.add(valor);
|
||||
else return;
|
||||
this.ocultos = ocultos;
|
||||
this.representStratified();
|
||||
}
|
||||
mostrarTodos() {
|
||||
if (!this.ocultos.size) return;
|
||||
this.ocultos = new Set();
|
||||
this.representStratified();
|
||||
}
|
||||
private representStratified() {
|
||||
if (this.dimension && this.stratifiedData && this.result().status === 'ready') {
|
||||
try { this.result.set(this.presentStratified(this.stratifiedData)); }
|
||||
catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); }
|
||||
}
|
||||
}
|
||||
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
|
||||
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
|
||||
private stratifiedData?: IndicadorDatos;
|
||||
@@ -279,18 +177,14 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
changeDimension(value: DimensionEstrato | '') {
|
||||
if (value && (!this.capabilities.includes(value) || !this.singlePeriod)) return;
|
||||
if (this.dimension === value) return;
|
||||
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.estratos = []; this.ocultos = new Set();
|
||||
this.requestFigure();
|
||||
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.requestFigure();
|
||||
}
|
||||
chooseStratified() {
|
||||
if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]);
|
||||
}
|
||||
private presentStratified(data: IndicadorDatos): FigureState {
|
||||
const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {};
|
||||
this.estratos = stratumOptions(data);
|
||||
const publicados = new Set(this.estratos.map(e => e.valor));
|
||||
if ([...this.ocultos].some(v => !publicados.has(v))) this.ocultos = new Set([...this.ocultos].filter(v => publicados.has(v)));
|
||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida, this.ocultos);
|
||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local);
|
||||
this.cells = adapted.cells;
|
||||
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
|
||||
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
|
||||
@@ -455,9 +349,7 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
}
|
||||
}
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) {
|
||||
this.dimension = ''; this.estratos = []; this.ocultos = new Set();
|
||||
}
|
||||
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) this.dimension = '';
|
||||
const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId);
|
||||
if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; }
|
||||
this.titleId = identityElementId(identity) + '-title';
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
// 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([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
// 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';
|
||||
|
||||
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');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
// 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-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 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.
|
||||
// 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.
|
||||
expect(indicadorId('M21-diagnosticados-con-eeg')).toBe('M21_diagnosticados_con_eeg');
|
||||
expect(indicadorId('CACU-EU7')).toBe('CACU_EU7');
|
||||
expect(Object.hasOwn(CAMA_MEASURE_IDS, 'CACU-EU7')).toBe(false);
|
||||
});
|
||||
|
||||
it('el catálogo lleva contrato, figuras y periodos de cada medida', () => {
|
||||
|
||||
@@ -9,7 +9,7 @@ import { strFromU8, unzipSync } from 'fflate';
|
||||
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
|
||||
import { camaPatientDocument } from './paciente-detalle/cama/cama-patient-pdf';
|
||||
import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
|
||||
import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaEscenario, etiquetaHistologia } from './etiquetas-cohorte';
|
||||
import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaHistologia } from './etiquetas-cohorte';
|
||||
import { CONTEXTO, listaCohorte } from './indicadores-analisis.testing';
|
||||
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service';
|
||||
@@ -33,17 +33,6 @@ describe('Etiquetas de la cohorte', () => {
|
||||
expect(etiquetaDeFiltro('birads', 'BIRADS_5')).toBe('BI-RADS 5'); expect(etiquetaDeFiltro('prioridad', 'ALTA')).toBe('ALTA');
|
||||
expect(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'DESCONOCIDO', 'OTRO'].map(etiquetaHistologia))
|
||||
.toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Desconocido', 'OTRO']);
|
||||
expect(['POST_TRATAMIENTO', 'EN_OBSERVACION', 'CONTROL'].map(etiquetaEscenario)).toEqual(['Post-tratamiento', 'En observación', 'CONTROL']);
|
||||
});
|
||||
it('el escenario clínico de una fila se lee «Post-tratamiento» o «En observación» en la lista y en la ficha, con su código guardado', () => {
|
||||
// Fails if the list or the record show the scenario's code, or the code the filter sends is lost.
|
||||
const cruda = listaCohorte();
|
||||
const items = cruda['items'] as Record<string, unknown>[];
|
||||
items[0]['escenario_clinico'] = 'POST_TRATAMIENTO'; items[1]['escenario_clinico'] = 'EN_OBSERVACION';
|
||||
const r = seguimientoTablaResponse(cruda);
|
||||
expect(r.items[0]).toMatchObject({ escenario_clinico: 'Post-tratamiento', escenario_clinico_codigo: 'POST_TRATAMIENTO' });
|
||||
expect(r.items[1]).toMatchObject({ escenario_clinico: 'En observación', escenario_clinico_codigo: 'EN_OBSERVACION' });
|
||||
expect(toCamaPatientSummary(r.items[0], '2026-01-01')?.clinicalScenario).toBe('Post-tratamiento');
|
||||
});
|
||||
it('la respuesta de una cohorte se escribe una vez: opciones y filas legibles, con el código guardado, y una lista sin cohorte no cambia', () => {
|
||||
// Fails if the table, the record and the files can still show the code, or the code is lost for the requests.
|
||||
|
||||
@@ -228,17 +228,18 @@ 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' };
|
||||
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)]);
|
||||
// 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)}`);
|
||||
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)), customdata: custom(interior),
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), hovertext: hoverText(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)), customdata: custom(exterior),
|
||||
labels: m.grados.map(g => escapar(g.etiqueta)), hovertext: hoverText(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,8 +119,12 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
||||
return active[0];
|
||||
};
|
||||
const rg = reporte(general), re = reporte(porEscenario);
|
||||
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.');
|
||||
// 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 (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.
|
||||
@@ -145,17 +149,20 @@ 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) return fail('No hay escenarios que correspondan a los datos generales.');
|
||||
} else if (g.size && !generalEnCeros) 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,
|
||||
total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size || (generalEnCeros && !escenarios.length),
|
||||
notas: [...new Set([...(general.notas ?? []), ...(porEscenario.notas ?? [])])] };
|
||||
}
|
||||
const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo);
|
||||
@@ -193,19 +200,20 @@ 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' };
|
||||
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!)]);
|
||||
// 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`);
|
||||
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' }, customdata: custom(interior),
|
||||
textfont: { color: '#FFFFFF' }, hovertext: hoverText(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 }, customdata: custom(exterior),
|
||||
textfont: { size: 11 }, hovertext: hoverText(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 } };
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
// technical sheet from `Measure`, the data rows from `MeasureReport`, the periods from two one-report searches, the
|
||||
// C3r box plot, and the follow-up list and patient summary from `EpisodeOfCare` and `$resumen-tea`; each mapped into
|
||||
// the shapes the page reads and passed through the same checks.
|
||||
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database.
|
||||
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database; `conModelo`
|
||||
// below adds to its patient summary the age at the EEG, a metric's age-norm curve and the ADOS-2 association model,
|
||||
// in the shape `webapi/fhir/tea.py` emits them.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { Bundle, resources } from './fhir';
|
||||
import { Bundle, Resource, resources } from './fhir';
|
||||
import {
|
||||
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado,
|
||||
periodosDesde, Report,
|
||||
@@ -20,6 +22,49 @@ import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-f
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
|
||||
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
|
||||
|
||||
const SD = 'https://isssteleon.org/fhir/StructureDefinition';
|
||||
const CS = 'https://isssteleon.org/fhir/CodeSystem';
|
||||
const CURVA = `${SD}/curva-referencia`;
|
||||
const curva = {
|
||||
url: CURVA, extension: [
|
||||
{ url: `${CURVA}/fuente`, valueString: 'tea-ritmo_posterior/3' }, { url: `${CURVA}/estado`, valueString: 'validada' },
|
||||
...[12, 24, 36].map(v => ({ url: `${CURVA}/edad-meses`, valueDecimal: v })),
|
||||
...([['p5', [4, 4.5, 5]], ['p25', [5, 5.5, 6]], ['mediana', [5.5, 6, 6.5]], ['p75', [6, 6.5, 7]], ['p95', [6.5, 7, 7.5]]] as [string, number[]][])
|
||||
.flatMap(([p, vs]) => vs.map(v => ({ url: `${CURVA}/${p}`, valueDecimal: v }))),
|
||||
],
|
||||
};
|
||||
const prediccion = (zona: string, z: number | null) => ({
|
||||
outcome: { coding: [{ system: `${CS}/tea-catalogo`, code: 'ados2.sa_b9', display: 'Mostrar' }] },
|
||||
probabilityDecimal: 0.41,
|
||||
extension: [
|
||||
{ url: `${SD}/biomarcador`, valueCoding: { system: `${CS}/tea-eeg-metrica`, code: 'RITMO_POSTERIOR', display: 'Ritmo posterior' } },
|
||||
{ url: `${SD}/zona`, valueCoding: { system: `${CS}/tea-eeg-zona`, code: zona, display: 'Occipital' } },
|
||||
{ url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=2' },
|
||||
...(z === null ? [] : [{ url: `${SD}/valor-z`, valueDecimal: z }]),
|
||||
{ url: `${SD}/odds-ratio`, valueDecimal: 0.5 }, { url: `${SD}/ic-inf`, valueDecimal: 0.3 }, { url: `${SD}/ic-sup`, valueDecimal: 0.8 },
|
||||
{ url: `${SD}/q`, valueDecimal: 0.01 }, { url: `${SD}/probabilidad-referencia`, valueDecimal: 0.2 }, { url: `${SD}/observado`, valueInteger: 2 },
|
||||
],
|
||||
});
|
||||
// The fixture's patient summary with what the WebApi adds when the analysis and the association model have data.
|
||||
function conModelo(): Bundle {
|
||||
const bundle = structuredClone(fx.resumenPaciente) as Bundle;
|
||||
for (const r of resources(bundle)) {
|
||||
if (r.resourceType === 'DiagnosticReport') r.extension = [...(r.extension ?? []), { url: `${SD}/edad-meses`, valueDecimal: 23.6 }];
|
||||
const codigo = (r['code'] as { coding?: { code?: string }[] } | undefined)?.coding?.[0]?.code;
|
||||
if (r.resourceType === 'Observation' && codigo === 'ritmo_posterior' && !r.id?.startsWith('electrodos-'))
|
||||
r.extension = [...(r.extension ?? []), curva];
|
||||
}
|
||||
const riesgo: Resource = {
|
||||
resourceType: 'RiskAssessment', id: 'relacion-ados2-P-4A59E9D8B4', status: 'final',
|
||||
meta: { tag: resources(bundle)[0].meta?.tag },
|
||||
extension: [{ url: `${SD}/modelo-version`, valueString: '1.0.0' }, { url: `${SD}/modelo-validado`, valueBoolean: false },
|
||||
{ url: `${SD}/modelo-nivel`, valueString: 'item' }, { url: `${SD}/modelo-n-cohorte`, valueInteger: 40 }],
|
||||
prediction: [prediccion('occipital', -2.6), prediccion('parietal', null)],
|
||||
};
|
||||
bundle.entry = [...(bundle.entry ?? []), { resource: riesgo }];
|
||||
return bundle;
|
||||
}
|
||||
const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[];
|
||||
|
||||
describe('Indicadores sobre FHIR', () => {
|
||||
@@ -210,6 +255,49 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(codigos.filter(c => c === 'ritmo_posterior').length).toBe(1);
|
||||
});
|
||||
|
||||
it('el resumen lleva la edad al EEG y la norma por edad de la métrica cuando la WebApi las manda', async () => {
|
||||
// Pins down: the report's `edad-meses` extension as the EEG's age and a metric observation's `curva-referencia`
|
||||
// sub-extensions read back in order as the age norm (ages, five percentiles, source and state), so the page's
|
||||
// checks accept it. Fails if the adapter stops reading either extension or scrambles the series.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const detalle = await answer;
|
||||
expect(detalle.eeg!.edad_meses).toBe(23.6);
|
||||
expect(detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!.curva_referencia).toEqual({
|
||||
fuente: 'tea-ritmo_posterior/3', estado: 'validada', edad_meses: [12, 24, 36],
|
||||
p5: [4, 4.5, 5], p25: [5, 5.5, 6], mediana: [5.5, 6, 6.5], p75: [6, 6.5, 7], p95: [6.5, 7, 7.5] });
|
||||
});
|
||||
|
||||
it('el resumen arma la relación con el ADOS-2 del RiskAssessment y deja fuera la fila incompleta', async () => {
|
||||
// Pins down: the model's version, validation, level and cohort from the resource's extensions, and each
|
||||
// prediction as a row with the metric's and zone's labels, the outcome, OR, interval, q, z, both probabilities
|
||||
// and the observed score; a prediction without its z is dropped instead of failing the page's checks. Fails if
|
||||
// the adapter stops reading the RiskAssessment or lets an incomplete row through.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const relacion = (await answer).relacion_ados2!;
|
||||
expect(relacion).toMatchObject({ version: '1.0.0', validado: false, nivel: 'item', n_cohorte: 40 });
|
||||
expect(relacion.filas).toEqual([{
|
||||
biomarcador: 'Ritmo posterior', zona: 'occipital', zona_etiqueta: 'Occipital', valor_z: -2.6, tipo: 'item',
|
||||
resultado: 'ados2.sa_b9', resultado_etiqueta: 'Mostrar', evento: '>=2', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01,
|
||||
probabilidad: 0.41, probabilidad_referencia: 0.2, observado: 2 }]);
|
||||
});
|
||||
|
||||
it('sin edad, norma ni modelo el resumen no inventa esos campos', async () => {
|
||||
// Pins down: a summary without the new extensions or a RiskAssessment (the fixture as the WebApi served it before
|
||||
// the analysis wrote them) leaves `edad_meses`, `curva_referencia` and `relacion_ados2` out, so the page hides
|
||||
// the chart and the panel. Fails if the adapter fills them with defaults.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const detalle = await answer;
|
||||
expect('edad_meses' in detalle.eeg!).toBe(false);
|
||||
expect(detalle.eeg!.alteraciones.some(a => 'curva_referencia' in a)).toBe(false);
|
||||
expect('relacion_ados2' in detalle).toBe(false);
|
||||
});
|
||||
|
||||
it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => {
|
||||
// Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no
|
||||
// value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes.
|
||||
|
||||
@@ -13,6 +13,7 @@ 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
|
||||
@@ -40,8 +41,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
|
||||
// have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`).
|
||||
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? measureId.replace(/-/g, '_');
|
||||
// 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, '_');
|
||||
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,10 +57,21 @@ function decimal(score: Score | undefined, name: string): number | null {
|
||||
}
|
||||
const round1 = (value: number) => Math.round(value * 10) / 10;
|
||||
|
||||
// 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: null }]] : [];
|
||||
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]] : [];
|
||||
}));
|
||||
}
|
||||
function contrato(measure: Measure): string {
|
||||
@@ -193,6 +205,34 @@ 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);
|
||||
@@ -200,6 +240,8 @@ 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];
|
||||
@@ -241,6 +283,21 @@ 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]));
|
||||
@@ -280,10 +337,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 ? { totales_estrato: totales } : {}),
|
||||
...(cruzado || porEstrato ? { totales_estrato: totales } : {}),
|
||||
grupos,
|
||||
categorias: cats,
|
||||
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : {},
|
||||
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : gruposDeCategoria(measure),
|
||||
notas: [],
|
||||
reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))),
|
||||
filas,
|
||||
|
||||
@@ -48,9 +48,7 @@ describe('Barras estratificadas: activación y caché',()=>{
|
||||
toggle[1].click(); const stratified = request(); stratified.flush(age); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.dimension).toBe('grupo_edad');
|
||||
expect(toggle[1].getAttribute('aria-checked')).toBe('true');
|
||||
// The dimensions, apart from the counts or percentage toggle that follows them.
|
||||
expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions:not(.distribution-medida) [role="radio"]')).toHaveLength(2);
|
||||
expect(fixture.nativeElement.querySelectorAll('.distribution-medida [role="radio"]')).toHaveLength(2);
|
||||
expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions [role="radio"]')).toHaveLength(2);
|
||||
for(const button of toggle) { expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button'); }
|
||||
});
|
||||
it('deshabilita estratificación en multiperiodo y conserva el mensaje contextual',()=>{
|
||||
@@ -95,46 +93,3 @@ describe('Barras estratificadas: activación y caché',()=>{
|
||||
expect(TestBed.inject(IndicadoresSnapshots).reading('cacu',item,applied)?.data).toEqual(general());
|
||||
});
|
||||
});
|
||||
|
||||
describe('Barra lateral de estratificación', () => {
|
||||
// Fija: con más de dos estratificadores, la elección de dimensión, los valores visibles y la medida van en una
|
||||
// barra lateral; ocultar y volver a mostrar valores redibuja sin pedir datos. Falla si la barra no aparece, si un
|
||||
// valor oculto sigue en la figura, si se puede ocultar el último o si un cambio local vuelve a consultar.
|
||||
let fixture:ReturnType<typeof TestBed.createComponent<IndicadorFigurePanel>>, http:HttpTestingController;
|
||||
const tres:Indicador={...item,filtros:[...item.filtros!,{estrato:'estadio',etiqueta:'Estadio clínico',valores:[{valor:'I',etiqueta:'I'}]}]};
|
||||
const general=()=>({...c2Fixture(),id:item.id,version:item.version});
|
||||
beforeEach(()=>{
|
||||
TestBed.configureTestingModule({providers:[provideHttpClient(),provideHttpClientTesting()]});
|
||||
TestBed.overrideComponent(IndicadorFigureCard,{remove:{imports:[PlotlyChart]},add:{imports:[ChartStub]}});
|
||||
fixture=TestBed.createComponent(IndicadorFigurePanel); http=TestBed.inject(HttpTestingController);
|
||||
for(const [k,v] of Object.entries({dominio:'cama',indicador:tres,figuraId:'fig_c2_barras',tema:'claro',applied})) fixture.componentRef.setInput(k,v);
|
||||
});
|
||||
afterEach(()=>{fixture.destroy();http.verify();});
|
||||
const request=()=>http.expectOne(r=>r.url.endsWith('/datos'));
|
||||
const aside=()=>fixture.nativeElement.querySelector('.strata-sidebar') as HTMLElement;
|
||||
it('lista los estratificadores y oculta o muestra valores sin consultar',()=>{
|
||||
fixture.detectChanges(); request().flush(general()); fixture.detectChanges();
|
||||
expect(aside()).not.toBeNull(); expect(fixture.nativeElement.querySelector('.distribution-toggle')).toBeNull();
|
||||
const opciones=[...aside().querySelectorAll('[role="radiogroup"] [role="radio"]')] as HTMLButtonElement[];
|
||||
expect(opciones.map(b=>b.textContent!.trim())).toEqual(['Sin estratificar','Por grupo de edad','Por estatus de seguimiento','Por estadio clínico']);
|
||||
opciones[1].click(); request().flush(age); fixture.detectChanges();
|
||||
const valores=()=>[...aside().querySelectorAll('.stratum-toggle')] as HTMLButtonElement[];
|
||||
expect(valores()).toHaveLength(age.valores_estrato.length);
|
||||
valores()[0].click(); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.result().figure?.data.map(t=>t['name'])).not.toContain('<25');
|
||||
expect(valores()[0].getAttribute('aria-pressed')).toBe('false');
|
||||
for(const b of valores().slice(1,-1)) b.click(); fixture.detectChanges();
|
||||
expect(valores().at(-1)!.disabled).toBe(true); expect(fixture.componentInstance.result().figure?.data).toHaveLength(1);
|
||||
(aside().querySelector('.sidebar-reset') as HTMLButtonElement).click(); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.result().figure?.data).toHaveLength(age.valores_estrato.length);
|
||||
http.expectNone(()=>true);
|
||||
});
|
||||
it('cambiar de estratificador muestra de nuevo todos los valores',()=>{
|
||||
fixture.detectChanges(); request().flush(general());
|
||||
fixture.componentInstance.changeDimension('grupo_edad'); request().flush(age);
|
||||
fixture.componentInstance.toggleEstrato('<25'); expect(fixture.componentInstance.ocultos.size).toBe(1);
|
||||
fixture.componentInstance.changeDimension('estatus_seguimiento'); request().flush(status);
|
||||
expect(fixture.componentInstance.ocultos.size).toBe(0);
|
||||
expect(fixture.componentInstance.estratos.map(e=>e.valor)).toEqual(status.valores_estrato);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import ageJson from './fixtures/cacu_eu7_datos_estrato_grupo_edad.json';
|
||||
import statusJson from './fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json';
|
||||
import { etiquetaDimension, stratifiedBars, stratifiedCapabilities, stratumOptions } from './indicadores-stratified';
|
||||
import { stratifiedBars, stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { DimensionEstrato, Indicador } from './indicadores.models';
|
||||
|
||||
const age = { ...ageJson, tipo_periodo: 'semestre' as const };
|
||||
@@ -61,52 +61,3 @@ describe('Contratos simulados de estratificación de los analistas', () => {
|
||||
expect(()=>stratifiedBars(data,'grupo_edad','2025-S2','claro')).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// A CaMa quantity of interest broken down by a stratifier: two strata of different size, one with a suppressed total.
|
||||
const porEtapa = () => ({
|
||||
id: 'cama_birads_cancer_invasor', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1'], estrato: 'etapa',
|
||||
valores_estrato: ['TEMPRANA', 'AVANZADA', 'SIN'], etiquetas_estrato: { TEMPRANA: 'Temprana', AVANZADA: 'Avanzada', SIN: 'Sin dato' },
|
||||
grupos: { TOTAL: 'Total' }, grupos_de_categoria: {}, categorias: { B4A: { etiqueta: 'BI-RADS 4A' }, B5: { etiqueta: 'BI-RADS 5' } },
|
||||
totales_estrato: [{ periodo: '2025-S1', grupo: 'TOTAL', estrato: 'TEMPRANA', n: 40, suprimido: 0 }, { periodo: '2025-S1', grupo: 'TOTAL', estrato: 'AVANZADA', n: 10, suprimido: 0 },
|
||||
{ periodo: '2025-S1', grupo: 'TOTAL', estrato: 'SIN', n: null, suprimido: 1 }],
|
||||
filas: [['TEMPRANA', 'B4A', 10], ['TEMPRANA', 'B5', 30], ['AVANZADA', 'B4A', 1], ['AVANZADA', 'B5', 9], ['SIN', 'B4A', null], ['SIN', 'B5', null]]
|
||||
.map(([estrato, categoria, n], i) => ({ periodo: '2025-S1', grupo: 'TOTAL', estrato, categoria, n, orden: i % 2, suprimido: n === null ? 1 : 0 })),
|
||||
});
|
||||
describe('Porcentaje en cada estrato', () => {
|
||||
it('cada categoría es la parte de su estrato, y un estrato con total suprimido no tiene porcentaje', () => {
|
||||
// Fails if the share is taken over the whole period instead of the stratum, or drawn over an unknown total.
|
||||
const { figure, cells } = stratifiedBars(porEtapa() as never, 'etapa', '2025-S1', 'claro', {}, 'porcentaje');
|
||||
expect(cells.filter(c => c.stratum !== 'Sin dato').map(c => c.percent)).toEqual([25, 75, 10, 90]);
|
||||
expect(cells.filter(c => c.stratum === 'Sin dato').map(c => c.percent)).toEqual([null, null]);
|
||||
expect((figure.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Porcentaje del estrato');
|
||||
expect(stratifiedBars(porEtapa() as never, 'etapa', '2025-S1', 'claro').figure.data[0]['x']).toEqual([10, 30]);
|
||||
});
|
||||
it('las dimensiones de CaMa toman su etiqueta del catálogo, y CaCu conserva la suya', () => {
|
||||
// Fails if a new stratifier is offered without its published label, or CaCu's wording changes.
|
||||
const item = { id: 'x', titulo: 'X', contrato: 'C2', figuras: [], tipos_periodo: ['semestre'] as ['semestre'],
|
||||
filtros: [{ estrato: 'etapa', etiqueta: 'Etapa (temprana o avanzada)', valores: [{ valor: 'TEMPRANA', etiqueta: 'Temprana' }] },
|
||||
{ estrato: 'grupo_edad', etiqueta: 'Grupo de edad', valores: [{ valor: '40-49', etiqueta: '40-49' }] }] };
|
||||
expect(stratifiedCapabilities(item)).toEqual(['grupo_edad', 'etapa']);
|
||||
expect(etiquetaDimension(item, 'etapa')).toBe('Por etapa (temprana o avanzada)');
|
||||
expect(etiquetaDimension(item, 'grupo_edad')).toBe('Por grupo de edad');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Estratos ocultos', () => {
|
||||
// Fija: ocultar valores de un estrato quita sus series y sus celdas, cada estrato conserva su trama y nunca se
|
||||
// quedan todas fuera. Falla si el filtro deja de aplicarse, si las tramas se recorren o si se puede vaciar la figura.
|
||||
it('quita las series ocultas, conserva la trama de cada estrato y no deja la figura vacía', () => {
|
||||
const todos = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro');
|
||||
const patron = (f: typeof todos.figure, nombre: string) => (f.data.find(t => t['name'] === nombre)!['marker'] as Record<string, Record<string, unknown>>)['pattern']['shape'];
|
||||
const algunos = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro', {}, 'conteo', new Set(['<25', '35-44']));
|
||||
expect(algunos.figure.data.map(t => t['name'])).toEqual(['25-34', '45-54', '55-64', '65+', 'Sin dato']);
|
||||
expect(new Set(algunos.cells.map(c => c.stratum))).toEqual(new Set(['25-34', '45-54', '55-64', '65+', 'Sin dato']));
|
||||
for (const nombre of ['25-34', '65+', 'Sin dato']) expect(patron(algunos.figure, nombre)).toEqual(patron(todos.figure, nombre));
|
||||
const ninguno = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro', {}, 'conteo', new Set(age.valores_estrato));
|
||||
expect(ninguno.figure.data).toHaveLength(todos.figure.data.length);
|
||||
});
|
||||
it('lista los valores del estrato con su etiqueta, en el orden publicado', () => {
|
||||
expect(stratumOptions(age).map(e => e.etiqueta)).toEqual(['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'Sin dato']);
|
||||
expect(stratumOptions(age).at(-1)).toEqual({ valor: 'sin_dato', etiqueta: 'Sin dato' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,53 +4,37 @@ import { c2Theme, seriesColors } from './indicadores-c2-palette';
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
// The dimensions a C2's bars can be broken down by, in this order; `citologia_alto_grado` belongs to CaCu's C1 donut.
|
||||
const ESTRATIFICABLES: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'birads', 'brca', 'estadio', 'tamano', 'etapa'];
|
||||
/** The button of a dimension: CaCu's two keep their wording; the rest take the label the catalog publishes. */
|
||||
export function etiquetaDimension(item: Indicador, d: DimensionEstrato): string {
|
||||
if (d === 'grupo_edad') return 'Por grupo de edad';
|
||||
if (d === 'estatus_seguimiento') return 'Por estatus de seguimiento';
|
||||
const etiqueta = item.filtros?.find(f => f.estrato === d)?.etiqueta;
|
||||
return 'Por ' + (etiqueta ? etiqueta.charAt(0).toLowerCase() + etiqueta.slice(1) : d);
|
||||
}
|
||||
export type MedidaEstrato = 'conteo' | 'porcentaje';
|
||||
export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] {
|
||||
return item.contrato === 'C2' && Array.isArray(item.filtros)
|
||||
? ESTRATIFICABLES.filter(d => item.filtros!.some(f => f?.estrato === d
|
||||
? (['grupo_edad', 'estatus_seguimiento'] as const).filter(d => item.filtros!.some(f => f?.estrato === d
|
||||
&& typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0
|
||||
&& f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : [];
|
||||
}
|
||||
/** A stratum a reader can show or hide: its published value and label, in the published order. */
|
||||
export interface StratumOption { valor: string; etiqueta: string; }
|
||||
export function stratumOptions(data: IndicadorDatos): StratumOption[] {
|
||||
const valores = Array.isArray(data['valores_estrato']) ? data['valores_estrato'] as unknown[] : [];
|
||||
const etiquetas = record(data['etiquetas_estrato']) ? data['etiquetas_estrato'] : {};
|
||||
return valores.filter((v): v is string => typeof v === 'string')
|
||||
.map(valor => ({ valor, etiqueta: typeof etiquetas[valor] === 'string' ? etiquetas[valor] as string : valor }));
|
||||
// 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);
|
||||
}
|
||||
// `percent`: the cell's share of its stratum, when the stratum's total is known.
|
||||
export interface StratifiedCell { category: string; stratum: string; value: number | null; percent: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
||||
/** The bars of one period broken down by `dimension`; the strata in `hidden` are left out of the figure and the cells,
|
||||
* unless that would leave none. */
|
||||
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}, medida: MedidaEstrato = 'conteo', hidden: ReadonlySet<string> = new Set()): { figure: PlotlyFigure; cells: StratifiedCell[] } {
|
||||
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
|
||||
|| !record(data['categorias']) || !record(data['grupos_de_categoria']) || !record(data['grupos'])
|
||||
|| Object.keys(data['grupos']).length !== 1
|
||||
|| !Array.isArray(data['valores_estrato']) || !data['valores_estrato'].length
|
||||
|| !data['valores_estrato'].every(v => typeof v === 'string')
|
||||
|| new Set(data['valores_estrato']).size !== data['valores_estrato'].length || !record(data['etiquetas_estrato'])) throw new Error('Distribución estratificada inválida');
|
||||
const published = data['valores_estrato'] as string[], labels = data['etiquetas_estrato'];
|
||||
const shown = published.filter(s => !hidden.has(s));
|
||||
const strata = shown.length ? shown : published;
|
||||
const strata = data['valores_estrato'] as string[], labels = data['etiquetas_estrato'];
|
||||
const statisticalGroup = Object.keys(data['grupos'])[0];
|
||||
if (published.some(s => typeof labels[s] !== 'string')) throw new Error('Etiquetas de estrato incompletas');
|
||||
if (strata.some(s => typeof labels[s] !== 'string')) throw new Error('Etiquetas de estrato incompletas');
|
||||
const catalog = data['categorias'], groups = data['grupos_de_categoria'];
|
||||
const entries = new Map<string, { order: number; label: string; color?: string; parent?: string }>();
|
||||
const rows = new Map<string, Record<string, unknown>>();
|
||||
for (const row of data.filas) {
|
||||
const id = row['categoria'], stratum = row['estrato'], n = row['n'];
|
||||
if (row['periodo'] !== period || row['grupo'] !== statisticalGroup || typeof id !== 'string' || !id
|
||||
|| typeof stratum !== 'string' || !published.includes(stratum) || typeof row['orden'] !== 'number' || !Number.isFinite(row['orden'])
|
||||
|| typeof stratum !== 'string' || !strata.includes(stratum) || typeof row['orden'] !== 'number' || !Number.isFinite(row['orden'])
|
||||
|| ![0, 1].includes(row['suprimido'] as number) || (row['suprimido'] === 1 ? n !== null : n !== null && (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0))) throw new Error('Fila estratificada inválida');
|
||||
const key = JSON.stringify([id, stratum]);
|
||||
if (rows.has(key) || (entries.has(id) && entries.get(id)!.order !== row['orden'])) throw new Error('Filas ambiguas');
|
||||
@@ -67,39 +51,21 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
|
||||
const cells: StratifiedCell[] = [];
|
||||
const theme = c2Theme(tema);
|
||||
const palette = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id));
|
||||
// The stratum's total: the one published, or else the sum of its cells when every one is published. A share is
|
||||
// only drawn over a known total; a suppressed or missing total leaves the stratum without percentages.
|
||||
const totales = Array.isArray(data['totales_estrato']) ? data['totales_estrato'] as Record<string, unknown>[] : [];
|
||||
const totalDe = (s: string): number | null => {
|
||||
const publicado = totales.find(t => t['periodo'] === period && t['estrato'] === s && t['grupo'] === statisticalGroup);
|
||||
if (publicado) return publicado['suprimido'] === 0 && typeof publicado['n'] === 'number' && publicado['n'] > 0 ? publicado['n'] : null;
|
||||
const propias = [...entries.keys()].map(id => rows.get(JSON.stringify([id, s])));
|
||||
if (propias.some(r => !r || r['suprimido'] !== 0 || typeof r['n'] !== 'number')) return null;
|
||||
const suma = propias.reduce((a, r) => a + (r!['n'] as number), 0);
|
||||
return suma > 0 ? suma : null;
|
||||
};
|
||||
const porcentaje = medida === 'porcentaje';
|
||||
const figure: PlotlyFigure = { data: strata.map(s => {
|
||||
const series = published.indexOf(s); // a stratum keeps its pattern when others are hidden
|
||||
const figure: PlotlyFigure = { data: strata.map((s, series) => {
|
||||
const selected = categories.map(([id, c]) => {
|
||||
const row = rows.get(JSON.stringify([id, s]));
|
||||
const status = row?.['suprimido'] === 1 ? 'Suprimido' : typeof row?.['n'] === 'number' ? 'Publicado' : 'No disponible';
|
||||
const value = status === 'Publicado' ? row!['n'] as number : null;
|
||||
const total = totalDe(s);
|
||||
const percent = value !== null && total ? Math.round(1000 * value / total) / 10 : null;
|
||||
cells.push({ category: c.label, stratum: labels[s] as string, value, percent, status });
|
||||
return { value, percent, total };
|
||||
cells.push({ category: c.label, stratum: labels[s] as string, value, status });
|
||||
return value;
|
||||
});
|
||||
const x = selected.map(v => porcentaje ? v.percent : v.value);
|
||||
return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x, y: categories.map(([, c]) => escape(c.label)),
|
||||
customdata: selected.map(v => [v.value ?? 'sin valor', v.total ?? 'sin total']),
|
||||
return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)),
|
||||
marker: { color: palette, pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } },
|
||||
hovertemplate: porcentaje ? '%{y}<br>%{x:.1f} % (%{customdata[0]} de %{customdata[1]})<extra>%{fullData.name}</extra>' : '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
|
||||
}), layout: { title: { text: (porcentaje ? 'Porcentaje en cada estrato, ' : 'Distribución estratificada, ') + period }, barmode: 'group', autosize: true,
|
||||
hovertemplate: '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
|
||||
}), layout: { title: { text: 'Distribución estratificada, ' + period }, barmode: 'group', autosize: true,
|
||||
height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background,
|
||||
font: { color: theme.text }, margin: { l: 100, r: 24, t: 40, b: 100 },
|
||||
xaxis: porcentaje ? { range: [0, 100], title: { text: 'Porcentaje del estrato' }, ticksuffix: ' %', gridcolor: theme.grid }
|
||||
: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid },
|
||||
xaxis: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid },
|
||||
yaxis: { type: 'category', categoryorder: 'array', categoryarray: categories.map(([, c]) => escape(c.label)).reverse(), automargin: true },
|
||||
legend: { orientation: 'h', y: -0.12, itemclick: false, itemdoubleclick: false } } };
|
||||
return { figure, cells };
|
||||
|
||||
@@ -18,16 +18,8 @@ export interface Indicador {
|
||||
filtros?: IndicadorFiltro[];
|
||||
// Tabs that show it; without this field, all of them.
|
||||
vistas?: string[];
|
||||
// Interactive donut and bars by one stratum, like CaCu's EU7.
|
||||
escenario?: VistaEscenario;
|
||||
// How the breakdown by stratum opens: counts, or each category's share of its stratum.
|
||||
medida_estrato?: 'conteo' | 'porcentaje';
|
||||
}
|
||||
// CaMa's stratifiers (brca, estadio, tamano, etapa) break down its quantities of interest.
|
||||
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads' | 'brca' | 'estadio' | 'tamano' | 'etapa';
|
||||
export const DIMENSIONES_ESTRATO: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado', 'birads', 'brca', 'estadio', 'tamano', 'etapa'];
|
||||
// `etiqueta` names one value of the stratum in lower case, as in «por escenario clínico».
|
||||
export interface VistaEscenario { estrato: DimensionEstrato; etiqueta: string; }
|
||||
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads';
|
||||
export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; }
|
||||
export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; }
|
||||
export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; }
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
<dl class="summary">
|
||||
<div><dt>{{ p.idLabel }}</dt><dd>{{ p.patientId }}</dd></div>
|
||||
<div><dt>Grupo de edad</dt><dd>{{ p.ageGroup ?? notAvailable }}</dd></div>
|
||||
<div><dt>Escenario clínico</dt><dd>{{ p.clinicalScenario ?? notAvailable }}</dd></div>
|
||||
<div><dt>Estatus de seguimiento</dt><dd>{{ p.status ?? notAvailable }}</dd></div>
|
||||
<div><dt>Prioridad</dt><dd>{{ p.priority ?? notAvailable }}</dd></div>
|
||||
<div><dt>Días de mastografía a diagnóstico</dt><dd>{{ p.daysMammographyToDiagnosis ?? notAvailable }}</dd></div>
|
||||
|
||||
@@ -16,7 +16,7 @@ describe('Ficha CaMa: resumen', () => {
|
||||
it('reads every field the follow-up row carries', () => {
|
||||
const row = complete();
|
||||
expect(toCamaPatientSummary(row, '2026-10-20')).toEqual({
|
||||
patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], clinicalScenario: null, status: row['estatus'], priority: row['prioridad'],
|
||||
patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], status: row['estatus'], priority: row['prioridad'],
|
||||
birads: row['birads'], mammographyDate: row['mastografia_fecha'], histopathology: row['biopsia'], biopsyDate: row['biopsia_fecha'],
|
||||
daysMammographyToDiagnosis: row['dias_mastografia_diagnostico'],
|
||||
});
|
||||
|
||||
@@ -21,7 +21,6 @@ export function camaPatientDocument(patient: CamaPatientSummary, now: Date, logo
|
||||
...section('Resumen', [
|
||||
[patient.idLabel, patient.patientId],
|
||||
['Grupo de edad', patient.ageGroup],
|
||||
['Escenario clínico', patient.clinicalScenario],
|
||||
['Estatus de seguimiento', patient.status],
|
||||
['Prioridad', patient.priority],
|
||||
['Días de mastografía a diagnóstico', patient.daysMammographyToDiagnosis],
|
||||
|
||||
@@ -14,8 +14,6 @@ export interface CamaPatientSummary {
|
||||
idLabel: string;
|
||||
cutoff: string;
|
||||
ageGroup: string | null;
|
||||
/** «Post-tratamiento» or «En observación» at the cut-off. */
|
||||
clinicalScenario: string | null;
|
||||
status: string | null;
|
||||
priority: string | null;
|
||||
birads: string | null;
|
||||
@@ -53,7 +51,6 @@ export function toCamaPatientSummary(row: TrackingRow, cutoff: string, columnas:
|
||||
idLabel: ETIQUETA_IDENTIDAD[identity.campo],
|
||||
cutoff,
|
||||
ageGroup: text(row['grupo_edad']),
|
||||
clinicalScenario: text(row['escenario_clinico']),
|
||||
status: text(row['estatus']),
|
||||
priority: text(row['prioridad']),
|
||||
birads: text(row['birads']),
|
||||
|
||||
@@ -8,13 +8,33 @@
|
||||
@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>
|
||||
@let riesgo = lectura.datos.riesgo;
|
||||
@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) {
|
||||
<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>
|
||||
@@ -26,6 +46,7 @@
|
||||
<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) {
|
||||
@@ -33,12 +54,14 @@
|
||||
<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,39 +1,46 @@
|
||||
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 {
|
||||
/** The resource's id, `<lote_id>-<pac_id>`. */
|
||||
id: string;
|
||||
lote_id: number;
|
||||
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: the patient's current `RiskAssessment`, from a `searchset` Bundle tagged `simulado`. */
|
||||
/** DEV-only contract from cacu_riesgo_paciente.md, 2026-10-28. */
|
||||
export interface RiesgoPacienteCacu {
|
||||
simulado: true;
|
||||
riesgo: LoteRiesgoCacu;
|
||||
cohorte: CohorteRiesgoCacu | null;
|
||||
riesgo: LoteRiesgoCacu | null;
|
||||
}
|
||||
|
||||
/** The raw FHIR answer (a Bundle), or `null` when the patient has no risk data. */
|
||||
/** `null` when the patient has no risk data. */
|
||||
export interface PacienteRiesgoProvider {
|
||||
obtener(pacId: string): Observable<unknown>;
|
||||
}
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
|
||||
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
||||
import { inject, InjectionToken } from '@angular/core';
|
||||
import { catchError, of, throwError } from 'rxjs';
|
||||
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
|
||||
|
||||
// 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.
|
||||
// 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.
|
||||
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
|
||||
providedIn: 'root', factory: () => {
|
||||
const http = inject(HttpClient);
|
||||
return {
|
||||
obtener: (pacId: string) => http.get<unknown>('/cacu/fhir/RiskAssessment', {
|
||||
params: new HttpParams().set('subject', `Patient/${pacId}`),
|
||||
}).pipe(
|
||||
obtener: (pacId: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).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 { prediccion, riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { 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 RiskAssessment FHIR de la paciente por su pac_id y trata un 404 como no disponible', () => {
|
||||
it('pide el riesgo por el pac_id de los lotes a la WebApi y trata un 404 como no disponible', () => {
|
||||
const f = setup(), root: HTMLElement = f.nativeElement;
|
||||
TestBed.inject(HttpTestingController).expectOne('/cacu/fhir/RiskAssessment?subject=Patient/42')
|
||||
.flush({ resourceType: 'OperationOutcome' }, { status: 404, statusText: 'Not Found' });
|
||||
TestBed.inject(HttpTestingController).expectOne('/cacu/pacientes/42/riesgo')
|
||||
.flush({ error: 'no existe' }, { 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,33 +33,27 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0);
|
||||
});
|
||||
|
||||
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', () => {
|
||||
it('renderiza el ejemplo contractual, estados, 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(3);
|
||||
expect(root.querySelectorAll('thead th')).toHaveLength(4);
|
||||
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)');
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', '2026-06-01', 'CIN2+ por biopsia']) {
|
||||
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']) {
|
||||
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/);
|
||||
// The resource id (batch and patient) stays in the contract, never in a UI label.
|
||||
expect(root.textContent).not.toMatch(/lote_id|12-42/);
|
||||
// Internal batch key stays in the contract, never in a UI label.
|
||||
expect(root.textContent).not.toContain('lote_id');
|
||||
expect(data).toEqual(baseline);
|
||||
});
|
||||
|
||||
@@ -73,15 +67,17 @@ 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.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'),
|
||||
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' },
|
||||
];
|
||||
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']);
|
||||
@@ -90,9 +86,31 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(root.textContent).toContain('Preliminar (preliminary)');
|
||||
});
|
||||
|
||||
it.each([[[]], [[{ code: 'real' }]], [undefined]])('no expone una respuesta no simulada (%j)', tag => {
|
||||
it('preserva variables nulas y el cero basal sin convertirlos en hallazgos', () => {
|
||||
const data = riesgoCacuEjemplo();
|
||||
if (tag === undefined) delete data.entry[0].resource.meta; else data.entry[0].resource.meta.tag = tag;
|
||||
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 };
|
||||
const f = setup({ obtener: () => of(data) });
|
||||
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(f.nativeElement.textContent).not.toContain('modelo-cacu');
|
||||
@@ -100,7 +118,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
});
|
||||
|
||||
it('rechaza probabilidades inválidas sin presentar parcialmente la cohorte', () => {
|
||||
const data = riesgoCacuEjemplo(); data.entry[0].resource.prediction[0].probabilityDecimal = 12;
|
||||
const data = riesgoCacuEjemplo(); data.riesgo!.horizontes[0].probabilidad = 12;
|
||||
const f = setup({ obtener: () => of(data) });
|
||||
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(f.nativeElement.querySelectorAll('table, dl')).toHaveLength(0);
|
||||
@@ -116,14 +134,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.entry[0].resource.prediction[0].probabilityDecimal = 1; f.detectChanges();
|
||||
data.riesgo!.horizontes[0].probabilidad = 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().entry[0].resource.prediction[0].probabilityDecimal).toBe(0.08);
|
||||
expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08);
|
||||
otra.destroy(); expect(source.observed).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -14,10 +14,8 @@ 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((respuesta): PacienteRiesgoEstado => {
|
||||
const datos = respuesta === null ? null : riesgoPacienteResponse(respuesta, id);
|
||||
return datos === null ? { tipo: 'no-disponible' } : { tipo: 'disponible', datos };
|
||||
}),
|
||||
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
|
||||
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
|
||||
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
|
||||
startWith(CARGANDO),
|
||||
)),
|
||||
|
||||
@@ -1,51 +1,20 @@
|
||||
import { RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
|
||||
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 {
|
||||
/** TEST ONLY. Exact external contract example; never belongs to the selected patient. */
|
||||
export function riesgoCacuEjemplo(): 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: {
|
||||
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',
|
||||
lote_id: 12, modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0',
|
||||
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final',
|
||||
horizontes: [
|
||||
{ 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 },
|
||||
{ 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' },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,89 +1,121 @@
|
||||
import { prediccion, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing';
|
||||
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { riesgoPacienteResponse, tieneIntervalo } from './paciente-riesgo.validation';
|
||||
import { TipoCensuraCacu } from './paciente-riesgo.models';
|
||||
|
||||
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', () => {
|
||||
describe('RIESGO-CACU-02: frontera del contrato DEV', () => {
|
||||
it('conserva todos los campos del ejemplo externo y copia los objetos', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
const salida = riesgoPacienteResponse(entrada, '42')!;
|
||||
expect(salida).toEqual(riesgoCacuVista());
|
||||
salida.riesgo.horizontes[0].probabilidad = 0;
|
||||
const salida = riesgoPacienteResponse(entrada);
|
||||
expect(salida).toEqual(entrada);
|
||||
salida.riesgo!.horizontes[0].probabilidad = 0;
|
||||
salida.cohorte!.c = -999;
|
||||
expect(entrada).toEqual(riesgoCacuEjemplo());
|
||||
});
|
||||
|
||||
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('admite campos aditivos sin eliminarlos ni renombrarlos', () => {
|
||||
const entrada = { ...riesgoCacuEjemplo(), futuro: { estado: null } };
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
});
|
||||
|
||||
it('el horizonte sale del whenPeriod; el inmediato es un periodo de un día', () => {
|
||||
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', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
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]);
|
||||
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 });
|
||||
});
|
||||
|
||||
it('ordena las predicciones por horizonte y admite campos aditivos de FHIR', () => {
|
||||
it('no impone dependencia entre cohorte nullable y riesgo nullable', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
recurso(entrada).prediction.reverse();
|
||||
recurso(entrada).note = [{ text: 'simulado' }];
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(riesgoCacuVista());
|
||||
entrada.cohorte = null;
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
});
|
||||
|
||||
it.each([[undefined], [[]], [[{ url: 'otra', valueString: 'x' }]]])('sin extensión de intervalo no fabrica límites (%j)', ext => {
|
||||
it.each([[], [2.5], [0, 0.5, 7, 12]])('acepta horizontes dinámicos/parciales/vacíos %j', (...anios: number[]) => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
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);
|
||||
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);
|
||||
});
|
||||
|
||||
it.each([0, 1])('acepta probabilidad y límites extremos %s sin convertir el transporte a porcentaje', p => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
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);
|
||||
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);
|
||||
});
|
||||
|
||||
const invalidos: [string, (v: any) => void][] = [
|
||||
['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'],
|
||||
['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],
|
||||
];
|
||||
it.each(invalidos)('rechaza %s sin coerción ni datos parciales', (_, mutar) => {
|
||||
const entrada = riesgoCacuEjemplo(); mutar(entrada);
|
||||
expect(() => riesgoPacienteResponse(entrada, '42')).toThrow('Respuesta de riesgo individual DEV inválida');
|
||||
expect(() => riesgoPacienteResponse(entrada)).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,104 +1,54 @@
|
||||
import { isoDate } from '../cacu-seguimiento.models';
|
||||
import { HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
import { HorizonteRiesgoCacu, 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 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 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 probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1;
|
||||
const DAYS_PER_YEAR = 365.25;
|
||||
const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
|
||||
const SIMULATED = 'simulado';
|
||||
const censuras = ['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo'];
|
||||
|
||||
function utcTimestamp(v: unknown): v is string {
|
||||
function utcTimestamp(v: unknown) {
|
||||
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 invalid(): never {
|
||||
throw new Error('Respuesta de riesgo individual DEV inválida');
|
||||
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']);
|
||||
}
|
||||
|
||||
/** 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);
|
||||
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;
|
||||
}
|
||||
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,
|
||||
};
|
||||
// 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'];
|
||||
}
|
||||
|
||||
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);
|
||||
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']);
|
||||
}
|
||||
|
||||
/** 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) };
|
||||
/** 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;
|
||||
}
|
||||
|
||||
/** Presentation helper: an incomplete interval must never become a fabricated range. */
|
||||
|
||||
@@ -147,7 +147,7 @@ export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaR
|
||||
}),
|
||||
};
|
||||
}
|
||||
const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true, biopsia: true, escenario_clinico: true };
|
||||
const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true, biopsia: true };
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class SeguimientoTablaService {
|
||||
|
||||
@@ -59,16 +59,16 @@
|
||||
</section>
|
||||
|
||||
@if (d.eeg; as e) {
|
||||
<div class="alteraciones-zona" [class.abierta]="mapaActual(e)">
|
||||
<div class="alteraciones-zona" [class.abierta]="abierto(e)">
|
||||
<section class="panel alteraciones" aria-label="Alteraciones del EEG">
|
||||
<h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3>
|
||||
<p class="meta">Curvas de referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}) y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas.</p>
|
||||
<p class="meta">Curvas de referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}) y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas o dónde queda el paciente en la norma por edad.</p>
|
||||
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
|
||||
<ul class="metricas">
|
||||
@for (m of e.alteraciones; track m.codigo) {
|
||||
<li [attr.data-estado]="m.estado">
|
||||
<div class="metrica">
|
||||
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : mapaActual(e)?.codigo === m.codigo"
|
||||
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : abierto(e) && mapaElegido === m.codigo"
|
||||
[attr.aria-controls]="'zonas-' + d.id_seudonimo" (click)="elegirMapa(e, m.codigo)">{{ m.etiqueta }}</button>
|
||||
<span class="estado">{{ estado[m.estado] }}</span>
|
||||
</div>
|
||||
@@ -88,8 +88,24 @@
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@if (mapaActual(e); as mapa) {
|
||||
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Mapa de zonas afectadas">
|
||||
@if (abierto(e)) {
|
||||
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Detalle de la alteración">
|
||||
@if (mapaActual(e) && normaActual(e)) {
|
||||
<div class="vistas" role="group" aria-label="Qué mostrar">
|
||||
<button type="button" [attr.aria-pressed]="vista === 'zonas'" (click)="verVista('zonas')">Zonas de la cabeza</button>
|
||||
<button type="button" [attr.aria-pressed]="vista === 'norma'" (click)="verVista('norma')">Norma por edad</button>
|
||||
</div>
|
||||
}
|
||||
@if (vista === 'norma' && normaActual(e); as m) {
|
||||
<h3>Norma por edad</h3>
|
||||
<p class="meta">{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, referencia {{ m.curva_referencia!.estado }}</p>
|
||||
@if (figuraNorma) {
|
||||
<app-plotly-chart [figure]="figuraNorma" [showNotes]="false" [style.--plot-height]="'280px'"
|
||||
[label]="'Norma por edad de ' + m.etiqueta + ' con el paciente ' + d.id_seudonimo" />
|
||||
}
|
||||
<p class="leyenda-norma">La línea es la mediana de la norma y las sombras, del 5 al 95 % (clara) y del 25 al 75 % (oscura).
|
||||
El punto es este paciente: {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} a los {{ e.edad_meses }} meses (z = {{ m.valor_z }}).</p>
|
||||
} @else if (mapaActual(e); as mapa) {
|
||||
<h3>Zonas más afectadas</h3>
|
||||
<p class="meta">{{ mapa.metrica }} · mapa ilustrativo</p>
|
||||
<p class="leyenda-mapa"><span class="azul" aria-hidden="true"></span>Azul: menos actividad <span class="rojo" aria-hidden="true"></span>Rojo: más actividad</p>
|
||||
@@ -102,9 +118,54 @@
|
||||
<li [class.destacada]="r.valor_z >= 2 || r.valor_z <= -2"><span>{{ r.etiqueta }}</span><span>z = {{ r.valor_z }}</span></li>
|
||||
}
|
||||
</ol>
|
||||
}
|
||||
</section></div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (d.relacion_ados2; as rel) {
|
||||
<section class="panel relacion" aria-label="Relación de las alteraciones del EEG con el ADOS-2">
|
||||
<h3>Relación con el ADOS-2 <span class="mock">Datos de ejemplo</span></h3>
|
||||
<p class="meta">Modelo de asociación ajustado en la cohorte ({{ rel.n_cohorte }} niños, por edad y módulo del ADOS-2): qué tanto se
|
||||
asocia cada alteración del EEG por zona con {{ rel.nivel === 'item' ? 'un reactivo' : 'la severidad de un dominio' }} del ADOS-2.
|
||||
No es un diagnóstico ni indica qué causa qué.@if (!rel.validado) { Pendiente de validación médica.}</p>
|
||||
@if (!filasRelacion(rel).length) {
|
||||
<p class="sin-alteraciones">Ninguna zona alterada de este paciente (|z| ≥ 2) tiene una asociación clara con el ADOS-2 en la cohorte.</p>
|
||||
} @else {
|
||||
<div class="tabla-relacion" role="region" aria-label="Asociaciones por zona" tabindex="0">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Zona del EEG</th><th scope="col">Aspecto del ADOS-2</th><th scope="col">Asociación en la cohorte</th>
|
||||
<th scope="col">Probabilidad para este paciente</th><th scope="col">Lo que muestra su ADOS-2</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (f of filasRelacion(rel); track f.biomarcador + f.zona + f.resultado) {
|
||||
<tr [class.alterada]="zonaAlterada(f)">
|
||||
<td><strong>{{ f.biomarcador }}</strong><small>{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · <span class="marca">alterada</span>}</small></td>
|
||||
<td>{{ f.resultado_etiqueta }}<small>{{ f.tipo === 'item' ? 'Reactivo' : 'Dominio' }}</small></td>
|
||||
<td><span class="or">OR {{ f.or }}</span><small>IC 95 % {{ f.ic_inf }}–{{ f.ic_sup }} · q {{ qTexto(f.q) }}</small><small>{{ direccion(f) }}</small></td>
|
||||
<td>
|
||||
<span class="prob">{{ porcentaje(f.probabilidad) }} %</span>
|
||||
<span class="barra" aria-hidden="true">
|
||||
<span class="paciente" [style.width.%]="porcentaje(f.probabilidad)"></span>
|
||||
<span class="referencia" [style.left.%]="porcentaje(f.probabilidad_referencia)"></span>
|
||||
</span>
|
||||
<small>{{ f.evento }} · con z = 0: {{ porcentaje(f.probabilidad_referencia) }} %</small>
|
||||
</td>
|
||||
<td>{{ observado(f) }}@if (coincide(f) !== null) { <small>{{ coincide(f) ? 'Coincide con lo que el modelo esperaba' : 'No coincide con lo que el modelo esperaba' }}</small> }</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="nota">OR mayor que 1: a mayor z en esa zona, más probable que el aspecto salga alterado; menor que 1, al revés. La
|
||||
probabilidad es la que da el modelo a un niño de su edad y módulo con su z; la marca gris de la barra es la de un niño con z = 0.
|
||||
Solo se muestran las zonas alteradas del paciente (|z| ≥ 2) con una asociación clara en la cohorte (q < 0.05). Versión del modelo: {{ rel.version }}.</p>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -73,3 +73,24 @@ li[data-estado=no_evaluable] .estado { color: var(--issste-text-secondary); font
|
||||
button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border); border-radius: 4px; background: var(--issste-surface); color: inherit; font: inherit; cursor: pointer; }
|
||||
|
||||
.canales-malos { margin: .25rem 0 0; padding-inline-start: 1.1rem; font-size: .85rem; }
|
||||
|
||||
// Relation with the ADOS-2 (association model): full width, a scrollable table on narrow screens.
|
||||
.relacion { grid-column: 1 / -1; }
|
||||
.tabla-relacion { overflow-x: auto; }
|
||||
.tabla-relacion table { width: 100%; min-width: 44rem; border-collapse: collapse; font-size: .85rem; }
|
||||
.tabla-relacion th, .tabla-relacion td { padding: .45rem .5rem; border-top: 1px solid var(--issste-border); text-align: start; vertical-align: top; }
|
||||
.tabla-relacion thead th { font-size: .8rem; color: var(--issste-text-secondary); font-weight: 600; }
|
||||
.tabla-relacion small { display: block; margin-top: .1rem; color: var(--issste-text-secondary); font-size: .75rem; }
|
||||
.tabla-relacion tr.alterada td:first-child { box-shadow: inset 4px 0 0 #B3261E; }
|
||||
.tabla-relacion .marca { color: #B3261E; font-weight: 600; }
|
||||
.or, .prob { font-weight: 700; font-variant-numeric: tabular-nums; }
|
||||
.barra { position: relative; display: block; height: .45rem; margin-top: .25rem; border-radius: 999px; background: var(--issste-border); }
|
||||
.barra .paciente { position: absolute; inset-block: 0; inset-inline-start: 0; border-radius: 999px; background: var(--issste-accent); }
|
||||
.barra .referencia { position: absolute; top: -.15rem; bottom: -.15rem; width: 2px; background: var(--issste-text-secondary); }
|
||||
.nota { margin: .5rem 0 0; font-size: .75rem; color: var(--issste-text-secondary); }
|
||||
// The switch between the head map and the age norm, when the metric has both.
|
||||
.vistas { display: inline-flex; margin-bottom: .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); overflow: hidden; }
|
||||
.vistas button { margin: 0; min-height: 0; padding: .3rem .75rem; border: 0; background: none; color: inherit; font: inherit; font-size: .8rem; cursor: pointer; }
|
||||
.vistas button + button { border-inline-start: 1px solid var(--issste-border); }
|
||||
.vistas button[aria-pressed=true] { background: color-mix(in srgb, var(--issste-accent) 14%, transparent); font-weight: 600; }
|
||||
.leyenda-norma { margin: .25rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); }
|
||||
|
||||
@@ -4,9 +4,12 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import {
|
||||
CLASIFICACIONES_ADOS2, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaPacienteDetalle,
|
||||
TeaSeguimientoService, TeaAdos2,
|
||||
TeaRelacionAdos2, TeaRelacionModelo, TeaSeguimientoService, TeaAdos2,
|
||||
} from './tea-seguimiento.service';
|
||||
|
||||
// A zone counts as altered from |z| ≥ 2, as the alteration cards do.
|
||||
const Z_ALTERADO = 2;
|
||||
|
||||
// ADOS-2 calibrated severity score ranges.
|
||||
const NIVEL_CSS: Record<TeaAdos2['nivel_css'], string> = { minimo: 'Evidencia mínima o nula', bajo: 'Nivel bajo', moderado: 'Nivel moderado', alto: 'Nivel alto' };
|
||||
const CALIDAD: Record<TeaEeg['calidad'], string> = { bueno: 'Válido', malo: 'No válido', sin_analizar: 'Sin analizar' };
|
||||
@@ -45,6 +48,36 @@ export function mapaFigure(eeg: TeaEeg, mapa: TeaEegMapa, fondo = '#FFFFFF'): Pl
|
||||
};
|
||||
}
|
||||
|
||||
// The age norm around the patient: the 5–95 and 25–75 percentile bands, the median line and the patient as a point.
|
||||
const BANDA_EXTERIOR = 'rgba(49,130,189,.16)', BANDA_INTERIOR = 'rgba(49,130,189,.32)', MEDIANA = '#2C6FA6', ALTERADO = '#B3261E';
|
||||
export function normaFigure(m: TeaEegAlteracion, edad: number): PlotlyFigure {
|
||||
const c = m.curva_referencia!, x = c.edad_meses, atras = [...x].reverse();
|
||||
const banda = (bajo: number[], alto: number[], color: string, nombre: string) => ({
|
||||
type: 'scatter', mode: 'lines', x: [...x, ...atras], y: [...alto, ...[...bajo].reverse()], fill: 'toself', fillcolor: color,
|
||||
line: { width: 0 }, name: nombre, hoverinfo: 'skip',
|
||||
});
|
||||
const unidad = m.unidad ? ` ${m.unidad}` : '';
|
||||
const alterado = m.estado === 'aumentado' || m.estado === 'disminuido';
|
||||
return {
|
||||
data: [
|
||||
banda(c.p5, c.p95, BANDA_EXTERIOR, 'Del 5 al 95 %'),
|
||||
banda(c.p25, c.p75, BANDA_INTERIOR, 'Del 25 al 75 %'),
|
||||
{ type: 'scatter', mode: 'lines', x, y: c.mediana, name: 'Mediana', line: { color: MEDIANA, width: 2 },
|
||||
hovertemplate: `%{x} meses: mediana %{y:.2f}${unidad}<extra></extra>` },
|
||||
{ type: 'scatter', mode: 'markers', x: [edad], y: [m.valor], name: 'Este paciente',
|
||||
marker: { size: 11, color: alterado ? ALTERADO : INK, line: { color: '#FFFFFF', width: 2 } },
|
||||
hovertemplate: `Este paciente: %{y:.2f}${unidad} a los %{x:.1f} meses (z = ${m.valor_z})<extra></extra>` },
|
||||
],
|
||||
layout: {
|
||||
margin: { l: 52, r: 12, t: 8, b: 44 }, paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)',
|
||||
showlegend: true, legend: { orientation: 'h', y: -0.28, font: { size: 11 } }, font: { color: INK },
|
||||
xaxis: { title: { text: 'Edad (meses)' }, range: [x[0], x[x.length - 1]], dtick: 6, gridcolor: 'rgba(8,24,57,.08)', fixedrange: true },
|
||||
yaxis: { title: { text: m.unidad || m.etiqueta }, gridcolor: 'rgba(8,24,57,.08)', zeroline: false, fixedrange: true },
|
||||
},
|
||||
config: { displayModeBar: false },
|
||||
};
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-tea-paciente-resumen',
|
||||
imports: [PlotlyChart],
|
||||
@@ -58,7 +91,7 @@ export class TeaPacienteResumen implements OnInit {
|
||||
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
|
||||
readonly detalle = signal<TeaPacienteDetalle | undefined>(undefined);
|
||||
figura?: PlotlyFigure;
|
||||
private mapaElegido?: string;
|
||||
mapaElegido?: string;
|
||||
private readonly elemento = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
// The first solid background around this component: the map has no box of its own.
|
||||
private fondo() {
|
||||
@@ -68,13 +101,29 @@ export class TeaPacienteResumen implements OnInit {
|
||||
}
|
||||
return '#FFFFFF';
|
||||
}
|
||||
// The side panel shows the chosen metric's head map, its age norm, or both with a switch between them.
|
||||
vista: 'zonas' | 'norma' = 'zonas';
|
||||
figuraNorma?: PlotlyFigure;
|
||||
mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); }
|
||||
elegirMapa(eeg: TeaEeg, codigo: string) {
|
||||
// The chosen card closes the map again, and the cards take the whole space back.
|
||||
const mapa = codigo === this.mapaElegido ? undefined : eeg.mapas.find(m => m.codigo === codigo);
|
||||
this.mapaElegido = mapa?.codigo;
|
||||
this.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
|
||||
// The age norm can only be drawn with the curve, the patient's value and their age.
|
||||
private conNorma(eeg: TeaEeg, codigo?: string) {
|
||||
const m = eeg.alteraciones.find(a => a.codigo === codigo);
|
||||
return m && m.curva_referencia && m.valor !== null && typeof eeg.edad_meses === 'number' ? m : undefined;
|
||||
}
|
||||
normaActual(eeg: TeaEeg) { return this.conNorma(eeg, this.mapaElegido); }
|
||||
abierto(eeg: TeaEeg) { return !!this.mapaActual(eeg) || !!this.normaActual(eeg); }
|
||||
private mostrar(eeg: TeaEeg, codigo: string | undefined) {
|
||||
const mapa = eeg.mapas.find(m => m.codigo === codigo), norma = this.conNorma(eeg, codigo);
|
||||
this.mapaElegido = mapa || norma ? codigo : undefined;
|
||||
this.vista = mapa ? 'zonas' : 'norma';
|
||||
this.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
|
||||
this.figuraNorma = norma && normaFigure(norma, eeg.edad_meses as number);
|
||||
}
|
||||
elegirMapa(eeg: TeaEeg, codigo: string) {
|
||||
// The chosen card closes the panel again, and the cards take the whole space back.
|
||||
this.mostrar(eeg, codigo === this.mapaElegido ? undefined : codigo);
|
||||
}
|
||||
verVista(vista: 'zonas' | 'norma') { this.vista = vista; }
|
||||
readonly clasificacion = CLASIFICACIONES_ADOS2;
|
||||
readonly nivelCss = NIVEL_CSS;
|
||||
readonly calidad = CALIDAD;
|
||||
@@ -84,10 +133,12 @@ export class TeaPacienteResumen implements OnInit {
|
||||
this.status.set('loading');
|
||||
this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
||||
next: d => {
|
||||
// Opens on the first altered metric, or on the first one if none is altered.
|
||||
const e = d.eeg, inicial = e?.mapas.find(m => e.alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'normal')) ?? e?.mapas[0];
|
||||
this.mapaElegido = inicial?.codigo;
|
||||
this.figura = e && inicial ? mapaFigure(e, inicial, this.fondo()) : undefined;
|
||||
// Opens on the first altered metric that has a map or a norm, or on the first one with either if none is altered.
|
||||
const e = d.eeg;
|
||||
if (e) {
|
||||
const conPanel = e.alteraciones.filter(a => e.mapas.some(m => m.codigo === a.codigo) || this.conNorma(e, a.codigo));
|
||||
this.mostrar(e, (conPanel.find(a => a.estado === 'aumentado' || a.estado === 'disminuido') ?? conPanel[0])?.codigo);
|
||||
} else { this.mapaElegido = undefined; this.figura = this.figuraNorma = undefined; }
|
||||
this.detalle.set(d); this.status.set('ready');
|
||||
},
|
||||
error: () => this.status.set('error'),
|
||||
@@ -106,4 +157,24 @@ export class TeaPacienteResumen implements OnInit {
|
||||
clasificacionDe(a: TeaAdos2) { return a.clasificacion ? this.clasificacion[a.clasificacion] : 'Sin clasificación'; }
|
||||
alteradas(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado === 'aumentado' || m.estado === 'disminuido'); }
|
||||
pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; }
|
||||
|
||||
// Relation with the ADOS-2: only the patient's altered zones (|z| ≥ 2), clearest cohort association first.
|
||||
zonaAlterada(f: TeaRelacionAdos2) { return Math.abs(f.valor_z) >= Z_ALTERADO; }
|
||||
filasRelacion(rel: TeaRelacionModelo) { return rel.filas.filter(f => this.zonaAlterada(f)).sort((a, b) => a.q - b.q); }
|
||||
direccion(f: TeaRelacionAdos2) {
|
||||
return f.or >= 1 ? 'A mayor z, mayor probabilidad' : 'A menor z, mayor probabilidad';
|
||||
}
|
||||
porcentaje(p: number) { return Math.round(100 * p); }
|
||||
qTexto(q: number) { return q < 0.001 ? '< 0.001' : `= ${q.toFixed(3)}`; }
|
||||
observado(f: TeaRelacionAdos2) {
|
||||
if (f.observado === null) return 'Sin dato';
|
||||
if (f.tipo === 'item') return f.observado >= 1 ? `Alterado (${f.observado})` : 'Sin anormalidad (0)';
|
||||
return `CSS ${f.observado}`;
|
||||
}
|
||||
// Whether what the patient shows matches what the model leans to (above or below one half).
|
||||
coincide(f: TeaRelacionAdos2) {
|
||||
if (f.observado === null) return null;
|
||||
const presente = f.tipo === 'item' ? f.observado >= 1 : f.observado >= 8;
|
||||
return presente === (f.probabilidad >= .5);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { forkJoin, map, Observable, of, shareReplay } from 'rxjs';
|
||||
import { Bundle, code, codeIn, Concept, display, extension, isSimulated, Quantity, referenceId, Resource, resources } from './fhir';
|
||||
import { Bundle, code, codeIn, Concept, display, extension, extensions, isSimulated, Quantity, referenceId, Resource, resources } from './fhir';
|
||||
import { estratoValor } from './indicadores-fhir';
|
||||
import { SeguimientoQuery } from './cacu-seguimiento.models';
|
||||
import { validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
import {
|
||||
CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg,
|
||||
TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaSeguimientoPaciente, teaSeguimientoResponse,
|
||||
TeaSeguimientoService,
|
||||
CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad,
|
||||
TeaCurvaReferencia, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaRelacionAdos2,
|
||||
TeaRelacionModelo, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService,
|
||||
} from './tea-seguimiento.service';
|
||||
|
||||
// TEA's follow-up list and patient summary over the WebApi's FHIR endpoint: each child's screening is an
|
||||
@@ -26,6 +26,7 @@ interface Report extends Resource {
|
||||
effectiveDateTime?: string; subject?: { reference?: string }; result?: { reference?: string }[]; conclusionCode?: Concept[];
|
||||
}
|
||||
interface Metric { code?: string; display?: string; property?: { code: string; valueString?: string }[] }
|
||||
interface Prediction { outcome?: Concept; probabilityDecimal?: number; extension?: Resource['extension'] }
|
||||
|
||||
const MAX_COUNT = 200;
|
||||
const METRICAS = 'tea-eeg-metrica';
|
||||
@@ -111,6 +112,18 @@ export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null
|
||||
};
|
||||
}
|
||||
|
||||
// The age norm a metric observation carries: one sub-extension per point, read back in order, because a FHIR
|
||||
// extension holds scalars, not arrays.
|
||||
function curvaDe(o: Observation): TeaCurvaReferencia | null {
|
||||
const curva = extension(o, 'curva-referencia');
|
||||
if (!curva) return null;
|
||||
const serie = (nombre: string) => extensions(curva, nombre).map(e => e.valueDecimal).filter((v): v is number => typeof v === 'number');
|
||||
return {
|
||||
fuente: extension(curva, 'fuente')?.valueString ?? '', estado: extension(curva, 'estado')?.valueString ?? '',
|
||||
edad_meses: serie('edad-meses'), p5: serie('p5'), p25: serie('p25'), mediana: serie('mediana'), p75: serie('p75'), p95: serie('p95'),
|
||||
};
|
||||
}
|
||||
|
||||
// A metric against its age baseline. Without a value nothing was measured; with a value but no z, the baseline doesn't
|
||||
// cover the child's age (or none is in production yet).
|
||||
function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
|
||||
@@ -123,6 +136,7 @@ function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
|
||||
const low = o.referenceRange?.[0]?.low?.value, high = o.referenceRange?.[0]?.high?.value;
|
||||
const referencia = typeof low === 'number' && typeof high === 'number'
|
||||
? { min: low, max: high, mediana: component(o, 'mediana')?.valueQuantity?.value ?? null } : null;
|
||||
const curva = evaluable ? curvaDe(o) : null;
|
||||
return {
|
||||
codigo, etiqueta: display(o.code) ?? metrica?.display ?? codigo,
|
||||
unidad: o.valueQuantity?.unit ?? metrica?.property?.find(p => p.code === 'unidad')?.valueString ?? '',
|
||||
@@ -130,6 +144,7 @@ function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
|
||||
valor, valor_z: evaluable && typeof z === 'number' ? z : null, estado,
|
||||
sin_evaluar: evaluable ? null : valor === null ? 'sin_valor' : 'sin_referencia',
|
||||
efectos: (metrica?.property ?? []).filter(p => p.code === `efecto-${estado}`).map(p => p.valueString!).filter(Boolean),
|
||||
...(curva ? { curva_referencia: curva } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -152,6 +167,7 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
|
||||
const listed = observations.filter(o => ids.has(o.id));
|
||||
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'SIN_ANALIZAR').toLowerCase() as TeaNivelCalidad;
|
||||
const duracion = extension(report, 'duracion-min')?.valueDecimal;
|
||||
const edad = extension(report, 'edad-meses')?.valueDecimal;
|
||||
// The report lists each metric's electrode map under the same code too; it feeds the maps, not the cards.
|
||||
const alteraciones = listed.filter(o => codeIn(o.code, METRICAS) && !o.id?.startsWith('electrodos-')).map(o => alteracion(o, metricas));
|
||||
// A metric's electrode values are `electrodos-<the metric observation's id>`.
|
||||
@@ -166,6 +182,7 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
|
||||
fecha: report.effectiveDateTime.slice(0, 10),
|
||||
duracion_min: duracion === undefined ? null : Math.round(duracion),
|
||||
canales: extension(report, 'canales')?.valueInteger ?? null,
|
||||
...(typeof edad === 'number' ? { edad_meses: edad } : {}),
|
||||
calidad: calidad(report.conclusionCode?.[0]),
|
||||
criterios_calidad: listed.filter(o => codeIn(o.code, CRITERIOS)).map(criterio),
|
||||
alteraciones, mapas,
|
||||
@@ -173,6 +190,34 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
|
||||
};
|
||||
}
|
||||
|
||||
// The ADOS-2 association model: one `RiskAssessment`, a prediction per association row with the patient's z and
|
||||
// probabilities. A row missing a number the panel needs is left out; without rows there is no panel.
|
||||
export function relacionDeRiesgo(riesgo: Resource | undefined): TeaRelacionModelo | null {
|
||||
if (!riesgo) return null;
|
||||
const nivel = extension(riesgo, 'modelo-nivel')?.valueString;
|
||||
const filas = ((riesgo['prediction'] ?? []) as Prediction[]).map((p): TeaRelacionAdos2 | null => {
|
||||
const numero = (nombre: string) => extension(p, nombre)?.valueDecimal;
|
||||
const biomarcador = extension(p, 'biomarcador')?.valueCoding, zona = extension(p, 'zona')?.valueCoding;
|
||||
const tipo = extension(p, 'tipo')?.valueString, evento = extension(p, 'evento')?.valueString;
|
||||
const valores = [numero('valor-z'), numero('odds-ratio'), numero('ic-inf'), numero('ic-sup'), numero('q'), p.probabilityDecimal,
|
||||
numero('probabilidad-referencia')];
|
||||
if (!biomarcador?.code || !zona?.code || (tipo !== 'item' && tipo !== 'dominio') || !evento || !code(p.outcome)
|
||||
|| !valores.every(v => typeof v === 'number')) return null;
|
||||
const [valor_z, or, ic_inf, ic_sup, q, probabilidad, probabilidad_referencia] = valores as number[];
|
||||
return {
|
||||
biomarcador: biomarcador.display ?? biomarcador.code, zona: zona.code, zona_etiqueta: zona.display ?? zona.code, valor_z,
|
||||
tipo, resultado: code(p.outcome)!, resultado_etiqueta: display(p.outcome) ?? code(p.outcome)!, evento,
|
||||
or, ic_inf, ic_sup, q, probabilidad, probabilidad_referencia, observado: extension(p, 'observado')?.valueInteger ?? null,
|
||||
};
|
||||
}).filter((f): f is TeaRelacionAdos2 => f !== null);
|
||||
if ((nivel !== 'item' && nivel !== 'dominio') || !filas.length) return null;
|
||||
return {
|
||||
validado: extension(riesgo, 'modelo-validado')?.valueBoolean === true, nivel,
|
||||
n_cohorte: extension(riesgo, 'modelo-n-cohorte')?.valueInteger ?? 0,
|
||||
version: extension(riesgo, 'modelo-version')?.valueString ?? '', filas,
|
||||
};
|
||||
}
|
||||
|
||||
function resultadoEeg(report: Report | undefined, observations: Observation[], validadas: boolean): 'normal' | 'anormal' | null {
|
||||
if (!validadas || !report || code(report.conclusionCode?.[0]) !== 'BUENO') return null;
|
||||
return alteracionesDe(report, observations).length ? 'anormal' : 'normal';
|
||||
@@ -288,12 +333,14 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
|
||||
const all = resources(bundle);
|
||||
const observations = all.filter(r => r.resourceType === 'Observation') as Observation[];
|
||||
const episode = resources(bundle, 'EpisodeOfCare')[0];
|
||||
const relacion = relacionDeRiesgo(resources(bundle, 'RiskAssessment')[0]);
|
||||
return teaPacienteDetalle({
|
||||
simulado: all.length > 0 && all.every(isSimulated),
|
||||
id_seudonimo: id,
|
||||
grupo_edad: grupoEdad(episode && extension(episode, 'grupo-edad')?.valueCoding?.code),
|
||||
ados2: ados2DeObservacion(byCode(observations, 'ados2')),
|
||||
eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas),
|
||||
...(relacion ? { relacion_ados2: relacion } : {}),
|
||||
}, id);
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -56,10 +56,17 @@ export interface TeaEegAlteracion {
|
||||
valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[];
|
||||
// Why it could not be evaluated: nothing measured (spindles without sleep), or no reference for the child's age.
|
||||
sin_evaluar: 'sin_valor' | 'sin_referencia' | null;
|
||||
// The age norm the reference comes from (percentiles by month), when the analysis sends it.
|
||||
curva_referencia?: TeaCurvaReferencia | null;
|
||||
}
|
||||
export interface TeaCurvaReferencia {
|
||||
fuente: string; estado: string; edad_meses: number[]; p5: number[]; p25: number[]; mediana: number[]; p75: number[]; p95: number[];
|
||||
}
|
||||
export interface TeaEegMapa { codigo: string; metrica: string; z: (number | null)[][]; regiones: TeaEegRegion[] }
|
||||
export interface TeaEeg {
|
||||
fecha: string; duracion_min: number | null; canales: number | null;
|
||||
// Age at the EEG, to place the patient on the age norms.
|
||||
edad_meses?: number | null;
|
||||
// The overall rating is the EEG analysis's verdict; its checks say why.
|
||||
calidad: TeaNivelCalidad; criterios_calidad: TeaCriterioCalidad[];
|
||||
alteraciones: TeaEegAlteracion[];
|
||||
@@ -67,7 +74,20 @@ export interface TeaEeg {
|
||||
mapas: TeaEegMapa[];
|
||||
ejes_mapa: { x: number[]; y: number[]; electrodos: { nombre: string; x: number; y: number }[] };
|
||||
}
|
||||
export interface TeaPacienteDetalle { simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null }
|
||||
// The association model (OR) of each EEG alteration by zone with an ADOS-2 item or domain, fitted on the cohort; for
|
||||
// this patient, their z, the probability the model gives them and what their ADOS-2 shows. Pending medical validation.
|
||||
export interface TeaRelacionAdos2 {
|
||||
biomarcador: string; zona: string; zona_etiqueta: string; valor_z: number;
|
||||
tipo: 'item' | 'dominio'; resultado: string; resultado_etiqueta: string; evento: string;
|
||||
or: number; ic_inf: number; ic_sup: number; q: number;
|
||||
probabilidad: number; probabilidad_referencia: number; observado: number | null;
|
||||
}
|
||||
export interface TeaRelacionModelo { validado: boolean; nivel: 'item' | 'dominio'; n_cohorte: number; version: string; filas: TeaRelacionAdos2[] }
|
||||
export interface TeaPacienteDetalle {
|
||||
simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null;
|
||||
// Absent until the WebApi serves the model.
|
||||
relacion_ados2?: TeaRelacionModelo | null;
|
||||
}
|
||||
// TEA has no follow-up status; its third filter is the EEG result, using the CaCu status shape.
|
||||
export const CLASIFICACIONES_ADOS2: Record<ClasificacionAdos2, string> = {
|
||||
autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro',
|
||||
@@ -141,13 +161,24 @@ function validAdos(a: unknown): boolean {
|
||||
return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0)
|
||||
&& a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0);
|
||||
}
|
||||
// An age norm: ages in increasing order and, at each one, percentiles that never cross.
|
||||
const PERCENTILES = ['p5', 'p25', 'mediana', 'p75', 'p95'] as const;
|
||||
function validCurva(c: unknown): boolean {
|
||||
if (c === undefined || c === null) return true;
|
||||
if (!record(c) || !text(c['fuente']) || !text(c['estado']) || !Array.isArray(c['edad_meses'])) return false;
|
||||
const edades = c['edad_meses'] as unknown[], n = edades.length;
|
||||
if (n < 2 || !edades.every((e, i) => finite(e) && (i === 0 || (e as number) > (edades[i - 1] as number)))) return false;
|
||||
const series = PERCENTILES.map(k => c[k]);
|
||||
return series.every(s => Array.isArray(s) && s.length === n && s.every(finite))
|
||||
&& edades.every((_, i) => series.every((s, k) => k === 0 || (s as number[])[i] >= (series[k - 1] as number[])[i]));
|
||||
}
|
||||
// A metric that can't be evaluated says why and has no z; one that can has its value, z and reference.
|
||||
function validAlteracion(a: unknown): boolean {
|
||||
const ref = a !== null && record(a) ? a['referencia'] : undefined;
|
||||
if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string'
|
||||
|| !(ref === null || record(ref) && finite(ref['min']) && finite(ref['max']) && (ref['min'] as number) <= (ref['max'] as number)
|
||||
&& (ref['mediana'] === null || finite(ref['mediana'])))
|
||||
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text)) return false;
|
||||
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text) || !validCurva(a['curva_referencia'])) return false;
|
||||
const estado = a['estado'];
|
||||
if (estado === 'no_evaluable') return a['valor_z'] === null && ['sin_valor', 'sin_referencia'].includes(a['sin_evaluar'] as string)
|
||||
&& (a['sin_evaluar'] === 'sin_valor') === (a['valor'] === null);
|
||||
@@ -157,7 +188,9 @@ function validAlteracion(a: unknown): boolean {
|
||||
function validEeg(e: unknown): boolean {
|
||||
if (e === null) return true;
|
||||
const optional = (v: unknown) => v === null || integer(v);
|
||||
const edad = record(e) ? e['edad_meses'] : undefined;
|
||||
if (!record(e) || !isoDate(e['fecha']) || !optional(e['duracion_min']) || !optional(e['canales'])
|
||||
|| !(edad === undefined || edad === null || finite(edad) && (edad as number) >= 0)
|
||||
|| !['bueno', 'malo', 'sin_analizar'].includes(e['calidad'] as string)
|
||||
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta'])
|
||||
&& ['bueno', 'malo'].includes(c['nivel'] as string) && typeof c['unidad'] === 'string' && typeof c['decisivo'] === 'boolean'
|
||||
@@ -172,9 +205,21 @@ function validEeg(e: unknown): boolean {
|
||||
&& m['z'].every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v)))
|
||||
&& Array.isArray(m['regiones']) && m['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z'])));
|
||||
}
|
||||
const probability = (v: unknown) => finite(v) && (v as number) >= 0 && (v as number) <= 1;
|
||||
function validRelacion(r: unknown): boolean {
|
||||
if (r === undefined || r === null) return true;
|
||||
return record(r) && typeof r['validado'] === 'boolean' && ['item', 'dominio'].includes(r['nivel'] as string)
|
||||
&& integer(r['n_cohorte'], 1) && text(r['version']) && Array.isArray(r['filas'])
|
||||
&& r['filas'].every(f => record(f) && text(f['biomarcador']) && text(f['zona_etiqueta']) && finite(f['valor_z'])
|
||||
&& ['item', 'dominio'].includes(f['tipo'] as string) && text(f['resultado_etiqueta']) && text(f['evento'])
|
||||
&& finite(f['or']) && finite(f['ic_inf']) && finite(f['ic_sup']) && (f['ic_inf'] as number) <= (f['ic_sup'] as number)
|
||||
&& probability(f['q']) && probability(f['probabilidad']) && probability(f['probabilidad_referencia'])
|
||||
&& (f['observado'] === null || finite(f['observado'])));
|
||||
}
|
||||
export function teaPacienteDetalle(v: unknown, id: string): TeaPacienteDetalle {
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg']))
|
||||
if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg'])
|
||||
|| !validRelacion(v['relacion_ados2']))
|
||||
throw new Error('Resumen del paciente inválido');
|
||||
return v as unknown as TeaPacienteDetalle;
|
||||
}
|
||||
|
||||
@@ -172,6 +172,41 @@ describe('Seguimiento TEA', () => {
|
||||
expect(root.querySelector('section.mapa')).not.toBeNull();
|
||||
http.verify();
|
||||
});
|
||||
it('muestra la norma por edad con el paciente, con o sin mapa, y rechaza una curva cuyos percentiles se cruzan', () => {
|
||||
const curva = { fuente: 'Helsinki (HK1K, base pública)', estado: 'vigilia', edad_meses: [12, 24, 48],
|
||||
p5: [0.5, 0.6, 0.7], p25: [0.8, 1, 1.1], mediana: [1.2, 1.5, 1.6], p75: [1.6, 1.8, 2], p95: [2, 2.2, 2.4] };
|
||||
const conCurva = detalle.eeg.alteraciones.map(m =>
|
||||
m.codigo === 'ritmo_posterior' || m.codigo === 'gradiente_anteroposterior' ? { ...m, curva_referencia: curva } : m);
|
||||
const conNorma = { ...detalle, eeg: { ...detalle.eeg, edad_meses: 20.5, alteraciones: conCurva } };
|
||||
const fixture = open();
|
||||
request().flush(data); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelector<HTMLButtonElement>('button.row-toggle')!.click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(conNorma); fixture.detectChanges();
|
||||
const panel = () => root.querySelector('section.mapa')!;
|
||||
const vistas = () => panel().querySelectorAll<HTMLButtonElement>('.vistas button');
|
||||
// Ritmo has both: it opens on the map, and the switch moves to the norm with the patient's value and age.
|
||||
expect(Array.from(vistas()).map(b => b.textContent)).toEqual(['Zonas de la cabeza', 'Norma por edad']);
|
||||
expect(panel().textContent).toContain('Zonas más afectadas');
|
||||
vistas()[1].click(); fixture.detectChanges();
|
||||
expect(vistas()[1].getAttribute('aria-pressed')).toBe('true');
|
||||
expect(panel().querySelector('h3')!.textContent).toBe('Norma por edad');
|
||||
expect(panel().textContent).toContain('0.9 a los 20.5 meses (z = -2.4)');
|
||||
expect(panel().querySelector('.regiones')).toBeNull();
|
||||
// Gradiente has no map: its card opens the norm alone, without the switch.
|
||||
const tarjetas = root.querySelectorAll<HTMLButtonElement>('button.nombre');
|
||||
tarjetas[4].click(); fixture.detectChanges();
|
||||
expect(tarjetas[4].getAttribute('aria-expanded')).toBe('true');
|
||||
expect(vistas().length).toBe(0);
|
||||
expect(panel().textContent).toContain('Gradiente anteroposterior');
|
||||
const c = fixture.debugElement.query(d => d.name === 'app-tea-paciente-resumen').componentInstance;
|
||||
const trazas = c.figuraNorma.data as { name: string; x: number[]; y: number[] }[];
|
||||
expect(trazas.map(t => t.name)).toEqual(['Del 5 al 95 %', 'Del 25 al 75 %', 'Mediana', 'Este paciente']);
|
||||
expect([trazas[3].x[0], trazas[3].y[0]]).toEqual([20.5, 1.2]);
|
||||
const cruzada = conCurva.map(m => m.codigo === 'ritmo_posterior' ? { ...m, curva_referencia: { ...curva, p25: [0.8, 3, 1.1] } } : m);
|
||||
expect(() => teaPacienteDetalle({ ...conNorma, eeg: { ...conNorma.eeg, alteraciones: cruzada } }, 'T-0001')).toThrow();
|
||||
http.verify();
|
||||
});
|
||||
it('el mapa oculta lo que queda fuera de la cabeza con el color que tiene detrás', () => {
|
||||
const figura = (fondo?: string) => mapaFigure(detalle.eeg as unknown as TeaEeg, detalle.eeg.mapas[0] as unknown as TeaEegMapa, fondo);
|
||||
const marco = (fondo?: string) => (figura(fondo).layout['shapes'] as { fillcolor: string }[])[0].fillcolor;
|
||||
@@ -342,4 +377,29 @@ describe('Seguimiento TEA', () => {
|
||||
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], efectos: [''] }), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(con(alteraciones[3]), 'T-0001')).not.toThrow();
|
||||
});
|
||||
// The association model's panel (prototype, simulated data): the field is optional and checked when present.
|
||||
it('valida la relación con el ADOS-2 y solo muestra las zonas alteradas del paciente', () => {
|
||||
const fila = { biomarcador: 'husos', zona: 'central', zona_etiqueta: 'Central', valor_z: -2.5, tipo: 'dominio', resultado: 'css_sa',
|
||||
resultado_etiqueta: 'CSS afecto social', evento: 'Severidad alta (CSS ≥ 8)', or: 0.2, ic_inf: 0.13, ic_sup: 0.3, q: 0.0002,
|
||||
probabilidad: 0.93, probabilidad_referencia: 0.18, observado: 10 };
|
||||
const otra = { ...fila, zona: 'parietal', zona_etiqueta: 'Parietal', valor_z: 0.4, q: 0.01 };
|
||||
const rel = (filas: object[]) => ({ ...detalle, relacion_ados2: { validado: false, nivel: 'item', n_cohorte: 46, version: 'v', filas } });
|
||||
expect(() => teaPacienteDetalle(detalle, 'T-0001')).not.toThrow();
|
||||
expect(() => teaPacienteDetalle({ ...detalle, relacion_ados2: null }, 'T-0001')).not.toThrow();
|
||||
expect(() => teaPacienteDetalle(rel([fila]), 'T-0001')).not.toThrow();
|
||||
expect(() => teaPacienteDetalle(rel([{ ...fila, probabilidad: 1.2 }]), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(rel([{ ...fila, ic_inf: 0.5 }]), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(rel([{ ...fila, tipo: 'zona' }]), 'T-0001')).toThrow();
|
||||
const fixture = open();
|
||||
request().flush(tres); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[0].click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(rel([otra, fila])); fixture.detectChanges();
|
||||
const filas = Array.from(root.querySelectorAll('section.relacion tbody tr'));
|
||||
expect(filas.length).toBe(1);
|
||||
expect(filas[0].classList.contains('alterada')).toBe(true);
|
||||
expect(filas[0].textContent).toContain('q < 0.001');
|
||||
expect(filas[0].textContent).toContain('93 %');
|
||||
http.verify();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user