feat(indicadores): Resumen as a story of questions, for the domains that have one

How: indicadores-relato.ts holds, per domain, the questions Resumen answers in
order, each with the opportunity cards and charts that answer it, a one-line
reading and, optionally, a button to the tab that continues it. Cáncer de mama
follows the patient's route: 1 ¿Cuántas pacientes tienen un hallazgo
sospechoso? (patients and mammograms with BI-RADS 4-6), 2 ¿Qué tan pronto llega
el diagnóstico? (the two time cards, then Histórico), 3 ¿Cuántos cánceres
confirma la biopsia, y en qué categorías? (detection rate and the BI-RADS
histopathology view), 4 ¿Quiénes siguen pendientes? (to Seguimiento). Each
answer leads to the next question. Indicators no question claims go to «Otros
indicadores». All opportunity cards have one size (17rem by at least 12.5rem):
beside charts they stack in a column, alone they sit in a row; charts take
equal halves and an interactive card the full width. Domains without a story
keep the opportunity and clinical sections.

Implications: the story is WebApp configuration, keyed by indicator ids; when
the catalog or KPI ids change, RELATO_BY_DOMAIN must follow (or come from the
API's metadata later, as a `pregunta` field per indicator). Cards render in
question order, so specs that read cáncer de mama's cards in DOM order expect
patients, times, then detection rate. The charts' search and the TEA print
report stay with the default layout.
This commit is contained in:
rockdrigo
2026-11-09 19:09:36 -06:00
parent 0bf1f82366
commit e5ff3427c7
8 changed files with 176 additions and 4 deletions
@@ -194,9 +194,10 @@ describe('KPI integración con autoridad global', () => {
flushAll(domain, { notas: ['Nota del pie de la figura.'] });
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 4);
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '40.0', '7', '7']);
// Cáncer de mama's cards follow its questions: patients, the two times, then the detection rate.
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '7', '7', '40.0']);
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined]
: ['pacientes', '%', 'días (mediana)', 'días (mediana)']);
: ['pacientes', 'días (mediana)', 'días (mediana)', '%']);
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? [undefined, 'Selección no consolidable', undefined, 'Indicador no disponible', 'Indicador no disponible'] : Array(4).fill(undefined));
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
expect.stringContaining('2025-S1'),
@@ -60,7 +60,9 @@ describe('D.2 integración de autoridad global y consumidores', () => {
const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf<HTMLElement>;
expect(sections[0].textContent).toContain('Filtros generales de ' + page.domainLabels[domain]);
expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(0);
expect(sections[1].getAttribute('aria-labelledby')).toBe('graphic-section-title');
// A domain with a story (relato) shows its questions instead of the charts section.
if (domain === 'cama') expect(sections[1].classList.contains('relato')).toBe(true);
else expect(sections[1].getAttribute('aria-labelledby')).toBe('graphic-section-title');
expect(page.filters!.applied.selection.mode).toBe('todos');
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true);
http.expectNone(() => true);
@@ -44,6 +44,74 @@
} @else if (initialPeriodState() === 'manual') {
<p role="status">La búsqueda inicial se detuvo para conservar tu selección. Pulsa Aplicar para consultar.</p>
}
@if (relato; as preguntas) {
<!-- Each question gathers the cards and charts that answer it, following the patient's route. -->
<section class="relato" aria-label="Preguntas del periodo">
@if (catalogLoading()) {
<mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" />
<p role="status">Cargando catálogo de indicadores…</p>
} @else if (catalogError()) {
<mat-card class="state" role="alert"><p>{{ catalogError() }}</p>
<button mat-stroked-button (click)="retryCatalog()">Reintentar catálogo</button></mat-card>
} @else if (!catalog().length) {
<mat-card class="state"><p role="status">No hay indicadores disponibles en el catálogo.</p>
<button mat-stroked-button (click)="retryCatalog()">Actualizar catálogo</button></mat-card>
} @else if (!initialPeriodBlocked) {
@for (pregunta of preguntas; track pregunta.id; let i = $index) {
@let r = respuesta(pregunta);
<section class="pregunta" [attr.aria-labelledby]="'pregunta-' + pregunta.id">
<header>
<span class="numero" aria-hidden="true">{{ i + 1 }}</span>
<div><h2 class="section-title" [id]="'pregunta-' + pregunta.id">{{ pregunta.pregunta }}</h2><p>{{ pregunta.lectura }}</p></div>
</header>
@if (r.kpis.length || r.items.length) {
<div class="respuesta" [class.con-graficas]="r.items.length">
@if (r.kpis.length) {
<div class="kpi-tarjetas">
@for (definition of r.kpis; track dominio + ':' + definition.id) {
<app-indicador-kpi-panel [dominio]="dominio" [definition]="definition" [indicador]="kpiIndicator(definition.id)"
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
}
</div>
}
@if (r.items.length) {
<div class="catalog-grid">
@for (item of r.items; track cardIdentity(item)) {
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
}
</div>
}
</div>
}
@if (pregunta.enlace; as enlace) {
<button class="continuar" mat-stroked-button type="button" (click)="changeSection(enlace.seccion)">{{ enlace.texto }}</button>
}
</section>
}
@let resto = sinPregunta;
@if (resto.kpis.length || resto.items.length) {
<section class="pregunta" aria-labelledby="pregunta-otros">
<header><div><h2 class="section-title" id="pregunta-otros">Otros indicadores</h2></div></header>
<div class="respuesta" [class.con-graficas]="resto.items.length">
@if (resto.kpis.length) {
<div class="kpi-tarjetas">
@for (definition of resto.kpis; track dominio + ':' + definition.id) { <app-indicador-kpi-panel [dominio]="dominio" [definition]="definition" [indicador]="kpiIndicator(definition.id)"
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" /> }
</div>
}
@if (resto.items.length) {
<div class="catalog-grid">
@for (item of resto.items; track cardIdentity(item)) { <app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" /> }
</div>
}
</div>
</section>
}
}
</section>
} @else {
@let kpis = opportunityKpis;
@if (kpis.length && !initialPeriodBlocked) {
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
@@ -117,6 +185,7 @@
</div>
}
</section>
}
</div>
@if (conHistorico) {
@@ -61,3 +61,24 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.section-panel { padding-block: var(--issste-space-6); }
.section-panel[hidden] { display: none; }
@media (max-width: 550px) { .section-tabs button { flex: 1 1 auto; padding-inline: .65rem; } }
// Resumen as questions. Every opportunity card has the same size (--kpi-ancho by --kpi-alto); next to charts
// they stack in a column, alone they sit in a row. Charts take equal halves; an interactive (dual) card, the full width.
.relato { --kpi-ancho: 17rem; --kpi-alto: 12.5rem; display: grid; gap: var(--issste-space-6); margin-top: var(--issste-space-4); }
.pregunta { padding: var(--issste-space-4) var(--issste-space-6) var(--issste-space-6); background: var(--issste-surface);
border: 1px solid var(--issste-border); border-left: 4px solid var(--issste-accent); border-radius: var(--issste-radius); min-width: 0; }
.pregunta > header { display: flex; align-items: flex-start; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
.pregunta > header p { margin: var(--issste-space-1) 0 0; color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.numero { flex: 0 0 auto; display: inline-grid; place-items: center; width: 2rem; height: 2rem; border: 1px solid var(--issste-text);
border-radius: var(--issste-radius); font-weight: 500; line-height: 1; }
.respuesta { display: grid; gap: var(--issste-space-6); grid-template-columns: minmax(0, 1fr); align-items: start; }
.kpi-tarjetas { display: flex; flex-wrap: wrap; gap: var(--issste-space-4); }
.kpi-tarjetas > app-indicador-kpi-panel { flex: 0 0 var(--kpi-ancho); max-width: 100%; min-height: var(--kpi-alto);
display: grid; grid-template-rows: 1fr auto; }
.respuesta .catalog-grid { grid-template-columns: minmax(0, 1fr); }
.continuar { margin-top: var(--issste-space-4); }
@container dashboard (min-width: 900px) {
.respuesta.con-graficas:has(.kpi-tarjetas) { grid-template-columns: var(--kpi-ancho) minmax(0, 1fr); }
.respuesta.con-graficas .kpi-tarjetas { flex-direction: column; }
.respuesta .catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@@ -13,6 +13,7 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, first, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs';
import { Dominio, isDominio, Indicador, Tema } from './indicadores.models';
import { vistaEscenario } from './indicadores-eu7-escenario';
import { PreguntaRelato, RELATO_BY_DOMAIN, respuesta, sinPregunta } from './indicadores-relato';
import { IndicadoresService } from './indicadores.service';
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
import { IndicadorPeriodFilters } from './indicador-period-filters';
@@ -357,6 +358,10 @@ export class IndicadoresPage {
this.filtersEdited();
this.changeDetector.markForCheck();
}
// Resumen as a story of questions, for the domains that have one.
get relato(): readonly PreguntaRelato[] | undefined { return RELATO_BY_DOMAIN[this.dominio]; }
respuesta(pregunta: PreguntaRelato) { return respuesta(pregunta, this.opportunityKpis, this.searchResults().items); }
get sinPregunta() { return sinPregunta(this.relato ?? [], this.opportunityKpis, this.searchResults().items); }
cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); }
cardElementId(item: Indicador) { return identityElementId(this.cardIdentity(item)); }
// «Ir» in the indicator selector: show the indicator if it was filtered out, then scroll to its card.
@@ -72,7 +72,8 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
const requests = flushDatos(domain);
expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPIS[domain].slice(1).map(() => '2026-S1'));
expect(panels().map(p => p.temporalReference)).toEqual(KPIS[domain].map(() => '2026-S1'));
expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, '0.0', 0]);
// Cáncer de mama shows its cards in the order of its questions: patients, time, detection rate.
expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, 0, '0.0']);
expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2026-S1'] });
expect(fixture.componentInstance.filters!.applied.revision).toBe(1);
fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true);
@@ -0,0 +1,28 @@
import { KPI_BY_DOMAIN } from './indicadores-kpi';
import { Indicador } from './indicadores.models';
import { RELATO_BY_DOMAIN, respuesta, sinPregunta } from './indicadores-relato';
// Covers how Resumen's questions pick their cards and charts. Fixtures: cáncer de mama's real KPI list and a
// small catalog built below with its chart ids plus one indicator no question claims.
const item = (id: string): Indicador => ({ id, titulo: id, contrato: 'C2', figuras: [], tipos_periodo: ['semestre'] });
const catalogo = ['cama_histopatologia_birads', 'cama_birads_456_paciente', 'cama_birads_456_mastografia', 'nuevo'].map(item);
const preguntas = RELATO_BY_DOMAIN.cama!;
describe('Resumen como preguntas', () => {
it('cada pregunta toma sus tarjetas y gráficas en su propio orden', () => {
// Fails if a question takes the catalog's order instead of its own, or loses a card it names.
const hallazgo = respuesta(preguntas[0], KPI_BY_DOMAIN.cama, catalogo);
expect(hallazgo.kpis.map(k => k.id)).toEqual(['cama_birads_456_paciente']);
expect(hallazgo.items.map(i => i.id)).toEqual(['cama_birads_456_paciente', 'cama_birads_456_mastografia']);
});
it('omite lo que la página no tiene', () => {
// Fails if a question names an indicator missing from the catalog and the page tries to draw it.
expect(respuesta(preguntas[2], KPI_BY_DOMAIN.cama, []).items).toEqual([]);
});
it('todas las tarjetas de cáncer de mama tienen pregunta, y lo nuevo queda al final', () => {
// Fails if a card is left out of every question, or a new indicator disappears instead of going to «Otros».
const resto = sinPregunta(preguntas, KPI_BY_DOMAIN.cama, catalogo);
expect(resto.kpis).toEqual([]);
expect(resto.items.map(i => i.id)).toEqual(['nuevo']);
});
});
@@ -0,0 +1,45 @@
import { Dominio, Indicador } from './indicadores.models';
import { KpiDefinition } from './indicadores-kpi';
// Resumen read as the patient's route through screening: each question gathers, in order, the cards and the
// charts that answer it, so the page reads from the suspicious finding to the patients still waiting.
export interface PreguntaRelato {
id: string;
pregunta: string;
// What the answer is made of, in one line.
lectura: string;
kpis: readonly string[];
indicadores: readonly string[];
// The tab that continues the answer: its evolution, or the patients behind it.
enlace?: { seccion: 'historico' | 'seguimiento'; texto: string };
}
export const RELATO_BY_DOMAIN: Partial<Record<Dominio, readonly PreguntaRelato[]>> = {
cama: [
{ id: 'hallazgo', pregunta: '¿Cuántas pacientes tienen un hallazgo sospechoso?',
lectura: 'Mastografías con BI-RADS 4, 5 o 6, y las pacientes que las tienen.',
kpis: ['cama_birads_456_paciente'], indicadores: ['cama_birads_456_paciente', 'cama_birads_456_mastografia'] },
{ id: 'oportunidad', pregunta: '¿Qué tan pronto llega el diagnóstico?',
lectura: 'Mediana de días de cada tramo: de la mastografía a su resultado, y del resultado al diagnóstico.',
kpis: ['cama_eu38a', 'cama_dias_resultado_diagnostico'], indicadores: [],
enlace: { seccion: 'historico', texto: 'Ver su evolución en Histórico' } },
{ id: 'confirmacion', pregunta: '¿Cuántos cánceres confirma la biopsia, y en qué categorías?',
lectura: 'Biopsias con resultado maligno, en total y por categoría BI-RADS.',
kpis: ['cama_tasa_deteccion_histopatologica'], indicadores: ['cama_histopatologia_birads'] },
{ id: 'pendientes', pregunta: '¿Quiénes siguen pendientes?',
lectura: 'Pacientes con biopsia o resultado por llegar, ordenadas por prioridad.',
kpis: [], indicadores: [], enlace: { seccion: 'seguimiento', texto: 'Abrir la lista de Seguimiento' } },
],
};
// The cards and charts of one question, in the question's order, out of those the page has.
export function respuesta(pregunta: PreguntaRelato, kpis: readonly KpiDefinition[], items: readonly Indicador[]) {
const ordenar = <T extends { id: string }>(ids: readonly string[], todos: readonly T[]) =>
ids.map(id => todos.find(item => item.id === id)).filter((item): item is T => !!item);
return { kpis: ordenar(pregunta.kpis, kpis), items: ordenar(pregunta.indicadores, items) };
}
// What no question claims, so a new indicator still shows up at the end.
export function sinPregunta(preguntas: readonly PreguntaRelato[], kpis: readonly KpiDefinition[], items: readonly Indicador[]) {
const usados = new Set(preguntas.flatMap(p => [...p.kpis, ...p.indicadores]));
return { kpis: kpis.filter(k => !usados.has(k.id)), items: items.filter(i => !usados.has(i.id)) };
}