{{ m.conBiopsia === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin mujeres con biopsia en el periodo.' }}
El anillo interior muestra grupos y el exterior categorías Bethesda. «Sin dato» se informa fuera de la dona.
-
Las barras usan el total con resultado válido de cada escenario, excluyendo «Sin dato». Al seleccionar un grupo o categoría se conserva ese denominador.
-
El escenario clínico corresponde al estatus de seguimiento al inicio del periodo, calculado con la historia previa.
-
Selecciona un grupo para expandirlo y una categoría para resaltarla. Repite el clic para liberar la selección. El centro o el botón Volver regresa de categoría a grupo y después a TOTAL. También puedes usar Tab y Enter o Espacio en la leyenda.
-
Los nulos y celdas suprimidas no son ceros. Si el denominador es desconocido, el escenario no muestra una barra porcentual.
- @if (metadata; as info) {
- @if (info.descripcion) {
}
- }
- Metadatos publicados de las figuras originales
-
Estas descripciones corresponden a las figuras publicadas originales. En esta vista coordinada, «Sin dato» queda fuera de la dona y las barras son porcentajes por escenario.
{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado válido para la dona.' }}
}
+
+ } @else {
{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado disponible para la dona.' }}
}
{{ sinDatoNote }}
-
{{ selectionLabel }} por escenario clínico · {{ m.periodo }}
+
{{ selectionLabel }} por escenario clínico, {{ m.periodo }}
Porcentaje del total válido de cada escenario; excluye «Sin dato».
@if (m.escenarios.length && barsFigure) {
-
+
}
}
@for (note of m.notas; track $index) {
{{ note }}
}
- Valores publicados y celdas suprimidas
+ Valores publicados
Ten en cuenta estas limitaciones al consultar las gráficas.
-
-
Un valor nulo significa que no hay un valor disponible; un cero es un valor observado. Los datos suprimidos tampoco representan un cero.
-
{{ periodInterpretation }}
-
Los periodos se presentan sin consolidar datos de distintos periodos, grupos o estratos.
-
Los intervalos de confianza, cuando están disponibles, describen incertidumbre y no garantizan certeza poblacional; su amplitud puede verse afectada por un tamaño de muestra pequeño.
-
-
Uso para investigación; la información no constituye aprobación clínica ni establece metas institucionales. Las notas de cada gráfica incluyen detalles adicionales para interpretar los datos mostrados.
-
diff --git a/src/app/features/indicadores/indicadores-definitions.ts b/src/app/features/indicadores/indicadores-definitions.ts
index 011cae5..78f09de 100644
--- a/src/app/features/indicadores/indicadores-definitions.ts
+++ b/src/app/features/indicadores/indicadores-definitions.ts
@@ -2,7 +2,7 @@ import { Component, Input, output } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { Dominio, Indicador, TipoPeriodo } from './indicadores.models';
import { figureDisplayName } from './indicadores-figure-labels';
-import { contractInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
+import { PERIOD_INTERPRETATION } from './indicadores-methodology';
import { IndicadorMetadata } from './indicador-metadata';
@Component({
@@ -19,20 +19,9 @@ export class IndicadoresDefinitions {
@Input() loading = false;
@Input() error = '';
readonly retry = output();
- readonly domainNames: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
+ readonly domainNames: Record = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'CaMa' };
readonly periodNames: Record = { semestre: 'Semestral', mes: 'Mensual' };
readonly figureDisplayName = figureDisplayName;
readonly periodInterpretation = PERIOD_INTERPRETATION;
get periodTypes() { return [...new Set(this.catalog.flatMap(item => item.tipos_periodo))]; }
- interpretation(item: Indicador) {
- if (!item.contrato) return [];
- const lines = contractInterpretation(item.contrato, this.dominio);
- // Catalog metadata does not describe the traces. Keep the shared C2 guidance
- // independent of bars/sectors; the actual figure retains its full explanation.
- return lines.filter(line =>
- !line.includes('Los valores nulos o suprimidos') &&
- !line.includes('Los puntos suprimidos') &&
- !line.includes('No hay una explicación específica disponible'),
- ).slice(item.contrato === 'C2' ? 1 : 0);
- }
}
diff --git a/src/app/features/indicadores/indicadores-donut-periods.spec.ts b/src/app/features/indicadores/indicadores-donut-periods.spec.ts
index e9f3cc0..80c6a00 100644
--- a/src/app/features/indicadores/indicadores-donut-periods.spec.ts
+++ b/src/app/features/indicadores/indicadores-donut-periods.spec.ts
@@ -113,7 +113,7 @@ describe('navegación multiperiodo en el panel común', () => {
expect(buttons()[0].disabled).toBe(true); expect(buttons()[1].disabled).toBe(false);
for (let i = 0; i < periods.length; i++) {
expect(panel().activeDonutPeriod).toBe(periods[i]);
- expect(fixture.nativeElement.querySelector('.donut-periods [role="status"]').textContent).toContain(`${i + 1} / 3`);
+ expect(fixture.nativeElement.querySelector('.donut-periods [role="status"]').textContent).toContain(`${i + 1} de 3`);
expect(card().chartFigure?.data).toHaveLength(1);
expect(panel().result().figure?.data.every(t => String(t['name']).startsWith(periods[i]))).toBe(true);
if (i < 2) { buttons()[1].click(); fixture.detectChanges(); }
diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts
index 49b17da..4ed77e2 100644
--- a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts
+++ b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts
@@ -1,6 +1,7 @@
import fixture from './fixtures/eu7-c2-ejemplos.json';
import { IndicadorDatos } from './indicadores.models';
import { barras, clic, dona, modelo, porcentaje, periodosCompatibles, Seleccion } from './indicadores-eu7-escenario';
+import { percentNumber } from './indicadores-format';
function eu7Datos() {
return structuredClone({ general: fixture.general as IndicadorDatos, escenarios: fixture.estatus_seguimiento as IndicadorDatos });
@@ -41,10 +42,13 @@ describe('EU7 modelo de presentación del entregable', () => {
expect(m.escenarios.map((s, i) => selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0).toFixed(1)))
.toEqual(['5.0', '24.3', '21.7', '7.8']);
const category = barras(m, { categoria: 'LIEAG' }, 'claro');
- expect(category.data).toHaveLength(1);
- expect(category.data[0]['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!));
+ // Same traces in every selection (animation identity); unselected ones are zero-width.
+ expect(category.data.map(t => t['uid'])).toEqual(f.data.map(t => t['uid']));
+ const lieag = category.data.find(t => t['uid'] === 'LIEAG')!;
+ expect(lieag['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!));
+ expect(category.data.filter(t => t !== lieag).every(t => (t['x'] as number[]).every(v => v === 0) && t['hoverinfo'] === 'skip')).toBe(true);
expect((category.layout['annotations'] as { text: string }[]).map(a => a.text))
- .toEqual(m.escenarios.map(s => `${(100 * s.celdas['LIEAG'].n! / s.den!).toFixed(1)} % (${s.celdas['LIEAG'].n}/${s.den})`));
+ .toEqual(m.escenarios.map(s => `${percentNumber(100 * s.celdas['LIEAG'].n! / s.den!)} % (${s.celdas['LIEAG'].n}/${s.den})`));
expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]);
});
it.each(['estrato', 'categorias', 'periodos', 'orden', 'duplicado', 'version', 'filtros', 'total', 'diferencia'])('rechaza incompatibilidad de %s', kind => {
@@ -73,7 +77,10 @@ describe('EU7 modelo de presentación del entregable', () => {
else if (kind === 'total suprimido') Object.assign((data.escenarios['totales_estrato'] as any[])[0], { n: 123456, suprimido: 1 });
else Object.assign(row, { n: kind === 'nulo' ? null : 123456, suprimido: kind === 'nulo' ? 0 : 1 });
const m = model(), f = barras(m, { categoria: 'LIEAG' }, 'claro');
- expect(m.escenarios[0].den).toBeNull(); expect(f.data[0]['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]);
+ expect(m.escenarios[0].den).toBeNull(); expect(f.data.find(t => t['uid'] === 'LIEAG')!['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]);
+ expect(f.data.every(t => (t['x'] as unknown[])[0] === null)).toBe(true);
+ expect(f.data.filter(t => t['uid'] !== 'LIEAG').every(t =>
+ t['hoverinfo'] === 'skip' && (t['customdata'] as unknown[]).length === 0)).toBe(true);
expect(JSON.stringify(f)).not.toContain('123456');
expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull();
});
@@ -94,6 +101,7 @@ describe('EU7 modelo de presentación del entregable', () => {
(data.escenarios['totales_estrato'] as any[]).forEach(t => t.n = 0);
const m = model(); expect(m.total).toBe(0); expect(dona(m, {}, 'claro').data).toEqual([]);
expect(barras(m, {}, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
+ expect(barras(m, { categoria: 'LIEAG' }, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
expect(barras(m, {}, 'claro').layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: 'Sin pacientes con resultado' })]));
});
it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => {
@@ -101,4 +109,20 @@ describe('EU7 modelo de presentación del entregable', () => {
const m = model(); expect(m.vacio).toBe(true); expect(m.total).toBe(0); expect(m.escenarios).toEqual([]);
expect(m.celdas['NORMAL'].n).toBeNull();
});
+ it('selección jerárquica y Volver conservan UID, orden, denominadores y datos fuente', () => {
+ const original = structuredClone(data), m = model(), snapshot = structuredClone(m);
+ const ids = m.categorias.map(c => c.id);
+ for (const selection of [{}, { grupo: 'ANORMAL' }, { grupo: 'ANORMAL', categoria: 'LIEAG' }, { categoria: 'LIEAG' }, {}]) {
+ const f = barras(m, selection, 'claro');
+ expect(f.data.map(t => t['uid'])).toEqual(ids);
+ expect(new Set(f.data.map(t => t['uid'])).size).toBe(ids.length);
+ f.data.forEach((t, i) => {
+ if (t['hoverinfo'] === 'skip') {
+ expect(t['customdata']).toEqual([]); expect(t['text']).toEqual(m.escenarios.map(() => ''));
+ } else expect(t['x']).toEqual(m.escenarios.map(s => porcentaje(s, ids[i])));
+ });
+ dona(m, selection, 'claro');
+ }
+ expect(m).toEqual(snapshot); expect(data).toEqual(original);
+ });
});
diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.ts b/src/app/features/indicadores/indicadores-eu7-escenario.ts
index 3e8c505..aca81aa 100644
--- a/src/app/features/indicadores/indicadores-eu7-escenario.ts
+++ b/src/app/features/indicadores/indicadores-eu7-escenario.ts
@@ -1,5 +1,6 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
+import { percentNumber, shareText } from './indicadores-format';
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
// This boundary is intentionally specific to EU7. Unknown cells never become zero.
@@ -189,12 +190,12 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
const centro = sel.categoria ? m.celdas[sel.categoria].n! : sel.grupo ? nGrupo(m, sel.grupo)! : m.total;
const rotulos = (values: number[], labels: string[], pct: boolean) => {
const total = values.reduce((s, n) => s + n, 0);
- return values.map((v, i) => !total || v / total < .05 ? '' : escapar(labels[i]) + (pct ? ` ${(100 * v / total).toFixed(0)} %` : ''));
+ return values.map((v, i) => !total || v / total < .05 ? '' : escapar(labels[i]) + (pct ? ` ${shareText(v, total)}` : ''));
};
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text',
insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' };
- const hover = { hovertemplate: '%{label} %{customdata[0]} pacientes · %{customdata[1]} % del total con resultado' };
- const custom = (values: number[]) => values.map(n => [miles(n), (100 * n / m.total!).toFixed(1)]);
+ const hover = { hovertemplate: '%{label} %{customdata[0]} pacientes, %{customdata[1]} % del total con resultado' };
+ const custom = (values: number[]) => values.map(n => [miles(n), percentNumber(100 * n / m.total!)]);
return { data: [
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
text: [`${miles(centro)} ${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text },
@@ -216,13 +217,20 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id);
const y = m.escenarios.map(s => escapar(s.etiqueta));
const sumas = m.escenarios.map(s => s.den === null || s.den === 0 ? null : visibles.reduce((n, c) => n + porcentaje(s, c)!, 0));
- return { data: m.categorias.filter(c => visibles.includes(c.id)).map(c => {
- const x = m.escenarios.map(s => porcentaje(s, c.id));
- return { type: 'bar', orientation: 'h', name: escapar(c.etiqueta), y, x,
- marker: { color: c.color, line: { color: p.background, width: 1 } },
- text: x.map(v => v !== null && v >= 6 ? `${v.toFixed(0)} %` : ''), textposition: 'inside', insidetextanchor: 'middle',
- customdata: m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]),
- hovertemplate: `%{y} ${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})` };
+ // Every category keeps its trace (same uid and count) so a selection animates;
+ // an unselected category is a zero-width bar without text or hover, never data.
+ return { data: m.categorias.map(c => {
+ const visible = visibles.includes(c.id);
+ const x = m.escenarios.map(s => {
+ const value = porcentaje(s, c.id);
+ return value === null ? null : visible ? value : 0;
+ });
+ return { type: 'bar', orientation: 'h', uid: c.id, name: escapar(c.etiqueta), y, x,
+ marker: { color: c.color, line: { color: p.background, width: visible ? 1 : 0 } },
+ text: x.map(v => visible && v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle',
+ customdata: visible ? m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]) : [],
+ ...(visible ? { hovertemplate: `%{y} ${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})` }
+ : { hoverinfo: 'skip' }) };
}), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65),
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false,
@@ -232,7 +240,7 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
tickvals: sel.grupo || sel.categoria ? undefined : [0, 20, 40, 60, 80, 100] },
annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false,
font: { size: 12, color: p.text }, text: s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado'
- : sel.grupo || sel.categoria ? `${sumas[i]!.toFixed(1)} % (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})`
+ : sel.grupo || sel.categoria ? `${percentNumber(sumas[i]!)} % (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})`
: miles(s.den) })),
}, config: { displayModeBar: false } };
}
diff --git a/src/app/features/indicadores/indicadores-format.spec.ts b/src/app/features/indicadores/indicadores-format.spec.ts
new file mode 100644
index 0000000..c904b7a
--- /dev/null
+++ b/src/app/features/indicadores/indicadores-format.spec.ts
@@ -0,0 +1,24 @@
+import { percentNumber, percentText, roundPercent, sharePercent, shareText } from './indicadores-format';
+
+describe('regla de redondeo de porcentajes', () => {
+ it('una décima, medio hacia arriba, calculada con enteros', () => {
+ expect(sharePercent(2, 303)).toBe(0.7);
+ expect(sharePercent(1, 8)).toBe(12.5);
+ expect(sharePercent(1, 3)).toBe(33.3);
+ expect(sharePercent(2, 3)).toBe(66.7);
+ expect(shareText(0, 9)).toBe('0.0 %');
+ expect(shareText(5, 5)).toBe('100.0 %');
+ });
+ it('entre 0 y 0.1, la primera cifra significativa', () => {
+ expect(shareText(1, 2000)).toBe('0.05 %');
+ expect(shareText(1, 1600)).toBe('0.06 %');
+ expect(percentText(0.0432)).toBe('0.04 %');
+ });
+ it('un porcentaje publicado redondea igual, sin sorpresas de coma flotante', () => {
+ expect(roundPercent(0.6600660066)).toBe(0.7);
+ expect(roundPercent(12.25)).toBe(12.3);
+ expect(roundPercent(1.005 * 10)).toBe(10.1);
+ expect(percentNumber(100)).toBe('100.0');
+ expect(percentText(null)).toBe('No disponible');
+ });
+});
diff --git a/src/app/features/indicadores/indicadores-format.ts b/src/app/features/indicadores/indicadores-format.ts
new file mode 100644
index 0000000..dbd30ef
--- /dev/null
+++ b/src/app/features/indicadores/indicadores-format.ts
@@ -0,0 +1,33 @@
+// One rounding rule for every percentage shown: one decimal, half up; between 0 and 0.1
+// the first significant digit (0.04 %, not 0.0 %). Integer counts round exactly, without
+// binary floating-point surprises (1.005 → 1.0 with toFixed).
+
+/** The percentage of `k` in `n`, rounded by the rule, computed from integers. */
+export function sharePercent(k: number, n: number): number {
+ if (k > 0 && 1000 * k < n) return Number((100 * k / n).toPrecision(1));
+ return Math.floor((2000 * k + n) / (2 * n)) / 10;
+}
+
+/** A published percentage (0 to 100), rounded by the rule. */
+export function roundPercent(value: number): number {
+ if (value > 0 && value < 0.1) return Number(value.toPrecision(1));
+ // Snap to 9 decimals first so 12.25 published as 12.2499999999 still rounds up.
+ return Math.floor(Math.round(value * 1e9) / 1e8 + 0.5) / 10;
+}
+
+/** Text of a rounded percentage: «12.3», «0.04», «100.0». */
+export function percentNumber(value: number): string {
+ const rounded = roundPercent(value);
+ return rounded > 0 && rounded < 0.1 ? String(rounded) : rounded.toFixed(1);
+}
+
+/** «12.3 %» from a published percentage, or the fallback when there is none. */
+export function percentText(value: number | null | undefined, fallback = 'No disponible'): string {
+ return typeof value === 'number' && Number.isFinite(value) ? `${percentNumber(value)} %` : fallback;
+}
+
+/** «12.3 %» from a count over its denominator. */
+export function shareText(k: number, n: number): string {
+ const value = sharePercent(k, n);
+ return `${value > 0 && value < 0.1 ? String(value) : value.toFixed(1)} %`;
+}
diff --git a/src/app/features/indicadores/indicadores-global-filters.spec.ts b/src/app/features/indicadores/indicadores-global-filters.spec.ts
index 9750138..ac69008 100644
--- a/src/app/features/indicadores/indicadores-global-filters.spec.ts
+++ b/src/app/features/indicadores/indicadores-global-filters.spec.ts
@@ -114,7 +114,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
expect(panel.result().status).toBe('incompatible'); expect(panel.result().figure).toBeUndefined();
http.expectNone(r => r.url.includes('/a/figuras/')); const r = request('b');
expect(r.request.params.get('periodos')).toBe('2025-01'); expect(r.request.params.has('tipoPeriodo')).toBe(false);
- expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('granularidad mes');
+ expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('intervalo de tiempo mes');
expect((host as HTMLElement).parentElement!.hidden).toBe(true);
r.flush({ data: [], layout: {} });
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
diff --git a/src/app/features/indicadores/indicadores-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts
index 308507f..8671c65 100644
--- a/src/app/features/indicadores/indicadores-initial-integration.spec.ts
+++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts
@@ -10,7 +10,7 @@ import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigureCard } from './indicador-figure-card';
import { IndicadorPeriodFilters } from './indicador-period-filters';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
-import { KPI_BY_DOMAIN } from './indicadores-kpi';
+import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
import { pending } from './indicadores-memory';
import { Indicador } from './indicadores.models';
@@ -22,7 +22,8 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
const definitions = KPI_BY_DOMAIN[domain];
const otherDomain = domain === 'cacu' ? 'cama' : 'cacu';
const items = [...definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f', 'g'] })),
- { id: 'other', titulo: 'Otra figura', contrato: 'C1', tipos_periodo: ['semestre'], figuras: ['f'] }];
+ // Two figures, so every domain keeps an ordinary card whose representation can change.
+ { id: 'other', titulo: 'Otra figura', contrato: 'C1', tipos_periodo: ['semestre'], figuras: ['f', 'g'] }];
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
@@ -45,11 +46,22 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
valor: 50, numerador: 5, denominador: 10, mediana: 2, q1: 1, q3: 3, unidad: 'dias' }] };
}
function request(period: string) { return http.expectOne(r => r.url.endsWith(`/${definitions[0].id}/datos`) && r.params.get('periodos') === period); }
- function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel); }
+ // Regression assertions below target the original KPI contracts. The added lab
+ // consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
+ // Satisfy its independent request with an explicit empty response, never diagnosis data.
+ function originalRequests() {
+ const requests = http.match(r => r.url.endsWith('/datos'));
+ for (const r of requests.filter(r => r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'))) {
+ const period = r.request.params.get('periodos')!;
+ r.flush({ id: CACU_RESULTADO_KPI.id, contrato: 'C3r', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [], filas: [] });
+ }
+ return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'));
+ }
+ function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
function flushPanels(period: string, expected = definitions.length - 1) {
- const requests = http.match(r => r.url.endsWith('/datos'));
+ const requests = originalRequests();
expect(requests).toHaveLength(expected);
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period);
const index = definitions.findIndex(d => r.request.url.endsWith(`/${d.id}/datos`)); r.flush(data(index, period)); });
@@ -108,13 +120,19 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
it('todas las figuras reciben el periodo compartido y mantienen carga diferida', () => {
choose(); http.expectNone(r => r.url.includes('/figuras/'));
cards().forEach(card => { expect(card.applied).toBe(page.filters!.applied); card.setVisible(true); });
- // EU7 now owns a coordinated C2 view. This temporal fixture publishes only
- // placeholder f/g figures, so that card must stop as incompatible, without GET.
- fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7).length); http.expectNone(() => true);
+ // EU7 and the CaCu paired times own coordinated views. This temporal fixture publishes
+ // only placeholder f/g figures, so EU7 stops as incompatible without GET; the paired times
+ // ask /datos for the same shared period, including the partner hidden from the catalog.
+ fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7 && !card.tiempos).length);
+ const tiempos = http.match(r => r.url.endsWith('/datos'));
+ // P0-C.1 cached the same lab payload; the paired figure reuses it.
+ expect(tiempos.some(r => r.request.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos')).toBe(false);
+ for (const r of tiempos) { expect(r.request.params.get('periodos')).toBe(periods[1]); r.flush('', { status: 404, statusText: 'Missing' }); }
+ http.expectNone(() => true);
});
it('KPI secundarios sin datos no retroceden a otro periodo', () => {
request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges();
- const requests = http.match(r => r.url.endsWith('/datos')); expect(requests).toHaveLength(definitions.length - 1);
+ const requests = originalRequests(); expect(requests).toHaveLength(definitions.length - 1);
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(periods[0]); r.flush('', { status: 404, statusText: 'Missing' }); });
fixture.detectChanges(); expect(panels().slice(1).every(p => p.result().state === 'Sin datos del periodo')).toBe(true); http.expectNone(() => true);
});
@@ -128,7 +146,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
it('tema, ancho y representación no reinician el periodo ni la búsqueda', () => {
choose(); const applied = page.filters!.applied;
page.changeTema('oscuro'); window.dispatchEvent(new Event('resize')); fixture.detectChanges(); http.expectNone(() => true);
- const card = cards().find(card => !card.isEu7)!;
+ const card = cards().find(card => !card.isEu7 && !card.tiempos)!;
card.setVisible(true); fixture.detectChanges(); flushFigures(periods[1], 1);
card.selectFigure('g'); fixture.detectChanges(); flushFigures(periods[1], 1);
expect(card.selectedFigure).toBe('g'); http.expectNone(() => true);
@@ -185,7 +203,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
expect(page.kpiIndicator(definitions[0].id)).toBeUndefined();
expect(panels()).toHaveLength(0); expect(cards()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos'));
editor().select([periods[0]]); page.applyFilters(); fixture.detectChanges();
- http.match(r => r.url.endsWith('/datos')).forEach(r => {
+ originalRequests().forEach(r => {
const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos'));
expect(index).toBeGreaterThan(0); r.flush(data(index, periods[0]));
}); fixture.detectChanges();
@@ -209,7 +227,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
value.filas[0].grupo = definitions[index].contrato === 'C1' && target !== 'tea' ? 'total' : 'TOTAL'; return value;
};
http.expectOne(r => r.url.endsWith('/' + definitions[0].id + '/datos')).flush(payload(0)); fixture.detectChanges();
- http.match(r => r.url.endsWith('/datos')).forEach(r => {
+ originalRequests().forEach(r => {
const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); r.flush(payload(index));
}); fixture.detectChanges();
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [period] });
diff --git a/src/app/features/indicadores/indicadores-initial-period.spec.ts b/src/app/features/indicadores/indicadores-initial-period.spec.ts
index d27810c..3284c83 100644
--- a/src/app/features/indicadores/indicadores-initial-period.spec.ts
+++ b/src/app/features/indicadores/indicadores-initial-period.spec.ts
@@ -74,7 +74,7 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma
const run = start(); http.expectOne(`/${domain}/indicadores/${anchor.id}/periodos`).flush('', { status: 404, statusText: 'Missing' });
expect(run.failed()).toBe(true); expect(run.completed()).toBe(false); http.expectNone(() => true);
});
- it.each(['semestre', 'mes'] as const)('busca únicamente la granularidad activa %s, sin mezclar tipos ni usar un mes más reciente', tipo => {
+ it.each(['semestre', 'mes'] as const)('busca únicamente el intervalo de tiempo activo %s, sin mezclar tipos ni usar un mes más reciente', tipo => {
const run = start(tipo); inventory(['2026-12', '2025-10', '2026-S1', '2025-S2']);
const expected = tipo === 'mes' ? '2026-12' : '2026-S1'; request(expected).flush(data(expected));
expect(run.selected()).toEqual({ periodo: expected, tipo }); http.expectNone(() => true);
diff --git a/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts b/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts
index a7675bc..93285fd 100644
--- a/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts
+++ b/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts
@@ -140,6 +140,6 @@ describe('KPI de CaMa con respuestas reales de WebApi', () => {
});
it('tiempo de tamizaje a diagnóstico: la mediana del C3r', () => {
expect(result(2).state).toBe('Disponible');
- expect(result(2).info).toContain('El horizonte de 180 días es provisional.');
+ expect(result(2).info).toMatch(/^[\d.,]+ mastografías; Q1 a Q3: [\d.]+ a [\d.]+ días\.$/);
});
});
diff --git a/src/app/features/indicadores/indicadores-kpi-resultado.spec.ts b/src/app/features/indicadores/indicadores-kpi-resultado.spec.ts
new file mode 100644
index 0000000..c41e96c
--- /dev/null
+++ b/src/app/features/indicadores/indicadores-kpi-resultado.spec.ts
@@ -0,0 +1,138 @@
+import { TestBed } from '@angular/core/testing';
+import { Component, input } from '@angular/core';
+import { provideHttpClient } from '@angular/common/http';
+import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
+import { provideRouter, ActivatedRoute } from '@angular/router';
+import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
+import { IndicadorKpiPanel } from './indicador-kpi-panel';
+import { GlobalApplied } from './indicadores-memory';
+import { IndicadorDatos } from './indicadores.models';
+import { IndicadoresSnapshots } from './indicadores-snapshots';
+import { IndicadoresPage } from './indicadores-page';
+import { PARES_TIEMPOS } from './indicadores-tiempos-pareados';
+import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
+import { PlotlyChart } from '../../shared/plotly/plotly-chart';
+
+@Component({ selector: 'app-plotly-chart', template: '' })
+class ChartStub { figure = input(); label = input(); showNotes = input(); }
+
+const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 1 };
+// Synthetic contract examples only; no value in these tests is a deployed clinical result.
+const payload = (period = '2025-S1', extra: Record = {}): IndicadorDatos => ({
+ id: CACU_RESULTADO_KPI.id, contrato: 'C3r', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period],
+ filas: [{ periodo: period, grupo: 'TOTAL', estrato: null, n: 20, q1: 7, mediana: 12, q3: 20, unidad: 'dias', suprimido: 0, ...extra }],
+});
+
+describe('P0-C.1: contrato de toma a resultado', () => {
+ const read = (data: IndicadorDatos) => kpiResult(data, CACU_RESULTADO_KPI, 'cacu', applied);
+ it('usa el ID del laboratorio del par, nunca la mediana de diagnóstico', () => {
+ expect(CACU_RESULTADO_KPI.id).toBe(PARES_TIEMPOS.find(p => p.dominio === 'cacu')!.reporte);
+ expect(read(payload())).toMatchObject({ state: 'Disponible', value: 12 });
+ expect(CACU_RESULTADO_KPI.unit).toBe('días (mediana)');
+ const diagnosis = { ...payload('2025-S1', { mediana: 52, q3: 90 }), id: KPI_BY_DOMAIN.cacu[1].id };
+ expect(read(diagnosis).state).toBe('Error de contrato');
+ expect(kpiResult(diagnosis, KPI_BY_DOMAIN.cacu[1], 'cacu', applied).value).toBe(52);
+ });
+ it.each([{ mediana: null }, { n: 0 }, { n: null }, { q1: null }, { unidad: 'meses' }, { q1: 15 }])('no inventa valor ante %j', extra => {
+ expect(read(payload('2025-S1', extra))).toEqual({ state: 'Sin valor disponible' });
+ });
+ it('cero publicado es válido, supresión nunca expone cuantiles ni conteo', () => {
+ expect(read(payload('2025-S1', { mediana: 0, q1: 0 })).value).toBe(0);
+ expect(read(payload('2025-S1', { suprimido: 1 }))).toEqual({ state: 'Dato oculto por tamaño' });
+ expect(read(payload('2025-S1', { suprimido: null })).value).toBeUndefined();
+ });
+ it('distingue vacío, periodo equivocado y selección no consolidable sin mezclar grupos o tipos', () => {
+ expect(read({ ...payload(), filas: [], periodos: [] }).state).toBe('Sin filas utilizables');
+ expect(read(payload('2025-S2')).state).toBe('Selección no consolidable');
+ expect(read(payload('2025-01')).state).toBe('Error de contrato');
+ expect(read({ ...payload(), filas: [...payload().filas, ...payload().filas] }).state).toBe('Selección no consolidable');
+ expect(read(payload('2025-S1', { estrato: 'grupo_edad' })).state).toBe('Selección no consolidable');
+ expect(kpiResult(payload(), CACU_RESULTADO_KPI, 'cacu', { ...applied, selection: { mode: 'todos' } }).state).toBe('Selección no consolidable');
+ });
+});
+
+describe('P0-C.1: transporte y periodo aplicado', () => {
+ let f: ReturnType>, http: HttpTestingController;
+ beforeEach(() => {
+ TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
+ TestBed.overrideComponent(IndicadorTiemposPareados, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
+ http = TestBed.inject(HttpTestingController);
+ f = TestBed.createComponent(IndicadorKpiPanel);
+ f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('definition', CACU_RESULTADO_KPI);
+ f.componentRef.setInput('applied', applied); f.detectChanges();
+ });
+ afterEach(() => { f.destroy(); http.verify(); });
+ const request = () => http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos');
+ it('reutiliza la consulta idéntica en vuelo y completada de la gráfica mediante snapshots', () => {
+ let received: IndicadorDatos | undefined;
+ const snapshots = TestBed.inject(IndicadoresSnapshots);
+ snapshots.datos('cacu', CACU_RESULTADO_KPI.id, 'semestre', ['2025-S1']).subscribe(data => received = data);
+ const r = request(); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(payload());
+ expect(received?.filas[0]['mediana']).toBe(12); expect(f.componentInstance.result().value).toBe(12);
+ f.componentRef.setInput('applied', { ...applied, revision: 2 }); f.detectChanges();
+ expect(f.componentInstance.result().value).toBe(12); http.expectNone(() => true);
+ });
+ it.each(['empty', '404', 'suppressed', 'error'] as const)('%s no dispara búsqueda de otro periodo', scenario => {
+ const r = request();
+ if (scenario === '404' || scenario === 'error') r.flush('private', { status: scenario === '404' ? 404 : 503, statusText: 'Unavailable' });
+ else r.flush(scenario === 'empty' ? { ...payload(), filas: [], periodos: [] } : payload('2025-S1', { suprimido: 1 }));
+ f.detectChanges();
+ expect(f.componentInstance.result().state).toBe({ empty: 'Sin filas utilizables', '404': 'Sin datos del periodo', suppressed: 'Dato oculto por tamaño', error: 'Error de consulta' }[scenario]);
+ expect(f.componentInstance.result().value).toBeUndefined(); expect(f.componentInstance.temporalReference).toBe('2025-S1');
+ expect(f.nativeElement.textContent).not.toContain('private'); http.expectNone(() => true);
+ });
+ it('la gráfica pareada comparte la petición en vuelo y conserva ambas series originales', () => {
+ const chart = TestBed.createComponent(IndicadorTiemposPareados);
+ try {
+ chart.componentRef.setInput('dominio', 'cacu'); chart.componentRef.setInput('tema', 'claro');
+ chart.componentRef.setInput('par', PARES_TIEMPOS.find(p => p.dominio === 'cacu')!);
+ chart.componentRef.setInput('indicador', { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', tipos_periodo: ['semestre'], figuras: ['fig_c3r_caja'] });
+ chart.componentRef.setInput('applied', applied); chart.detectChanges();
+ const lab = request(); expect(lab.request.params.get('periodos')).toBe('2025-S1');
+ lab.flush(payload());
+ http.expectOne(r => r.url.includes('/cacu_dias_toma_diagnostico/datos')).flush({ ...payload('2025-S1', { mediana: 52, q3: 90 }), id: 'cacu_dias_toma_diagnostico' });
+ chart.detectChanges();
+ expect(chart.componentInstance.figure!.data.map(series => series['name'])).toEqual(['Días de toma a resultado (laboratorio)', 'Días de toma a diagnóstico']);
+ expect(chart.componentInstance.figure!.data.map(series => series['median'])).toEqual([[12], [52]]);
+ expect(f.componentInstance.result().value).toBe(12); http.expectNone(() => true);
+ } finally { chart.destroy(); }
+ });
+ it('Todos y varios periodos no consultan; un mes consulta únicamente ese mes', () => {
+ const old = request();
+ for (const selection of [{ mode: 'todos' as const }, { mode: 'explicit' as const, periodos: ['2025-S1', '2025-S2'] as [string, ...string[]] }]) {
+ f.componentRef.setInput('applied', { ...applied, selection, revision: 2 }); f.detectChanges();
+ expect(f.componentInstance.result().state).toBe('Selección no consolidable'); http.expectNone(() => true);
+ }
+ expect(old.cancelled).toBe(true);
+ f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-02'] }, revision: 3 }); f.detectChanges();
+ const r = request(); expect(r.request.params.get('periodos')).toBe('2025-02'); r.flush(payload('2025-02'));
+ expect(f.componentInstance.result().value).toBe(12);
+ });
+});
+
+describe('P0-C.1: cinco tarjetas de oportunidad', () => {
+ it('conserva los originales, agrega laboratorio y deja ambos tratamientos inertes', () => {
+ vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
+ TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([]),
+ { provide: ActivatedRoute, useValue: { snapshot: { data: { dominio: 'cacu' } } } }] });
+ const f = TestBed.createComponent(IndicadoresPage), http = TestBed.inject(HttpTestingController);
+ try {
+ // The established lab partner is absent from this visible catalog, as in the paired figure.
+ http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
+ http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ tipo: 'semestre', periodo: '2025-S1' }] }));
+ http.expectOne(r => r.url.includes('/cacu_eu7/datos')).flush({ id: 'cacu_eu7', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: { A: {} }, filas: [{ periodo: '2025-S1', grupo: 'TOTAL', estrato: null, categoria: 'A', n: 20, suprimido: 0 }] });
+ f.detectChanges();
+ http.expectOne(r => r.url.includes('/cacu_eu_tiempo_reporte/datos')).flush(payload());
+ http.expectOne(r => r.url.includes('/cacu_dias_toma_diagnostico/datos')).flush({ ...payload('2025-S1', { mediana: 52, q3: 90 }), id: 'cacu_dias_toma_diagnostico' });
+ f.detectChanges();
+ const cards = [...f.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
+ expect(cards.map(c => c.querySelector('h3')!.textContent)).toEqual(['Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento']);
+ expect(cards.map(c => c.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['20', '12', '52', undefined, undefined]);
+ expect(cards.map(c => c.querySelector('.value span')?.textContent)).toEqual(['pacientes', 'días (mediana)', 'días (mediana)', undefined, undefined]);
+ for (const card of cards.slice(3)) {
+ expect(card.querySelectorAll('p')).toHaveLength(1); expect(card.querySelector('p')!.textContent).toBe('Indicador no disponible');
+ }
+ http.expectNone(() => true);
+ } finally { f.destroy(); vi.unstubAllGlobals(); http.verify(); }
+ });
+});
diff --git a/src/app/features/indicadores/indicadores-kpi.spec.ts b/src/app/features/indicadores/indicadores-kpi.spec.ts
index 9db24f4..9b612f7 100644
--- a/src/app/features/indicadores/indicadores-kpi.spec.ts
+++ b/src/app/features/indicadores/indicadores-kpi.spec.ts
@@ -21,10 +21,11 @@ describe.each(['tea', 'cacu', 'cama'] as const)('KPI %s', domain => {
expect(result.value).toBe('33.4'); expect(result.info).toContain('2 de 6');
expect(run(1, [{ ...total, grupo: c1Group, valor: 0, numerador: 0, denominador: 6 }]).value).toBe('0.0');
});
- it('C3r conserva mediana cero y Q1/Q3, referencia provisional solo en CaCu y CaMa', () => {
+ it('C3r conserva mediana cero y Q1/Q3, sin reglas provisionales en la tarjeta', () => {
const result = run(2, [{ ...total, mediana: 0, n: 5, q1: 0, q3: 7, unidad: 'dias' }]);
- expect(result.value).toBe(0); expect(result.info).toContain('0 a 7 días');
- if (domain === 'tea') expect(result.info).not.toContain('provisional'); else expect(result.info).toContain('provisional');
+ expect(result.value).toBe(0);
+ expect(result.info).toContain(domain === 'cacu' ? 'primer cuartil: 0 días; tercer cuartil: 7 días' : '0 a 7 días');
+ expect(result.info).not.toContain('provisional');
});
it.each([0, 1, 2])('suprimido en %s oculta cualquier cifra', index => {
expect(run(index, [{ ...total, grupo: index === 1 ? c1Group : 'TOTAL', categoria: 'A', n: 5, valor: 100, mediana: 7, suprimido: 2 }])).toEqual({ state: 'Dato oculto por tamaño' });
diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts
index 12f08c4..9985a79 100644
--- a/src/app/features/indicadores/indicadores-kpi.ts
+++ b/src/app/features/indicadores/indicadores-kpi.ts
@@ -1,7 +1,12 @@
import { Dominio, IndicadorDatos } from './indicadores.models';
import { GlobalApplied } from './indicadores-memory';
+import { percentNumber } from './indicadores-format';
-export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; }
+export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; singleAppliedPeriod?: boolean; }
+// Same laboratory-result source used by PARES_TIEMPOS; diagnosis has its own ID.
+export const CACU_RESULTADO_KPI: KpiDefinition = {
+ id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
+};
// Provisional (oct 2026): titles are copied by hand from the `title` of each indicator's TOML
// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories
// (patients), not the distribution. If a TOML title changes, change it here too, until the
@@ -31,8 +36,8 @@ const C1_INFO: Record strin
};
const C3R_INFO: Record string> = {
tea: (n, q1, q3) => `${n} pacientes; Q1 a Q3: ${q1} a ${q3} días.`,
- cacu: (n, q1, q3) => `${n} citologías; Q1 a Q3: ${q1} a ${q3} días. El horizonte de 180 días es provisional.`,
- cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días. El horizonte de 180 días es provisional.`,
+ cacu: (n, q1, q3) => `${n} citologías; primer cuartil: ${q1} días; tercer cuartil: ${q3} días.`,
+ cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días.`,
};
export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; }
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
@@ -42,6 +47,7 @@ const unscoped = { state: 'Selección no consolidable', info: 'Elige un único p
// C2 definitions count each patient once per period, in disjoint categories of TOTAL.
// C1/C3r publish a single total row. Never combine totals, strata, or periods.
export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domain: Dominio, applied: GlobalApplied): KpiResult {
+ if (definition.singleAppliedPeriod && (applied.selection.mode !== 'explicit' || applied.selection.periodos.length !== 1)) return unscoped;
if (data.id !== definition.id || data.contrato !== definition.contrato || data.tipo_periodo !== applied.tipo) {
return { state: 'Error de contrato', info: 'Los datos recibidos no corresponden al indicador o periodo aplicado.' };
}
@@ -68,12 +74,12 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
if (!rows.every(row => count(row['n']))) return empty;
const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0);
if (!count(value)) return empty;
- return { state: 'Disponible', value, info: 'Conteo de pacientes únicos en el periodo.' };
+ return { state: 'Disponible', value, info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.' : 'Conteo de pacientes únicos en el periodo.' };
}
if (definition.contrato === 'C1') {
if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty;
- return { state: 'Disponible', value: row['valor'].toFixed(1), info: C1_INFO[domain](row['numerador'], row['denominador']) };
+ return { state: 'Disponible', value: percentNumber(row['valor']), info: C1_INFO[domain](row['numerador'], row['denominador']) };
}
- if (!finite(row['mediana']) || !count(row['n']) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty;
+ if (!finite(row['mediana']) || !count(row['n']) || (definition.id === CACU_RESULTADO_KPI.id && row['n'] === 0) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty;
return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) };
}
diff --git a/src/app/features/indicadores/indicadores-memory.spec.ts b/src/app/features/indicadores/indicadores-memory.spec.ts
index 8ef623b..12de7c8 100644
--- a/src/app/features/indicadores/indicadores-memory.spec.ts
+++ b/src/app/features/indicadores/indicadores-memory.spec.ts
@@ -68,7 +68,7 @@ describe('D.2 memoria global por dominio', () => {
it.each([{ types: [] }, { types: ['semestre'] }, { types: ['mes', 'semestre'] }] as { types: TipoPeriodo[] }[])('adapter explica incompatibilidad mensual Todos con %j', ({ types }) => {
expect(filterCompatibility({ tipo: 'mes', selection: { mode: 'todos' }, revision: 1 }, types).compatible).toBe(false);
});
- it('adapter no transforma ni recorta y requiere primera granularidad para Todos', () => {
+ it('adapter no transforma ni recorta y requiere el primer intervalo de tiempo para Todos', () => {
const applied: GlobalFilterState['applied'] = { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-01', '2025-02'] }, revision: 1 };
const snapshot = JSON.stringify(applied);
expect(filterCompatibility(applied, ['semestre', 'mes']).compatible).toBe(true);
diff --git a/src/app/features/indicadores/indicadores-memory.ts b/src/app/features/indicadores/indicadores-memory.ts
index 7c0c764..1a1ac43 100644
--- a/src/app/features/indicadores/indicadores-memory.ts
+++ b/src/app/features/indicadores/indicadores-memory.ts
@@ -46,11 +46,11 @@ export type Compatibility = { compatible: true } | { compatible: false; reason:
export function filterCompatibility(applied: GlobalApplied | undefined, types: readonly TipoPeriodo[]): Compatibility {
if (!types.length) return { compatible: false, reason: 'El catálogo no declara capacidades temporales suficientes para consultar.' };
if (!applied) return { compatible: false, reason: 'No hay un filtro general aplicado.' };
- if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite la granularidad ' + applied.tipo + ' del filtro general.' };
+ if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite el intervalo de tiempo ' + applied.tipo + ' del filtro general.' };
const mode = applied.selection.mode;
if (!validDraft(applied.selection, applied.tipo, [...types])) return { compatible: false, reason: mode === 'todos'
- ? 'Todos con reporte requiere semestre como primera granularidad publicada. Para meses elige periodos explícitos.'
- : 'Los periodos del filtro general no son válidos para esta granularidad.' };
+ ? 'Todos con reporte requiere semestre como primer intervalo de tiempo publicado. Para meses elige periodos explícitos.'
+ : 'Los periodos del filtro general no son válidos para este intervalo de tiempo.' };
return { compatible: true };
}
export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boolean {
diff --git a/src/app/features/indicadores/indicadores-methodology.ts b/src/app/features/indicadores/indicadores-methodology.ts
index 53b5f87..1d2fccf 100644
--- a/src/app/features/indicadores/indicadores-methodology.ts
+++ b/src/app/features/indicadores/indicadores-methodology.ts
@@ -1,7 +1,7 @@
import { Dominio, IndicadorMetadatos } from './indicadores.models';
-// Existing WebApp explanations, shared by figures and the definitions section.
-// These are editorial guidance, not additional metadata supplied by WebApi.
+// Editorial fallback for a figure whose metadata publishes no `como_leer`
+// (metadata not loaded yet, failed, or an older kit). Not WebApi metadata.
const CONTRACT_INTERPRETATIONS: Readonly> = {
C1: [
'El punto representa la proporción observada.',
@@ -17,14 +17,15 @@ const CONTRACT_INTERPRETATIONS: Readonly> = {
};
export const PERIOD_INTERPRETATION = 'Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.';
-export function figureMetadataInterpretation(metadata: IndicadorMetadatos | undefined, figureId: string): readonly string[] | undefined {
- const detail = metadata?.figuras_detalle?.find(item => item.figura === figureId);
- if (!detail) return undefined;
- const instructions = detail.como_leer ?? [];
- return instructions.some(line => line.trim().length > 0) ? instructions : undefined;
+// "Cómo leer" of a figure: the kit's `como_leer` when it publishes one, otherwise
+// the generic guidance of the figure's contract.
+export function figureInterpretation(metadata: IndicadorMetadatos | undefined, figureId: string,
+ contract: string | undefined, domain: Dominio, pie = false): readonly string[] {
+ const instructions = metadata?.figuras_detalle?.find(item => item.figura === figureId)?.como_leer ?? [];
+ return instructions.some(line => line.trim().length > 0) ? instructions : contractInterpretation(contract, domain, pie);
}
-export function contractInterpretation(contract: string | undefined, domain: Dominio, pie = false): readonly string[] {
+function contractInterpretation(contract: string | undefined, domain: Dominio, pie: boolean): readonly string[] {
if (contract === 'C2') return [
pie
? 'Los sectores muestran la composición porcentual de las categorías publicadas para cada periodo.'
diff --git a/src/app/features/indicadores/indicadores-navegacion-lateral.spec.ts b/src/app/features/indicadores/indicadores-navegacion-lateral.spec.ts
new file mode 100644
index 0000000..f531f6c
--- /dev/null
+++ b/src/app/features/indicadores/indicadores-navegacion-lateral.spec.ts
@@ -0,0 +1,432 @@
+import { TestBed } from '@angular/core/testing';
+import { provideRouter } from '@angular/router';
+import { provideHttpClient } from '@angular/common/http';
+import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
+import { By } from '@angular/platform-browser';
+import { IndicadoresPage } from './indicadores-page';
+import { Indicador } from './indicadores.models';
+import { identityElementId, indicatorIdentity } from './indicadores-identities';
+import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
+import fixtureData from './fixtures/cacu_seguimiento.json';
+
+const item = (id: string, titulo: string): Indicador => ({ id, titulo, contrato: 'C1', figuras: ['f-' + id], tipos_periodo: ['semestre'] });
+
+describe('UX-10 navegación lateral del catálogo gráfico', () => {
+ let fixture: ReturnType>;
+ let page: IndicadoresPage;
+ let http: HttpTestingController;
+
+ beforeEach(() => {
+ vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
+ TestBed.configureTestingModule({
+ imports: [IndicadoresPage],
+ providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider],
+ });
+ fixture = TestBed.createComponent(IndicadoresPage);
+ page = fixture.componentInstance;
+ http = TestBed.inject(HttpTestingController);
+ vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ page.closeGraphicNavigation(false, false);
+ fixture.detectChanges();
+ http.match(request => request.url.endsWith('/seguimiento')).forEach(request => request.flush(fixtureData));
+ http.match(request => request.url.endsWith('/metadatos')).forEach(request => request.flush({}));
+ fixture.destroy();
+ http.verify();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ });
+
+ async function load(items: Indicador[], domain: 'tea' | 'cacu' | 'cama' = 'tea') {
+ if (domain !== page.dominio) {
+ http.expectOne('/' + page.dominio + '/indicadores').flush([]);
+ fixture.detectChanges();
+ page.changeDominio(domain);
+ }
+ http.expectOne('/' + domain + '/indicadores').flush(items);
+ fixture.detectChanges();
+ await fixture.whenStable();
+ fixture.detectChanges();
+ }
+
+ function trigger() { return fixture.nativeElement.querySelector('.graphic-navigation-trigger') as HTMLButtonElement | null; }
+ function optionButtons() { return Array.from(document.querySelectorAll('#indicator-navigation-panel .panel-list button')); }
+ async function openPanel() {
+ const button = trigger()!;
+ button.focus();
+ button.click();
+ fixture.detectChanges();
+ await fixture.whenStable();
+ fixture.detectChanges();
+ return button;
+ }
+ function expectNoFigureRequests() { http.expectNone(request => request.url.includes('/figuras/') || request.url.endsWith('/datos')); }
+
+ it.each(['tea', 'cacu', 'cama'] as const)('aparece solo en Resumen para el dominio %s', async domain => {
+ await load([item('chart', 'Indicador gráfico')], domain);
+ expect(trigger()).not.toBeNull();
+ page.changeSection('seguimiento'); fixture.detectChanges();
+ expect(trigger()).toBeNull();
+ page.changeSection('datos'); fixture.detectChanges();
+ expect(trigger()).toBeNull();
+ page.changeSection('resumen'); fixture.detectChanges();
+ page.fichaPacienteAbierta.set(true); fixture.detectChanges();
+ expect(trigger()).toBeNull();
+ page.fichaPacienteAbierta.set(false); fixture.detectChanges();
+ expect(trigger()).not.toBeNull();
+ expectNoFigureRequests();
+ });
+
+ it('toma únicamente títulos y orden del catálogo visible, sin agregar KPI ni nombres alternos', async () => {
+ const items = [item('a', 'Tasa visible exacta'), item('b', 'Distribución por edad')];
+ await load(items, 'cacu');
+ expect(page.showGraphicNavigation).toBe(true);
+ await openPanel();
+ expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Tasa visible exacta', 'Distribución por edad']);
+ expect(optionButtons().map(button => button.getAttribute('aria-label'))).toEqual(['Tasa visible exacta', 'Distribución por edad']);
+ expect(optionButtons().some(button => button.textContent?.includes('Oportunidad') || button.textContent?.includes('destacado'))).toBe(false);
+ expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-panel').length).toBe(0);
+ expectNoFigureRequests();
+ });
+
+ it('presenta un popover compacto anclado al botón, sin backdrop ni bloqueo del scroll', async () => {
+ await load([item('a', 'Uno'), item('b', 'Título largo del indicador')]);
+ const button = trigger()!;
+ vi.spyOn(button, 'getBoundingClientRect').mockReturnValue(new DOMRect(8, 180, 48, 48));
+ const bodyOverflow = document.body.style.overflow;
+ await openPanel();
+ const panel = document.querySelector('.panel-shell')!;
+ expect(page.navigationPositions[0]).toEqual({ originX: 'start', overlayX: 'start', originY: 'center', overlayY: 'center' });
+ expect(panel.closest('.cdk-overlay-pane')).not.toBeNull();
+ expect(document.querySelector('.cdk-overlay-backdrop')).toBeNull();
+ expect(getComputedStyle(panel).maxHeight).toBe('min(58dvh, 32rem)');
+ expect(bodyOverflow).toBe(document.body.style.overflow);
+ expect(page.navigationScrollStrategy.constructor.name).toBe('RepositionScrollStrategy');
+ expectNoFigureRequests();
+ });
+
+ it('usa scroll interno en una lista extensa y se adapta al ancho disponible', async () => {
+ await load(Array.from({ length: 30 }, (_, index) => item('indicator-' + index, 'Indicador clínico ' + index)));
+ await openPanel();
+ const panel = document.querySelector('.panel-shell')!;
+ const list = panel.querySelector('.panel-list')!;
+ expect(optionButtons()).toHaveLength(30);
+ expect(getComputedStyle(panel).maxHeight).toBe('min(58dvh, 32rem)');
+ expect(getComputedStyle(list).overflowY).toBe('auto');
+ expect(getComputedStyle(panel.parentElement!).maxWidth).toBe('calc(100vw - 1rem)');
+ expectNoFigureRequests();
+ });
+
+ it('reubica el popover en viewports estrechos y conserva límites verticales', async () => {
+ await load([item('one', 'Indicador')]);
+ const previousWidth = window.innerWidth;
+ Object.defineProperty(window, 'innerWidth', { configurable: true, value: 320 });
+ try {
+ await openPanel();
+ const panel = document.querySelector('.panel-shell')!;
+ const host = panel.parentElement!;
+ expect(getComputedStyle(host).maxWidth).toBe('calc(100vw - 1rem)');
+ expect(page.navigationPositions).toEqual(expect.arrayContaining([
+ expect.objectContaining({ originX: 'end', overlayX: 'end' }),
+ expect.objectContaining({ originY: 'bottom', overlayY: 'bottom' }),
+ ]));
+ expect(panel.closest('.cdk-overlay-pane')).not.toBeNull();
+ } finally {
+ Object.defineProperty(window, 'innerWidth', { configurable: true, value: previousWidth });
+ }
+ });
+
+ it('sigue el orden priorizado por búsqueda y fijación mientras el panel está abierto', async () => {
+ await load([item('one', 'Alfa'), item('two', 'Beta'), item('three', 'Gamma')]);
+ page.togglePinned(page.catalog()[2]);
+ fixture.detectChanges();
+ await openPanel();
+ expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Gamma', 'Alfa', 'Beta']);
+ page.changeSearchQuery('beta');
+ fixture.detectChanges();
+ expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Beta', 'Gamma', 'Alfa']);
+ page.changeSearchQuery('sin coincidencias');
+ fixture.detectChanges();
+ expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Gamma', 'Alfa', 'Beta']);
+ page.searchQuery.set('');
+ page.catalog.set([item('updated', 'Versión actualizada'), item('two', 'Beta')]);
+ fixture.detectChanges();
+ expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Versión actualizada', 'Beta']);
+ expectNoFigureRequests();
+ });
+
+ it('mantiene keys únicas para títulos duplicados y navega a la tarjeta elegida', async () => {
+ const items = [item('duplicate-a', 'Resultado clínico'), item('duplicate-b', 'Resultado clínico')];
+ await load(items, 'cama');
+ const scroll = vi.fn();
+ const focus = vi.spyOn(HTMLElement.prototype, 'focus');
+ for (const card of fixture.nativeElement.querySelectorAll('app-indicador-catalog-card')) {
+ card.scrollIntoView = scroll;
+ }
+ await openPanel();
+ expect(optionButtons()).toHaveLength(2);
+ expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Resultado clínico', 'Resultado clínico']);
+ optionButtons()[1].click();
+ fixture.detectChanges();
+ await fixture.whenStable();
+ fixture.detectChanges();
+ const targetId = identityElementId(indicatorIdentity('cama', 'duplicate-b'));
+ expect(scroll).toHaveBeenCalledOnce();
+ expect(scroll.mock.instances[0]).toBe(fixture.nativeElement.querySelector('#' + targetId));
+ expect(focus).toHaveBeenCalled();
+ expect(document.activeElement).toBe(fixture.nativeElement.querySelector('#' + targetId + ' h2'));
+ expectNoFigureRequests();
+ });
+
+ it('abre con foco dentro, expone el estado expandido y cierra restaurando el foco con Escape', async () => {
+ await load([item('one', 'Indicador')]);
+ const button = await openPanel();
+ expect(button.getAttribute('aria-expanded')).toBe('true');
+ expect(document.querySelector('nav[aria-label="Navegar a indicadores clínicos"]')).not.toBeNull();
+ expect(document.activeElement).toBe(optionButtons()[0]);
+ expect(document.querySelector('.cdk-focus-trap-anchor')).toBeNull();
+ document.querySelector('.panel-shell')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true, cancelable: true }));
+ await fixture.whenStable();
+ fixture.detectChanges();
+ expect(page.navigationOpen()).toBe(false);
+ expect(button.getAttribute('aria-expanded')).toBe('false');
+ expect(document.activeElement).toBe(button);
+ expectNoFigureRequests();
+ });
+
+ it('cierra al pulsar fuera y mantiene el click externo disponible', async () => {
+ const bodyOverflow = document.body.style.overflow;
+ await load([item('one', 'Indicador')]);
+ await openPanel();
+ document.body.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
+ document.body.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
+ fixture.detectChanges();
+ expect(page.navigationOpen()).toBe(false);
+ expect(page.navigationClosing()).toBe(true);
+ expect(document.querySelector('app-indicadores-navegacion-panel')?.hasAttribute('inert')).toBe(true);
+ expect(document.querySelector('.cdk-overlay-pane.indicator-navigation-overlay:has(.panel-closing)')).not.toBeNull();
+ expect(document.body.style.overflow).toBe(bodyOverflow);
+ expectNoFigureRequests();
+ });
+
+ it('no conserva elementos al cambiar de dominio y elimina el encabezado y el botón X', async () => {
+ await load([item('one', 'TEA gráfico')]);
+ await openPanel();
+ expect(document.querySelector('#indicator-navigation-title')).toBeNull();
+ expect(document.querySelector('.panel-header')).toBeNull();
+ expect(document.querySelector('.panel-shell mat-icon')).toBeNull();
+ expect(document.querySelector('.panel-shell')?.querySelectorAll('button')).toHaveLength(1);
+ page.changeDominio('cacu');
+ http.expectOne('/cacu/indicadores').flush([item('new', 'CaCu clínico')]);
+ fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
+ expect(page.navigationOpen()).toBe(false);
+ expect(trigger()).not.toBeNull();
+ await openPanel();
+ expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['CaCu clínico']);
+ expect(optionButtons().some(button => button.textContent?.includes('TEA'))).toBe(false);
+ expectNoFigureRequests();
+ });
+
+ it('respeta movimiento reducido, enfoca la tarjeta y no solicita sus figuras desde el panel', async () => {
+ await load([item('lazy', 'Carga diferida')]);
+ const card = fixture.nativeElement.querySelector('app-indicador-catalog-card') as HTMLElement;
+ const scroll = vi.fn();
+ card.scrollIntoView = scroll;
+ vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })));
+ await openPanel();
+ optionButtons()[0].click();
+ await fixture.whenStable(); fixture.detectChanges();
+ expect(scroll).toHaveBeenCalledWith({ behavior: 'instant', block: 'start' });
+ expect(fixture.debugElement.query(By.css('app-indicador-catalog-card'))?.componentInstance?.visible).toBe(false);
+ expectNoFigureRequests();
+ });
+
+ function pointer(target: Element, type: 'pointerenter' | 'pointerleave' | 'pointermove', pointerType = 'mouse', moved = true) {
+ const event = new Event(type);
+ Object.defineProperty(event, 'pointerType', { value: pointerType });
+ target.dispatchEvent(event);
+ // A real entry caused by mouse movement also dispatches pointermove. Layout-only entries don't.
+ if (type === 'pointerenter' && moved) {
+ const move = new Event('pointermove');
+ Object.defineProperty(move, 'pointerType', { value: pointerType });
+ target.dispatchEvent(move);
+ }
+ fixture.detectChanges();
+ }
+ function hoverDevice(enabled = true) {
+ vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: enabled && query === '(hover: hover) and (pointer: fine)' })));
+ }
+
+ it('abre por hover sin mover el foco y conserva el origen CDK oculto y su caja', async () => {
+ await load([item('a', 'Indicador')]);
+ hoverDevice();
+ const button = trigger()!;
+ const origin = fixture.debugElement.query(By.css('[cdkOverlayOrigin]')).nativeElement;
+ const rect = new DOMRect(8, 180, 48, 48);
+ vi.spyOn(button, 'getBoundingClientRect').mockReturnValue(rect);
+ const initialFocus = document.activeElement;
+ pointer(button, 'pointerenter');
+ expect(page.navigationOpen()).toBe(true);
+ expect(document.activeElement).toBe(initialFocus);
+ expect(trigger()).toBe(origin);
+ expect(getComputedStyle(button).opacity).toBe('0');
+ expect(getComputedStyle(button).pointerEvents).toBe('none');
+ expect(getComputedStyle(button).display).not.toBe('none');
+ expect(button.getBoundingClientRect()).toBe(rect);
+ expect(button.tabIndex).toBe(-1);
+ expect(optionButtons()).toHaveLength(1);
+ expectNoFigureRequests();
+ });
+
+ it('permite cruzar del disparador a cualquier opción y cancela el cierre al reingresar', async () => {
+ await load([item('a', 'Uno'), item('b', 'Dos')]);
+ hoverDevice(); vi.useFakeTimers();
+ pointer(trigger()!, 'pointerenter');
+ pointer(trigger()!, 'pointerleave');
+ vi.advanceTimersByTime(200);
+ expect(page.navigationOpen()).toBe(true);
+ const panel = document.querySelector('app-indicadores-navegacion-panel')!;
+ pointer(panel, 'pointerenter');
+ vi.advanceTimersByTime(300);
+ expect(page.navigationOpen()).toBe(true);
+ pointer(panel, 'pointerleave');
+ vi.advanceTimersByTime(200);
+ pointer(panel, 'pointerenter');
+ vi.advanceTimersByTime(500);
+ expect(page.navigationOpen()).toBe(true);
+ pointer(panel, 'pointerleave');
+ vi.advanceTimersByTime(229);
+ expect(page.navigationOpen()).toBe(true);
+ vi.advanceTimersByTime(1); fixture.detectChanges();
+ expect(page.navigationOpen()).toBe(false);
+ expect(page.navigationAttached()).toBe(true);
+ expect(document.querySelector('.panel-closing')).not.toBeNull();
+ vi.advanceTimersByTime(180); fixture.detectChanges();
+ expect(page.navigationAttached()).toBe(false);
+ expect(document.querySelector('.panel-shell')).toBeNull();
+ });
+
+ it.each(['touch', 'pen', 'mouse'])('sin hover real ignora %s y conserva la apertura por toque/clic', async pointerType => {
+ await load([item('a', 'Indicador')]);
+ hoverDevice(false);
+ pointer(trigger()!, 'pointerenter', pointerType);
+ expect(page.navigationOpen()).toBe(false);
+ trigger()!.dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 }));
+ fixture.detectChanges();
+ expect(page.navigationOpen()).toBe(true);
+ page.toggleGraphicNavigation(new MouseEvent('click', { detail: 1 }));
+ expect(page.navigationOpen()).toBe(false);
+ });
+
+ it.each(['Enter', ' '])('abre con %s, enfoca la primera opción y deja salir el foco con Tab', async key => {
+ await load([item('a', 'Uno'), item('b', 'Dos')]);
+ trigger()!.focus();
+ const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
+ trigger()!.dispatchEvent(event);
+ fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
+ expect(event.defaultPrevented).toBe(true);
+ expect(document.activeElement).toBe(optionButtons()[0]);
+ const tab = new KeyboardEvent('keydown', { key: 'Tab', bubbles: true, cancelable: true });
+ optionButtons()[1].dispatchEvent(tab);
+ expect(tab.defaultPrevented).toBe(false);
+ expect(document.querySelector('.cdk-focus-trap-anchor')).toBeNull();
+ const outside = fixture.nativeElement.querySelector('[role="tab"]') as HTMLButtonElement;
+ outside.focus();
+ expect(document.activeElement).toBe(outside);
+ expectNoFigureRequests();
+ });
+
+ it('no cierra al salir el puntero si una opción conserva el foco de teclado', async () => {
+ await load([item('a', 'Indicador')]);
+ await openPanel();
+ vi.useFakeTimers();
+ pointer(document.querySelector('app-indicadores-navegacion-panel')!, 'pointerleave');
+ vi.advanceTimersByTime(500);
+ expect(page.navigationOpen()).toBe(true);
+ });
+
+ it('cierra con Escape aun cuando hover no haya trasladado el foco al panel', async () => {
+ await load([item('a', 'Indicador')]); hoverDevice();
+ pointer(trigger()!, 'pointerenter');
+ document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true, cancelable: true }));
+ fixture.detectChanges();
+ expect(page.navigationOpen()).toBe(false);
+ expect(document.activeElement).toBe(trigger());
+ });
+
+ it('no espera animación al cerrar con movimiento reducido', async () => {
+ await load([item('a', 'Indicador')]);
+ vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })));
+ await openPanel();
+ page.closeGraphicNavigation(); fixture.detectChanges();
+ expect(page.navigationAttached()).toBe(false);
+ expect(document.querySelector('.panel-shell')).toBeNull();
+ });
+
+ it('no reabre por entradas del puntero generadas al desmontar el overlay y admite un nuevo movimiento', async () => {
+ await load([item('a', 'Indicador')]); hoverDevice(); vi.useFakeTimers();
+ pointer(trigger()!, 'pointerenter');
+ page.closeGraphicNavigation(); fixture.detectChanges();
+ page.closeGraphicNavigation(); fixture.detectChanges();
+ pointer(trigger()!, 'pointerenter', 'mouse', false);
+ expect(page.navigationOpen()).toBe(false);
+ vi.advanceTimersByTime(180); fixture.detectChanges();
+ expect(page.navigationAttached()).toBe(false);
+ pointer(trigger()!, 'pointermove');
+ expect(page.navigationOpen()).toBe(true);
+ page.closeGraphicNavigation(false); fixture.detectChanges();
+ pointer(trigger()!, 'pointerenter');
+ vi.advanceTimersByTime(500); fixture.detectChanges();
+ expect(page.navigationOpen()).toBe(true);
+ expect(page.navigationClosing()).toBe(false);
+ });
+
+ it('cancela el cierre pendiente al cambiar de sección o dominio y al destruir', async () => {
+ await load([item('a', 'TEA')]); hoverDevice(); vi.useFakeTimers();
+ pointer(trigger()!, 'pointerenter'); pointer(trigger()!, 'pointerleave');
+ page.changeSection('datos'); fixture.detectChanges();
+ expect(page.navigationAttached()).toBe(false);
+ page.changeSection('resumen'); fixture.detectChanges();
+ pointer(trigger()!, 'pointerenter');
+ vi.advanceTimersByTime(500);
+ expect(page.navigationOpen()).toBe(true);
+ pointer(trigger()!, 'pointerleave');
+ page.changeDominio('cama');
+ http.expectOne('/cama/indicadores').flush([item('b', 'CaMa')]); fixture.detectChanges();
+ expect(page.navigationAttached()).toBe(false);
+ pointer(trigger()!, 'pointerenter');
+ vi.advanceTimersByTime(500);
+ expect(page.navigationOpen()).toBe(true);
+ pointer(trigger()!, 'pointerleave');
+ const clear = vi.spyOn(globalThis, 'clearTimeout');
+ const close = vi.spyOn(page, 'closeGraphicNavigation');
+ fixture.destroy();
+ expect(page.navigationAttached()).toBe(false);
+ expect(clear).toHaveBeenCalled();
+ const callsAtDestroy = close.mock.calls.length;
+ vi.advanceTimersByTime(500);
+ expect(close.mock.calls).toHaveLength(callsAtDestroy);
+ });
+
+ it('mantiene botones estables, títulos completos multilínea y transforma solo la etiqueta visual', async () => {
+ const title = 'Indicador clínico con un título extenso que puede ocupar varias líneas completas';
+ await load([item('a', title), item('b', 'Otro indicador')]);
+ await openPanel();
+ const button = optionButtons()[0];
+ expect(button.textContent?.trim()).toBe(title);
+ expect(getComputedStyle(button).minHeight).toBe('44px');
+ expect(getComputedStyle(button).whiteSpace).toBe('normal');
+ expect(getComputedStyle(button).transform).not.toContain('scale');
+ expect(button.querySelector('.option-label')).not.toBeNull();
+ expect(getComputedStyle(document.querySelector('.panel-list')!).overflowX).toBe('hidden');
+ const styles = Array.from(document.querySelectorAll('style')).map(style => style.textContent).join('\n');
+ expect(styles).toContain('button:focus-visible');
+ expect(styles).toContain('scale(1.02)');
+ expect(styles).toContain('scale(0.99)');
+ expect(styles).toContain('prefers-reduced-motion: reduce');
+ expect(styles).toContain('@starting-style');
+ });
+});
diff --git a/src/app/features/indicadores/indicadores-navegacion-panel.html b/src/app/features/indicadores/indicadores-navegacion-panel.html
new file mode 100644
index 0000000..31a196d
--- /dev/null
+++ b/src/app/features/indicadores/indicadores-navegacion-panel.html
@@ -0,0 +1,11 @@
+
Valores publicados para {{ period }}. Los detalles se cargan al consultar las gráficas correspondientes. Cada fila conserva su periodo y población; no se suman grupos ni periodos.
-
-
-
Resultados de indicadores destacados y gráficas consultadas