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.
This commit is contained in:
2026-11-22 00:02:42 -06:00
parent e5aa205662
commit 284db98b23
11 changed files with 585 additions and 3 deletions
@@ -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');
}
}
@@ -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',
@@ -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,7 +54,7 @@ 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',
})
@@ -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'));
});
@@ -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,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`;
}