Compare commits

..

4 Commits

Author SHA1 Message Date
edgar 284db98b23 feat(indicadores): add the screening route chart to CaCu
Horizontal bars of the days from the sample to each event of the route (cytology result, colposcopy, biopsy result and
diagnosis), cumulative with the Q1 to Q3 interval or step by step with each step starting where the previous one ends.
It reads the seven duration measures of the route and shows up in CaCu's page once the catalog publishes all of them;
the measures only it draws get no card of their own.
2026-11-22 00:02:42 -06:00
edgar e5aa205662 fix(indicadores): draw CaCu's proportions in the history
The WebApi names the group of a proportion `principal`; the page read it as `total` only for CaMa, so the EU13 and
IND1 trends of CaCu came out empty. The rename now applies to every domain, and IND1 is listed in CaCu's history under
the id the catalog gives it.
2026-11-21 21:48:42 -06:00
edgar 89f3d41e0c feat(indicadores): add the Histórico tab to CaCu
CaCu's history is a fixed list, like CaMa's, with a pending panel for each indicator the catalog does not publish.
The risk bands stay out until their batches are readable.
2026-11-21 17:54:23 -06:00
edgar 2e9dd39cf1 fix(indicadores): read a proportion's interval as percentages
The ic-bajo and ic-alto of a proportion's score travel as proportions; the rows hold percentages, like the value,
so the history trend draws its confidence band on the same axis.
2026-11-21 17:42:02 -06:00
28 changed files with 736 additions and 453 deletions
+1 -1
View File
@@ -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; valueBoolean?: boolean;
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number;
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
extension?: Extension[];
}
@@ -384,7 +384,7 @@
"estrato": null,
"valores_estrato": [],
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -410,7 +410,7 @@
"filas": [
{
"periodo": "2021-S1",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 0,
@@ -423,7 +423,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 1,
@@ -463,7 +463,7 @@
"<25": "<25"
},
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -489,7 +489,7 @@
"filas": [
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "25-34",
"suprimido": 0,
"numerador": 0,
@@ -502,7 +502,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "35-44",
"suprimido": 0,
"numerador": 0,
@@ -515,7 +515,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "45-54",
"suprimido": 0,
"numerador": 1,
@@ -528,7 +528,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "55-64",
"suprimido": 0,
"numerador": 0,
@@ -541,7 +541,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "<25",
"suprimido": 0,
"numerador": 0,
@@ -573,7 +573,7 @@
"PRE_COLPOSCOPIA": "PRE_COLPOSCOPIA"
},
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -599,7 +599,7 @@
"filas": [
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "PRE_COLPOSCOPIA",
"suprimido": 0,
"numerador": 1,
@@ -845,7 +845,7 @@
"estrato": null,
"valores_estrato": [],
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -871,7 +871,7 @@
"filas": [
{
"periodo": "2021-S1",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 0,
@@ -884,7 +884,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 19,
@@ -0,0 +1,46 @@
<section class="route" aria-label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje">
<h3 class="figure-title">Tiempos de la ruta del tamizaje</h3>
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando los tiempos de la ruta del tamizaje" /><p role="status">Cargando los tiempos de la ruta…</p> }
@case ('error') { <div role="alert"><p>{{ message() }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
@case ('incompatible') { <div role="alert"><p>{{ message() }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
}
@if (model(); as m) {
<div class="controls">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Periodo</mat-label>
<mat-select [value]="m.period" (selectionChange)="selectPeriod($event.value)" aria-label="Periodo de la ruta del tamizaje">
@for (period of m.periods; track period) { <mat-option [value]="period">{{ periodLabel(period) }}</mat-option> }
</mat-select>
</mat-form-field>
<mat-button-toggle-group [value]="view()" (change)="selectView($event.value)" aria-label="Vista de los tiempos">
<mat-button-toggle value="cumulative">Acumulado desde la toma</mat-button-toggle>
<mat-button-toggle value="steps">Por pasos</mat-button-toggle>
</mat-button-toggle-group>
</div>
@if (status() === 'empty') { <p role="status">No hay tiempos publicados para esta ruta.</p> }
@else if (figure(); as figure) {
<app-plotly-chart [figure]="figure" [showNotes]="false" label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje" />
<p class="note">
@if (view() === 'cumulative') {
Cada barra es la mediana de días desde la toma de muestra hasta ese evento y el bigote va de Q1 a Q3. Cada fila cuenta solo a quienes llegaron a ese evento.
El diagnóstico incluye a quienes lo recibieron tras el tamizaje, en la colposcopía o tras la biopsia, por eso su barra puede salir antes que la de biopsia.
} @else {
Cada barra es el tramo desde el evento anterior y empieza donde termina el tramo previo; la de color es el tramo más lento. Cada tramo cuenta solo a quienes llegaron a sus dos eventos.
Las medianas de los tramos no tienen que sumar el tiempo acumulado.
}
</p>
}
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" aria-label="Tabla de tiempos de la ruta del tamizaje" tabindex="0">
<table><caption>Días por evento en {{ m.period ? periodLabel(m.period) : 'el periodo' }}</caption>
<thead><tr><th scope="col">Evento</th><th scope="col">Desde la toma</th><th scope="col">Desde el paso anterior</th></tr></thead>
<tbody>@for (row of m.rows; track row.step.id) {
<tr><th scope="row">{{ row.step.label }}</th><td>{{ cellText(row.fromSample) }}</td><td>{{ cellText(row.fromPrevious) }}</td></tr>
}</tbody>
</table>
</div>
</details>
}
</section>
@@ -0,0 +1,13 @@
:host { display: block; min-width: 0; }
.route { min-width: 0; padding-top: var(--issste-space-3); }
p, h3, summary { overflow-wrap: anywhere; }
h3 { font-size: 1rem; line-height: 1.5; }
.controls { display: flex; flex-wrap: wrap; gap: 1rem 1.5rem; align-items: center; margin-block: .75rem; }
.note { color: var(--issste-text-secondary); max-width: 70ch; }
app-plotly-chart { --plot-height: 360px; }
summary { cursor: pointer; padding-block: .75rem; }
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.table-scroll { overflow: auto; max-height: 28rem; }
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
caption { text-align: start; font-weight: 600; }
@@ -0,0 +1,112 @@
// What this module covers: the screening route component: when it loads, the seven requests it makes, what it draws for
// each view and period, and its empty, error and incompatible states. The model and the figure have their own spec
// (`screening-route.spec.ts`).
// Fixtures: `payload`, synthetic C3r /datos shaped like /cacu/indicadores/<id>/datos; `ChartStub` stands for the chart.
import { Component, input } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadorScreeningRoute } from './indicador-screening-route';
import { IndicadorDatos } from './indicadores.models';
import { ROUTE_IDS } from './screening-route';
@Component({ selector: 'app-plotly-chart', template: '' })
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); }
const row = (periodo: string, n: number, q1: number, mediana: number, q3: number, suprimido = 0) =>
({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido, unidad: 'dias' });
const MEDIANAS: Record<string, number> = {
cacu_eu_tiempo_reporte: 7.9, cacu_dias_toma_colposcopia: 35.7, cacu_dias_resultado_colposcopia: 27.8, cacu_dias_toma_biopsia: 52.1,
cacu_dias_colposcopia_biopsia: 16.4, cacu_dias_toma_diagnostico: 18.4, cacu_dias_biopsia_diagnostico: 12.8,
};
const payload = (id: string, suprimido = 0): IndicadorDatos => ({
id, contrato: 'C3r', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'], version: '1',
filas: [row('2025-S1', 100, 3, MEDIANAS[id] + 1, MEDIANAS[id] + 9, suprimido), row('2025-S2', 120, 4, MEDIANAS[id], MEDIANAS[id] + 8, suprimido)],
});
describe('Ruta del tamizaje: componente', () => {
let f: ReturnType<typeof TestBed.createComponent<IndicadorScreeningRoute>>;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadorScreeningRoute], providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadorScreeningRoute, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
f = TestBed.createComponent(IndicadorScreeningRoute);
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('tema', 'claro');
});
afterEach(() => { f.destroy(); http.match(() => true); http.verify(); });
// The shared request queue runs a few at a time: answer in waves until nothing is left.
function responder(entrega: (id: string) => IndicadorDatos = id => payload(id)) {
const vistos: string[] = [];
for (;;) {
const pendientes = http.match(r => r.url.endsWith('/datos'));
if (!pendientes.length) return vistos;
for (const r of pendientes) { const id = r.request.url.split('/').at(-2)!; vistos.push(id); r.flush(entrega(id)); }
f.detectChanges();
}
}
const charts = () => f.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
it('carga diferida; pide las siete medidas; dibuja una gráfica y cambia de vista y de periodo sin otra petición', () => {
// Pins down: nothing is requested while hidden, each of the seven measures is requested once, the view and the period
// are chosen without new requests, and the theme redraws the same data. Fails if the region loads before it is
// visible, a measure is missing or repeated, or a control triggers a request.
f.componentRef.setInput('visible', false); f.detectChanges();
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
f.componentRef.setInput('visible', true); f.detectChanges();
expect(f.componentInstance.status()).toBe('loading');
expect(responder().sort()).toEqual([...ROUTE_IDS].sort());
expect(f.componentInstance.status()).toBe('ready');
expect(charts()).toHaveLength(1);
expect(charts()[0].figure()).toBe(f.componentInstance.figure());
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeUndefined();
f.componentInstance.selectView('steps'); f.detectChanges();
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeDefined();
f.componentInstance.selectPeriod('2025-S1'); f.detectChanges();
expect(f.componentInstance.model()!.period).toBe('2025-S1');
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
expect(f.componentInstance.figure()!.layout['paper_bgcolor']).toBe('#081839');
http.expectNone(() => true);
});
it('la tabla de valores publicados dice la mediana de cada evento y el estado si no hay caja', () => {
// Fails if the table drops an event or shows a suppressed box as a number.
f.detectChanges();
responder(id => (id === 'cacu_dias_toma_biopsia' ? payload(id, 1) : payload(id)));
const text = f.nativeElement.querySelector('table').textContent as string;
expect(text).toContain('Resultado de citología');
expect(text).toContain('mediana 35.7');
expect(text).toContain('Suprimido');
});
it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => {
// Fails if an empty route draws a chart or hides the reason.
f.detectChanges();
responder(id => payload(id, 1));
expect(f.componentInstance.status()).toBe('empty');
expect(charts()).toHaveLength(0);
expect(f.nativeElement.textContent).toContain('No hay tiempos publicados');
});
it('un fallo del servicio se anuncia como error y reintentar vuelve a pedir', () => {
// Fails if an error leaves a stale chart, hides the alert, or retry does not request again.
f.detectChanges();
http.match(r => r.url.endsWith('/datos'))[0].flush({}, { status: 500, statusText: 'Server Error' });
f.detectChanges();
expect(f.componentInstance.status()).toBe('error');
expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
expect(charts()).toHaveLength(0);
http.match(() => true); // the other requests of the first try were cancelled with it
f.componentInstance.retry(); f.detectChanges();
expect(f.componentInstance.status()).toBe('loading');
expect(responder().length).toBe(ROUTE_IDS.length);
expect(f.componentInstance.status()).toBe('ready');
});
it('datos de otro contrato quedan incompatibles y no se dibujan', () => {
// Fails if a payload that is not a duration is drawn as one.
f.detectChanges();
responder(id => (id === 'cacu_dias_toma_biopsia' ? { ...payload(id), contrato: 'C1' } : payload(id)));
expect(f.componentInstance.status()).toBe('incompatible');
expect(charts()).toHaveLength(0);
expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
});
});
@@ -0,0 +1,86 @@
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { forkJoin, Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSelectModule } from '@angular/material/select';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
import { etiquetaPeriodo } from './indicadores-historico-figures';
import { httpMessage } from './indicadores-http';
import { IndicadoresSnapshots } from './indicadores-snapshots';
import { ROUTE_IDS, RouteIncompatible, RouteView, routeCellText, routeFigure, routeHasData, routeModel } from './screening-route';
/** Days along the screening route, from the sample to each event, as horizontal bars: cumulative or step by step. */
@Component({
selector: 'app-indicador-screening-route',
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
templateUrl: './indicador-screening-route.html',
styleUrl: './indicador-screening-route.scss',
})
export class IndicadorScreeningRoute {
readonly dominio = input.required<Dominio>();
readonly tema = input.required<Tema>();
readonly tipo = input<TipoPeriodo>('semestre');
/** The measures load once the region is visible. */
readonly visible = input(true);
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
readonly message = signal('');
readonly view = signal<RouteView>('cumulative');
readonly requestedPeriod = signal<string | undefined>(undefined);
private readonly payloads = signal<Record<string, IndicadorDatos> | undefined>(undefined);
readonly model = computed(() => {
const data = this.payloads();
return data ? routeModel(data, this.tipo(), this.requestedPeriod()) : undefined;
});
readonly figure = computed(() => {
const model = this.model();
return model && routeHasData(model) ? routeFigure(model, this.view(), this.tema()) : undefined;
});
readonly periodLabel = etiquetaPeriodo;
readonly cellText = routeCellText;
private readonly snapshots = inject(IndicadoresSnapshots);
private subscription?: Subscription;
constructor() {
effect(() => {
const dominio = this.dominio(), tipo = this.tipo();
if (!this.visible()) { this.status.set('deferred'); return; }
untracked(() => this.load(dominio, tipo));
});
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
}
retry() { this.load(this.dominio(), this.tipo()); }
selectPeriod(period: string) { this.requestedPeriod.set(period); }
selectView(view: RouteView) { this.view.set(view); }
private load(dominio: Dominio, tipo: TipoPeriodo) {
this.subscription?.unsubscribe();
this.payloads.set(undefined);
this.status.set('loading');
const requests = Object.fromEntries(ROUTE_IDS.map(id => [id, this.snapshots.datos(dominio, id, tipo)]));
this.subscription = forkJoin(requests).pipe(timeout({ first: 40000 })).subscribe({
next: data => {
try {
const model = routeModel(data, tipo, this.requestedPeriod());
this.payloads.set(data);
this.status.set(routeHasData(model) ? 'ready' : 'empty');
} catch (error) { this.failure(error); }
},
error: error => this.failure(error),
});
}
private failure(error: unknown) {
this.payloads.set(undefined);
this.message.set(error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
: error instanceof RouteIncompatible ? error.message : httpMessage(error));
this.status.set(error instanceof RouteIncompatible || (error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError))
? 'incompatible' : 'error');
}
}
@@ -10,6 +10,7 @@ import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
import { GlobalApplied } from './indicadores-memory';
import { historicoFigura } from './indicadores-historico-figures';
const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition';
const ENDPOINT = ['CACU-CONFIRMACION-CITOLOGIA', 'CACU-DIAS-TOMA-DIAGNOSTICO', 'CACU-EU-TIEMPO-REPORTE', 'CACU-EU13', 'CACU-EU7',
@@ -130,4 +131,37 @@ describe('Las medidas de CaCu como las publica el WebApi con figuras y etiquetas
expect(dibujo.status).toBe('supported');
}
});
it('un C1 publicado con su intervalo de Wilson llena la banda del histórico, en porcentaje', () => {
// Pins down: the `ic-bajo` and `ic-alto` of a proportion's score (proportions) reach the rows as percentages and
// the history trend draws them as its band. Fails if the bounds are read unconverted or dropped.
const eu13 = medida('CACU-EU13');
const cuenta = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
const reporte13 = { resourceType: 'MeasureReport', id: 'CACU-EU13-1', period: { start: '2025-01-01', end: '2025-06-30' },
group: [{ code: { coding: [{ code: 'principal' }] }, population: [cuenta('initial-population', 4), cuenta('denominator', 4), cuenta('numerator', 1)],
measureScore: { value: 0.25, extension: [{ url: `${STRUCTURE}/ic-bajo`, valueDecimal: 0.0456 }, { url: `${STRUCTURE}/ic-alto`, valueDecimal: 0.6994 }] } }] } as unknown as Report;
const datos = datosDeReportes(eu13, [reporte13], 'semestre');
expect(datos.filas[0]).toMatchObject({ valor: 25, ic_bajo: 4.6, ic_alto: 69.9 });
const banda = (historicoFigura(datos, 'claro').figure as unknown as { data: { name: string; y: number[] }[] }).data[0];
expect(banda.name).toBe('Intervalo de confianza');
expect(banda.y).toEqual([69.9, 4.6]);
});
it('un C1 de CaCu cuyo grupo se llama principal dibuja su tendencia en el histórico', () => {
// Pins down: the WebApi names the group of a proportion `principal`; the page reads it as `total`, the group the
// history trend draws, for CaCu as for CaMa. Fails if the rows keep the group `principal` and the trend comes out
// empty, with its period listed as having no data.
const cuenta = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
for (const id of ['CACU-EU13', 'IND1']) {
const medida13 = medida(id);
const reporte = { resourceType: 'MeasureReport', id: id + '-1', period: { start: '2025-01-01', end: '2025-06-30' },
group: [{ code: { coding: [{ code: 'principal' }] }, population: [cuenta('initial-population', 4), cuenta('denominator', 4), cuenta('numerator', 1)],
measureScore: { value: 0.25 } }] } as unknown as Report;
const datos = datosDeReportes(medida13, [reporte], 'semestre');
expect(datos.filas[0]['grupo']).toBe('total');
const figura = historicoFigura(datos, 'claro');
expect((figura.figure as unknown as { data: { y: number[] }[] }).data[1].y).toEqual([25]);
expect(figura.sinDato).toEqual([]);
}
});
});
@@ -6,6 +6,11 @@
// the correspondence is explicit, as CaMa's is, and a measure outside it keeps the generic rule.
export const CACU_MEASURE_IDS: Readonly<Record<string, string>> = {
'CACU-CONFIRMACION-CITOLOGIA': 'cacu_confirmacion_citologia',
'CACU-DIAS-BIOPSIA-DIAGNOSTICO': 'cacu_dias_biopsia_diagnostico',
'CACU-DIAS-COLPOSCOPIA-BIOPSIA': 'cacu_dias_colposcopia_biopsia',
'CACU-DIAS-RESULTADO-COLPOSCOPIA': 'cacu_dias_resultado_colposcopia',
'CACU-DIAS-TOMA-BIOPSIA': 'cacu_dias_toma_biopsia',
'CACU-DIAS-TOMA-COLPOSCOPIA': 'cacu_dias_toma_colposcopia',
'CACU-DIAS-TOMA-DIAGNOSTICO': 'cacu_dias_toma_diagnostico',
'CACU-EU-TIEMPO-REPORTE': 'cacu_eu_tiempo_reporte',
'CACU-EU13': 'cacu_eu13',
@@ -2,14 +2,12 @@
// 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; `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.
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database.
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, Resource, resources } from './fhir';
import { Bundle, resources } from './fhir';
import {
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado,
periodosDesde, Report,
@@ -22,49 +20,6 @@ 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', () => {
@@ -255,49 +210,6 @@ 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.
@@ -56,6 +56,8 @@ function decimal(score: Score | undefined, name: string): number | null {
return typeof value === 'number' ? value : null;
}
const round1 = (value: number) => Math.round(value * 10) / 10;
// A proportion's bounds travel as proportions; the rows hold percentages, like `valor`.
const percent = (value: number | null) => value === null ? null : round1(value * 100);
// A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's,
// keeps every category ungrouped.
@@ -146,7 +148,7 @@ function proporcion(populations: Population[] | undefined, score: Score | undefi
return {
suprimido: 0, numerador, denominador,
valor: typeof score?.value === 'number' ? round1(score.value * 100) : null,
ic_bajo: decimal(score, 'ic-bajo'), ic_alto: decimal(score, 'ic-alto'),
ic_bajo: percent(decimal(score, 'ic-bajo')), ic_alto: percent(decimal(score, 'ic-alto')),
n_sin_evento: numerador !== null && denominador !== null ? denominador - numerador : null,
n_excluido: count(populations, 'denominator-exclusion') ?? 0,
};
@@ -251,10 +253,10 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
: { ...declaradas,
...Object.fromEntries([...extras].map(([categoria, etiqueta]) => [categoria, { etiqueta, color: null, grupo: null }])) };
const totales: Record<string, unknown>[] = [];
// CaMa's page names the primary group of a proportion `total`; the WebApi names it `principal`.
// The page names the primary group of a proportion `total`; the WebApi names it `principal`.
const nombre = (codigo: string | undefined) => {
const grupo = codigo ?? 'TOTAL';
return cama && kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
return kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
};
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
const id = nombre(code(g.code));
@@ -0,0 +1,42 @@
// Covers CaCu's history tab: its fixed list of indicators, in order, with a pending panel for each one the catalog
// does not publish. Catalogs are synthetic, shaped like /cacu/indicadores; the tab stays inactive, so nothing is
// requested.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { MatDialog } from '@angular/material/dialog';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { HISTORICO_CACU, IndicadoresHistorico } from './indicadores-historico';
import { Indicador } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub {}
const item = (id: string, contrato: string): Indicador => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
describe('Histórico de CaCu', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresHistorico>>, http: HttpTestingController;
function montar(catalog: Indicador[]) {
TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: vi.fn() } }] });
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('catalog', catalog);
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', false);
fixture.detectChanges();
}
afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); });
const paneles = () => [...(fixture.nativeElement as HTMLElement).querySelectorAll('article.panel')] as HTMLElement[];
it('lista los seis indicadores en orden y deja pendientes los que el catálogo no publica', () => {
// Pins down: the tab shows the fixed list, not the whole catalog, so the risk bands stay out and an indicator
// the catalog lacks keeps its place as a pending panel. Fails if the list changes, or the catalog's order or
// extra measures leak into the tab.
montar([item('cacu_riesgo_banda', 'C2'), item('ind1', 'C1'), item('cacu_eu13', 'C1')]);
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(e => e.titulo));
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
expect(pendientes).toEqual(['Distribución de resultados citológicos', 'Tasa de confirmación histopatológica',
'Días de la toma de la citología a su resultado', 'Tiempo de tamizaje a diagnóstico']);
http.expectNone(() => true);
});
});
@@ -1,4 +1,4 @@
// Covers the history tab in the page: it exists for CaMa only, sits between Resumen and Seguimiento, and its
// Covers the history tab in the page: it exists for TEA, CaMa and CaCu, sits between Resumen and Seguimiento, and its
// panel loads nothing until it is opened. Catalogs are synthetic, shaped like /<dominio>/indicadores.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
@@ -38,12 +38,13 @@ describe('Pestaña Histórico', () => {
expect(root().querySelector('#panel-analisis')).toBeNull();
http.expectNone(request => request.url.startsWith('/cama/analisis'));
});
it('cacu no tiene la pestaña Histórico', () => {
// Fails if the history tab of TEA or CaMa leaks into CaCu.
it('cacu tiene Histórico pero no Análisis epidemiológico', () => {
// Fails if CaCu loses its history tab or gains CaMa's analysis tab.
abrir('cama', []);
abrir('cacu', [item('cacu_x', 'C2')]);
expect(tabs()).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).toBeNull();
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).not.toBeNull();
expect(root().querySelector('#panel-analisis')).toBeNull();
});
it('tea tiene Histórico pero no Análisis epidemiológico', () => {
abrir('cama', []);
@@ -36,6 +36,18 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
];
// CaCu's history, built like CaMa's: a fixed list, with the same pending panel for what the catalog does not publish.
// The risk bands are left out until their batches are readable.
export const HISTORICO_CACU: readonly { id: string; titulo: string }[] = [
{ id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos' },
{ id: 'ind1', titulo: 'Pacientes con citología anómala' },
{ id: 'cacu_eu13', titulo: 'Tasa de detección histopatológica' },
{ id: 'cacu_confirmacion_citologia', titulo: 'Tasa de confirmación histopatológica' },
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado' },
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico' },
];
const HISTORICO_FIJO: Readonly<Partial<Record<string, readonly { id: string; titulo: string }[]>>> = { cama: HISTORICO_CAMA, cacu: HISTORICO_CACU };
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] {
const pasos = TIEMPOS.map(id => paneles.find(p => p.item.id === id));
@@ -171,9 +183,11 @@ export class IndicadoresHistorico {
readonly catalog = input.required<readonly Indicador[]>();
readonly tema = input.required<Tema>();
readonly active = input(false);
// The indicators the tab draws: CaMa's fixed list, where the catalog publishes it; the whole catalog elsewhere.
private readonly publicados = computed(() => this.dominio() === 'cama'
? HISTORICO_CAMA.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)) : this.catalog());
// The indicators the tab draws: a domain's fixed list, where the catalog publishes it; the whole catalog elsewhere.
private readonly publicados = computed(() => {
const fijo = HISTORICO_FIJO[this.dominio()];
return fijo ? fijo.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)) : this.catalog();
});
// Only the granularities some indicator publishes; monthly first when there is one.
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.publicados().some(item => item.tipos_periodo.includes(tipo))));
readonly elegido = signal<TipoPeriodo | undefined>(undefined);
@@ -241,9 +255,10 @@ export class IndicadoresHistorico {
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
}
};
if (this.dominio() === 'cama') {
const fijo = HISTORICO_FIJO[this.dominio()];
if (fijo) {
if (!this.publicados().length) return [];
return HISTORICO_CAMA.map((entrada): Panel => {
return fijo.map((entrada): Panel => {
const item = this.catalog().find(i => i.id === entrada.id);
return item ? { ...panelDe(item), item: { ...entrada, contrato: item.contrato } } : { item: entrada, estado: 'pendiente' };
});
@@ -115,6 +115,7 @@
<span>Incluye el periodo y los indicadores seleccionados. Elige «Guardar como PDF» en el cuadro de impresión.</span>
</div>
}
@if (screeningRouteAvailable) { <app-indicador-screening-route [dominio]="dominio" [tema]="tema" /> }
<div class="catalog-grid">
@if (histopatologiaPendiente) { <app-indicador-histopatologia-pendiente /> }
@for (item of searchResults().items; track cardIdentity(item)) {
@@ -20,6 +20,8 @@ import { esSocioConteos } from './indicadores-conteos-pareados';
import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, KpiCardSlot, camaKpiCards } from './indicadores-kpi';
import { TeaResumenPeriodo } from './tea-resumen-periodo';
import { IndicadorKpiPanel } from './indicador-kpi-panel';
import { IndicadorScreeningRoute } from './indicador-screening-route';
import { ROUTE_IDS, ROUTE_ONLY_IDS } from './screening-route';
import { IndicadorKpiCard } from './indicador-kpi-card';
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
import { identityElementId, indicatorIdentity } from './indicadores-identities';
@@ -52,13 +54,13 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, IndicadorScreeningRoute],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; }
get conHistorico() { return this.dominio === 'tea' || this.dominio === 'cama'; }
get conHistorico() { return this.dominio === 'tea' || this.dominio === 'cama' || this.dominio === 'cacu'; }
get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; }
readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
@@ -334,6 +336,10 @@ export class IndicadoresPage {
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
}
// CaCu's screening route chart, once the catalog publishes every measure it reads.
get screeningRouteAvailable() {
return this.dominio === 'cacu' && ROUTE_IDS.every(id => this.catalog().some(item => item.id === id));
}
// How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them.
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
@@ -363,8 +369,10 @@ export class IndicadoresPage {
// Stable presentation order. Pins no longer reorder the summary.
readonly catalogOrder = computed(() => {
const catalog = this.catalog();
// The route chart draws its own measures: they get no card of their own once it is there.
const route = this.screeningRouteAvailable ? ROUTE_ONLY_IDS : [];
return this.dominio === 'cacu'
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7' && !route.includes(item.id))]
: this.dominio === 'cama' ? this.cardsDeCama(catalog)
: catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
});
@@ -163,7 +163,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar();
expect(e.page.seleccionSeguimiento()).toBeUndefined();
expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(
dominio === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
expect(e.root.querySelector('#panel-analisis')).toBeNull();
}
e.page.changeDominio('cama'); e.harness.detectChanges();
@@ -11,7 +11,7 @@ describe('Regresión del mapeo FHIR en CaCu y TEA', () => {
it('las 16 medidas se mapean igual que antes: ids, catálogo, ficha y filas de datos', () => {
// Pins down: ids, catalog entries, sheets and data rows of CaCu's seven and TEA's nine measures, over real reports,
// equal the recorded ones; an error counts as a result too. Fails if a change meant for CaMa (its id table, its
// group name, its undeclared categories, its sheet code) reaches another domain. If the new result is the right one,
// undeclared categories, its sheet code) reaches another domain. If the new result is the right one,
// regenerate the recorded mapping and say why in the change.
const actual = mapeoDeCacuYTea({ indicadorId, indicadorDeMeasure, metadatosDeMeasure, datosDeReportes });
expect(Object.keys(actual)).toEqual(Object.keys(esperado));
@@ -0,0 +1,57 @@
// What this module covers: the screening route chart in CaCu's page: it appears only when the catalog publishes the seven
// measures it reads, and then those measures that nothing else draws lose their own cards. Catalogs are synthetic,
// shaped like /cacu/indicadores.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadoresPage } from './indicadores-page';
import { IndicadoresMemory } from './indicadores-memory';
import { Dominio } from './indicadores.models';
import { ROUTE_IDS, ROUTE_ONLY_IDS } from './screening-route';
const item = (id: string, contrato = 'C3r') => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] });
describe('Ruta del tamizaje: página de CaCu', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
function abrir(domain: Dominio, catalog: unknown[]) {
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges();
http.match(() => true);
}
const ruta = () => fixture.nativeElement.querySelector('app-indicador-screening-route');
const tarjetas = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(d => (d.componentInstance as IndicadorCatalogCard).indicador.id);
it('con las siete medidas publicadas aparece la gráfica y sus medidas exclusivas no tienen tarjeta', () => {
// Pins down: the chart replaces the cards of the five measures only it draws, while the cytology's and the diagnosis'
// keep theirs. Fails if the chart stops appearing, or a measure it draws also shows as a card.
abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.map(id => item(id))]);
expect(ruta()).not.toBeNull();
const ids = tarjetas();
for (const id of ROUTE_ONLY_IDS) expect(ids).not.toContain(id);
expect(ids).toContain('cacu_eu_tiempo_reporte');
expect(ids).toContain('cacu_eu7');
});
it('si el catálogo no publica alguna de las siete, no hay gráfica y las medidas conservan sus tarjetas', () => {
// Fails if the chart appears with a measure missing, or the cards of the others disappear anyway.
abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.filter(id => id !== 'cacu_dias_toma_biopsia').map(id => item(id))]);
expect(ruta()).toBeNull();
const ids = tarjetas();
for (const id of ROUTE_ONLY_IDS.filter(id => id !== 'cacu_dias_toma_biopsia')) expect(ids).toContain(id);
});
it('las otras áreas no la tienen', () => {
// Fails if the CaCu chart leaks into TEA or CaMa.
abrir('cama', [item('cama_eu38a'), ...ROUTE_IDS.map(id => item(id))]);
expect(ruta()).toBeNull();
});
});
@@ -39,9 +39,9 @@ describe('Secciones compartidas por dominio', () => {
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
const root = harness.routeNativeElement!;
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
// TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos; CaCu keeps its three.
// TEA, CaMa and CaCu have Histórico; CaMa labels Seguimiento as Análisis de Riesgos.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']
: domain === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
: ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'];
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
@@ -39,7 +39,7 @@ const finito = (v: unknown): v is number => typeof v === 'number' && Number.isFi
const conteo = (v: unknown): v is number => finito(v) && Number.isSafeInteger(v) && v >= 0;
const fail = (message: string): never => { throw new TiemposIncompatibles(message); };
function caja(fila: Record<string, unknown> | undefined): Caja {
export function caja(fila: Record<string, unknown> | undefined): Caja {
if (!fila) return { estado: 'No disponible' };
if (fila['suprimido'] === 1) return { estado: 'Suprimido' };
const { n, q1, mediana, q3 } = fila;
@@ -0,0 +1,124 @@
// What this module covers: the screening route chart's model and figure. The model turns the seven C3r payloads of the
// route (days from the sample and days from the previous event, per event) into one row per event for a period, and
// chains the steps one after another; the figure draws them as horizontal bars of days.
// Fixtures: `payload`, synthetic C3r /datos shaped like the WebApi's, with the values of the chart's mockup: a
// cytology result at 7.9 days, a colposcopy at 35.7, a biopsy result at 52.1 and a diagnosis after it at 64.9.
import { IndicadorDatos } from './indicadores.models';
import { C2_PALETTE } from './indicadores-c2-palette';
import { drawnRows, ROUTE_IDS, routeCellText, routeFigure, routeHasData, routeModel, RouteIncompatible } from './screening-route';
type Box = [number, number, number, number];
const row = (periodo: string, [n, q1, mediana, q3]: Box, extra: Record<string, unknown> = {}) =>
({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido: 0, unidad: 'dias', ...extra });
const payload = (id: string, filas: Record<string, unknown>[], periodos = ['2025-S1', '2025-S2']): IndicadorDatos =>
({ id, contrato: 'C3r', tipo_periodo: 'semestre', periodos, filas, version: '1' });
const S2: Record<string, Box> = {
cacu_eu_tiempo_reporte: [4855, 4.9, 7.9, 12.2],
cacu_dias_toma_colposcopia: [864, 22.2, 35.7, 55.4],
cacu_dias_resultado_colposcopia: [864, 17, 27.8, 44],
cacu_dias_toma_biopsia: [454, 32.4, 52.1, 80.8],
cacu_dias_colposcopia_biopsia: [454, 10, 16.4, 26],
cacu_dias_toma_diagnostico: [4999, 11.4, 18.4, 28.5],
cacu_dias_biopsia_diagnostico: [454, 8, 12.8, 20],
};
function all(): Record<string, IndicadorDatos> {
return Object.fromEntries(ROUTE_IDS.map(id => [id, payload(id, [row('2025-S1', [10, 1, 2, 3]), row('2025-S2', S2[id])])]));
}
const figure = (view: 'cumulative' | 'steps', data = all(), period?: string) => routeFigure(routeModel(data, 'semestre', period), view, 'claro');
describe('Ruta del tamizaje: modelo', () => {
it('una fila por evento del periodo más reciente, con los pasos encadenados uno tras otro', () => {
// Pins down: the newest period is the default and each step starts where the previous one ends (7.9 + 27.8 = 35.7,
// + 16.4 = 52.1, + 12.8 = 64.9). Fails if the chain restarts at zero or follows another order.
const m = routeModel(all(), 'semestre');
expect(m.periods).toEqual(['2025-S2', '2025-S1']);
expect(m.period).toBe('2025-S2');
expect(m.rows.map(r => r.step.id)).toEqual(['cytology', 'colposcopy', 'biopsy', 'diagnosis']);
expect(m.rows.map(r => [r.start, r.end!.toFixed(1)])).toEqual([[0, '7.9'], [7.9, '35.7'], [35.7, '52.1'], [52.1, '64.9']]);
expect(m.rows[1].fromSample).toEqual({ estado: 'Publicado', n: 864, q1: 22.2, mediana: 35.7, q3: 55.4 });
});
it('un periodo pedido y publicado se usa; uno que no existe cae al más reciente', () => {
// Fails if a period nobody published is shown empty instead of falling back.
expect(routeModel(all(), 'semestre', '2025-S1').period).toBe('2025-S1');
expect(routeModel(all(), 'semestre', '2024-S1').period).toBe('2025-S2');
});
it('un paso suprimido o sin datos no se dibuja y la cadena sigue desde el último publicado', () => {
// Pins down: nothing is drawn as zero and the next step starts at the last published end. Fails if a suppressed box
// becomes a bar or leaves a gap in the chain.
const d = all();
d['cacu_dias_colposcopia_biopsia'] = payload('cacu_dias_colposcopia_biopsia', [row('2025-S2', [454, 10, 16.4, 26], { suprimido: 1 })]);
const m = routeModel(d, 'semestre');
expect(m.rows[2]).toMatchObject({ start: null, end: null });
expect(m.rows[3].start!.toFixed(1)).toBe('35.7');
expect(drawnRows(m, 'steps').map(r => r.step.id)).toEqual(['cytology', 'colposcopy', 'diagnosis']);
d['cacu_dias_toma_biopsia'] = payload('cacu_dias_toma_biopsia', []);
expect(drawnRows(routeModel(d, 'semestre'), 'cumulative').map(r => r.step.id)).toEqual(['cytology', 'colposcopy', 'diagnosis']);
});
it('rechaza datos de otro indicador, contrato, tipo de periodo o unidad, y dos totales por periodo', () => {
// Fails if a payload that doesn't belong to the route is drawn as if it did.
const con = (id: string, cambio: Partial<IndicadorDatos>) => ({ ...all(), [id]: { ...all()[id], ...cambio } });
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { id: 'otro' }), 'semestre')).toThrow(RouteIncompatible);
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { contrato: 'C1' }), 'semestre')).toThrow(RouteIncompatible);
expect(() => routeModel(all(), 'mes')).toThrow(RouteIncompatible);
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { filas: [row('2025-S2', S2['cacu_eu_tiempo_reporte'], { unidad: 'horas' })] }), 'semestre')).toThrow(RouteIncompatible);
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { filas: [row('2025-S2', [1, 1, 1, 1]), row('2025-S2', [2, 2, 2, 2])] }), 'semestre')).toThrow(RouteIncompatible);
const sinUno = all(); delete sinUno['cacu_dias_toma_biopsia'];
expect(() => routeModel(sinUno, 'semestre')).toThrow(RouteIncompatible);
});
it('sin periodos publicados no hay nada que dibujar', () => {
// Fails if an empty catalog throws or draws an empty bar.
const vacio = Object.fromEntries(ROUTE_IDS.map(id => [id, payload(id, [], [])]));
const m = routeModel(vacio, 'semestre');
expect(m.period).toBeUndefined();
expect(routeHasData(m)).toBe(false);
expect(routeFigure(m, 'cumulative', 'claro')).toEqual({ data: [], layout: {} });
});
it('la celda de la tabla dice el estado si no hay caja publicada', () => {
expect(routeCellText({ estado: 'Suprimido' })).toBe('Suprimido');
expect(routeCellText(routeModel(all(), 'semestre').rows[0].fromSample)).toBe('n = 4,855, Q1 4.9, mediana 7.9, Q3 12.2 días');
});
});
describe('Ruta del tamizaje: figura', () => {
it('acumulado: barras horizontales hasta la mediana con el intervalo de Q1 a Q3 y el número de casos', () => {
// Pins down: orientation, bar lengths, the asymmetric interval, the case counts in the labels and the first
// event on top. Fails if the bars stop being horizontal or the interval stops being Q1 to Q3.
const f = figure('cumulative');
const trace = f.data[0] as Record<string, any>;
expect(trace['type']).toBe('bar');
expect(trace['orientation']).toBe('h');
expect(trace['x']).toEqual([7.9, 35.7, 52.1, 18.4]);
expect(trace['error_x'].array.map((v: number) => +v.toFixed(1))).toEqual([4.3, 19.7, 28.7, 10.1]);
expect(trace['error_x'].arrayminus.map((v: number) => +v.toFixed(1))).toEqual([3, 13.5, 19.7, 7]);
expect(trace['y'][0]).toBe('Resultado de citología<br>n = 4,855');
expect(trace['y']).toHaveLength(4);
expect((f.layout['yaxis'] as Record<string, unknown>)['autorange']).toBe('reversed');
expect(JSON.stringify(f.data)).not.toContain('null');
});
it('por pasos: cada barra flota desde donde termina la anterior y la más lenta lleva el color', () => {
// Pins down: `base` equals the chained starts, the length is the step's own median, the slowest step (colposcopy,
// 27.8 days) is the only one in colour. Fails if the steps stop floating or the emphasis moves.
const f = figure('steps');
const trace = f.data[0] as Record<string, any>;
expect(trace['base'].map((v: number) => +v.toFixed(1))).toEqual([0, 7.9, 35.7, 52.1]);
expect(trace['x']).toEqual([7.9, 27.8, 16.4, 12.8]);
expect(trace['text']).toEqual(['+7.9 d', '+27.8 d', '+16.4 d', '+12.8 d']);
expect(trace['marker'].color).toEqual([C2_PALETTE.states.noData, C2_PALETTE.series[0], C2_PALETTE.states.noData, C2_PALETTE.states.noData]);
expect(trace['y'][1]).toBe('Del resultado de citología a la colposcopía<br>n = 864');
expect(trace['hovertemplate']).toContain('Hasta el día');
});
it('un paso sin caja se omite de la figura sin dejar huecos', () => {
// Fails if an undrawn step keeps its label or leaves a null in the traces.
const d = all();
d['cacu_dias_toma_biopsia'] = payload('cacu_dias_toma_biopsia', [row('2025-S2', S2['cacu_dias_toma_biopsia'], { suprimido: 1 })]);
const trace = figure('cumulative', d).data[0] as Record<string, any>;
expect(trace['y']).toHaveLength(3);
expect(trace['x']).toEqual([7.9, 35.7, 18.4]);
});
it('el tema oscuro cambia fondo y texto, no los datos', () => {
const claro = figure('steps'), oscuro = routeFigure(routeModel(all(), 'semestre'), 'steps', 'oscuro');
expect(oscuro.layout['paper_bgcolor']).toBe('#081839');
expect(claro.layout['paper_bgcolor']).toBe('#FFFFFF');
expect(oscuro.data[0]['x']).toEqual(claro.data[0]['x']);
});
});
@@ -0,0 +1,130 @@
import { IndicadorDatos, PlotlyFigure, Tema, TipoPeriodo } from './indicadores.models';
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
import { Caja, caja } from './indicadores-tiempos-pareados';
/**
* The screening route as a chain of events timed from the sample: the cytology result, the colposcopy, the biopsy
* result and the diagnosis. Each event has two C3r measures: the days from the sample and the days from the previous
* event. The cytology's step is its own days from the sample.
*/
export interface RouteStep {
id: 'cytology' | 'colposcopy' | 'biopsy' | 'diagnosis';
label: string;
stepLabel: string;
sinceSample: string;
sinceStep: string;
}
export const ROUTE_STEPS: readonly RouteStep[] = [
{ id: 'cytology', label: 'Resultado de citología', stepLabel: 'Toma a resultado de citología',
sinceSample: 'cacu_eu_tiempo_reporte', sinceStep: 'cacu_eu_tiempo_reporte' },
{ id: 'colposcopy', label: 'Resultado de colposcopía', stepLabel: 'Del resultado de citología a la colposcopía',
sinceSample: 'cacu_dias_toma_colposcopia', sinceStep: 'cacu_dias_resultado_colposcopia' },
{ id: 'biopsy', label: 'Resultado de biopsia', stepLabel: 'De la colposcopía al resultado de biopsia',
sinceSample: 'cacu_dias_toma_biopsia', sinceStep: 'cacu_dias_colposcopia_biopsia' },
{ id: 'diagnosis', label: 'Diagnóstico', stepLabel: 'Del resultado de biopsia al diagnóstico',
sinceSample: 'cacu_dias_toma_diagnostico', sinceStep: 'cacu_dias_biopsia_diagnostico' },
];
/** Every measure the chart reads, once each. */
export const ROUTE_IDS: readonly string[] = [...new Set(ROUTE_STEPS.flatMap(s => [s.sinceSample, s.sinceStep]))];
/** The measures only this chart draws: the cytology's and the diagnosis' keep their own cards. */
export const ROUTE_ONLY_IDS: readonly string[] = ROUTE_IDS.filter(id => id !== 'cacu_eu_tiempo_reporte' && id !== 'cacu_dias_toma_diagnostico');
export type RouteView = 'cumulative' | 'steps';
export interface RouteRow {
step: RouteStep;
fromSample: Caja;
fromPrevious: Caja;
/** Where the step starts and ends on the days axis, when chained one after another; null without a published box. */
start: number | null;
end: number | null;
}
export interface RouteModel { period: string | undefined; periods: string[]; rows: RouteRow[]; }
export class RouteIncompatible extends Error {}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const fail = (message: string): never => { throw new RouteIncompatible(message); };
const NOT_AVAILABLE: Caja = { estado: 'No disponible' };
/** The seven C3r /datos payloads -> one row per event for a period, newest period first when none is requested. */
export function routeModel(data: Record<string, IndicadorDatos>, tipo: TipoPeriodo, requested?: string): RouteModel {
const boxes: Record<string, Record<string, Caja>> = {};
for (const id of ROUTE_IDS) {
const d = data[id];
if (!d || d.id !== id || d.contrato !== 'C3r' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|| new Set(d.periodos).size !== d.periodos.length) {
fail('Los datos de tiempos no corresponden a los indicadores de la ruta del tamizaje.');
}
boxes[id] = {};
for (const row of d.filas) {
if (!record(row) || typeof row['periodo'] !== 'string' || !d.periodos.includes(row['periodo'])) fail('Fila C3r fuera de los periodos publicados.');
if (row['grupo'] !== 'TOTAL' || row['estrato'] != null) continue;
if (row['unidad'] !== undefined && row['unidad'] !== 'dias') fail('Unidad de tiempo distinta de días.');
const period = row['periodo'] as string;
if (boxes[id][period]) fail('Más de una fila total por periodo.');
boxes[id][period] = caja(row);
}
}
const periods = [...new Set(ROUTE_IDS.flatMap(id => data[id].periodos))].sort().reverse();
const period = requested && periods.includes(requested) ? requested : periods[0];
let cursor = 0;
const rows = ROUTE_STEPS.map((step): RouteRow => {
const fromSample = period ? boxes[step.sinceSample][period] ?? NOT_AVAILABLE : NOT_AVAILABLE;
const fromPrevious = period ? boxes[step.sinceStep][period] ?? NOT_AVAILABLE : NOT_AVAILABLE;
if (fromPrevious.estado !== 'Publicado') return { step, fromSample, fromPrevious, start: null, end: null };
const start = cursor;
cursor += fromPrevious.mediana!;
return { step, fromSample, fromPrevious, start, end: cursor };
});
return { period, periods, rows };
}
/** The rows with a published box for the view. */
export function drawnRows(model: RouteModel, view: RouteView): RouteRow[] {
return model.rows.filter(row => (view === 'cumulative' ? row.fromSample : row.fromPrevious).estado === 'Publicado');
}
export const routeHasData = (model: RouteModel) => drawnRows(model, 'cumulative').length > 0 || drawnRows(model, 'steps').length > 0;
const days = (v: number) => v.toLocaleString('es-MX', { maximumFractionDigits: 1 });
const count = (v: number) => v.toLocaleString('es-MX');
/**
* Horizontal bars of days. Cumulative: from the sample to each event, with the Q1 to Q3 range as the interval. Steps:
* each step floats from where the previous one ends, and the slowest is the one in colour.
*/
export function routeFigure(model: RouteModel, view: RouteView, tema: Tema): PlotlyFigure {
const t = c2Theme(tema);
const rows = drawnRows(model, view);
if (!rows.length) return { data: [], layout: {} };
const base = { autosize: true, height: 360, showlegend: false, paper_bgcolor: t.background, plot_bgcolor: t.background, font: { color: t.text },
margin: { t: 24, l: 150, r: 32, b: 56 } };
const axes = {
xaxis: { title: { text: 'Días' }, rangemode: 'tozero', gridcolor: t.grid, zeroline: false, fixedrange: true },
yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true },
};
if (view === 'cumulative') {
const boxes = rows.map(row => row.fromSample);
return { data: [{
type: 'bar', orientation: 'h', y: rows.map((row, i) => `${row.step.label}<br>n = ${count(boxes[i].n!)}`), x: boxes.map(b => b.mediana),
marker: { color: C2_PALETTE.series[0] },
error_x: { type: 'data', symmetric: false, color: t.text, thickness: 1.5, width: 6,
array: boxes.map(b => b.q3! - b.mediana!), arrayminus: boxes.map(b => b.mediana! - b.q1!) },
customdata: boxes.map(b => [count(b.n!), days(b.q1!), days(b.mediana!), days(b.q3!)]),
hovertemplate: '%{y}<br>Mediana: %{customdata[2]} días<br>Q1 a Q3: %{customdata[1]} a %{customdata[3]} días<extra></extra>',
}], layout: { ...base, ...axes }, config: { displayModeBar: false } };
}
const slowest = rows.reduce((best, row, i) => (row.fromPrevious.mediana! > rows[best].fromPrevious.mediana! ? i : best), 0);
const boxes = rows.map(row => row.fromPrevious);
return { data: [{
type: 'bar', orientation: 'h', y: rows.map((row, i) => `${row.step.stepLabel}<br>n = ${count(boxes[i].n!)}`), x: boxes.map(b => b.mediana),
base: rows.map(row => row.start),
marker: { color: rows.map((_, i) => (i === slowest ? C2_PALETTE.series[0] : C2_PALETTE.states.noData)) },
text: boxes.map(b => `+${days(b.mediana!)} d`), textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' }, cliponaxis: false,
customdata: rows.map((row, i) => [count(boxes[i].n!), days(boxes[i].q1!), days(boxes[i].mediana!), days(boxes[i].q3!), days(row.end!)]),
hovertemplate: '%{y}<br>Tramo: %{customdata[2]} días (Q1 a Q3: %{customdata[1]} a %{customdata[3]})<br>Hasta el día %{customdata[4]}<extra></extra>',
}], layout: { ...base, ...axes }, config: { displayModeBar: false } };
}
export function routeCellText(box: Caja): string {
return box.estado !== 'Publicado' ? box.estado : `n = ${count(box.n!)}, Q1 ${days(box.q1!)}, mediana ${days(box.mediana!)}, Q3 ${days(box.q3!)} días`;
}
@@ -59,16 +59,16 @@
</section>
@if (d.eeg; as e) {
<div class="alteraciones-zona" [class.abierta]="abierto(e)">
<div class="alteraciones-zona" [class.abierta]="mapaActual(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 o dónde queda el paciente en la norma por edad.</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.</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 : abierto(e) && mapaElegido === m.codigo"
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : mapaActual(e)?.codigo === 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,24 +88,8 @@
</ul>
</section>
@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) {
@if (mapaActual(e); as mapa) {
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Mapa de zonas afectadas">
<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>
@@ -118,54 +102,9 @@
<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 &lt; 0.05). Versión del modelo: {{ rel.version }}.</p>
}
</section>
}
</div>
}
@@ -73,24 +73,3 @@ 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,12 +4,9 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { PlotlyFigure } from './indicadores.models';
import {
CLASIFICACIONES_ADOS2, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaPacienteDetalle,
TeaRelacionAdos2, TeaRelacionModelo, TeaSeguimientoService, TeaAdos2,
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' };
@@ -48,36 +45,6 @@ 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],
@@ -91,7 +58,7 @@ export class TeaPacienteResumen implements OnInit {
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
readonly detalle = signal<TeaPacienteDetalle | undefined>(undefined);
figura?: PlotlyFigure;
mapaElegido?: string;
private 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() {
@@ -101,29 +68,13 @@ 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); }
// 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);
// 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());
}
verVista(vista: 'zonas' | 'norma') { this.vista = vista; }
readonly clasificacion = CLASIFICACIONES_ADOS2;
readonly nivelCss = NIVEL_CSS;
readonly calidad = CALIDAD;
@@ -133,12 +84,10 @@ 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 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; }
// 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;
this.detalle.set(d); this.status.set('ready');
},
error: () => this.status.set('error'),
@@ -157,24 +106,4 @@ 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, extensions, isSimulated, Quantity, referenceId, Resource, resources } from './fhir';
import { Bundle, code, codeIn, Concept, display, extension, 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,
TeaCurvaReferencia, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaRelacionAdos2,
TeaRelacionModelo, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService,
CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg,
TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, 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,7 +26,6 @@ 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';
@@ -112,18 +111,6 @@ 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 {
@@ -136,7 +123,6 @@ 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 ?? '',
@@ -144,7 +130,6 @@ 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 } : {}),
};
}
@@ -167,7 +152,6 @@ 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>`.
@@ -182,7 +166,6 @@ 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,
@@ -190,34 +173,6 @@ 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';
@@ -333,14 +288,12 @@ 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,17 +56,10 @@ 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[];
@@ -74,20 +67,7 @@ export interface TeaEeg {
mapas: TeaEegMapa[];
ejes_mapa: { x: number[]; y: number[]; electrodos: { nombre: string; x: number; y: number }[] };
}
// 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;
}
export interface TeaPacienteDetalle { simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | 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',
@@ -161,24 +141,13 @@ 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) || !validCurva(a['curva_referencia'])) return false;
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text)) 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);
@@ -188,9 +157,7 @@ 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'
@@ -205,21 +172,9 @@ 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'])
|| !validRelacion(v['relacion_ados2']))
if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg']))
throw new Error('Resumen del paciente inválido');
return v as unknown as TeaPacienteDetalle;
}
@@ -172,41 +172,6 @@ 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;
@@ -377,29 +342,4 @@ 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();
});
});