Merge pull request 'feat(indicadores): ajustar indicadores CaCu y presentacion EU7' (#6) from feature/dona-barras-generales into dev

Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/6
This commit was merged in pull request #6.
This commit is contained in:
2026-10-24 03:23:00 +00:00
19 changed files with 325 additions and 62 deletions
@@ -16,6 +16,22 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
afterEach(()=>{ fixture.destroy(); http.verify(); });
function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); }
function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); }
it('prioridad deshabilitada con una sola opción y sin parámetros nuevos al consultar o paginar', () => {
respond();
const select = fixture.nativeElement.querySelector('select[name="prioridad"]') as HTMLSelectElement;
expect(select.disabled).toBe(true); expect(select.labels?.[0].textContent).toContain('Ordenar por prioridad');
expect(Array.from(select.options).map(o => o.text)).toEqual(['No disponible']);
const order = fixture.componentInstance.data!.items.map(i => i.id_seudonimo);
expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order);
fixture.componentInstance.apply();
let req = http.expectOne(r => r.url === '/cacu/seguimiento');
expect(req.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']);
req.flush(fixtureData); fixture.detectChanges();
fixture.componentInstance.navigate(2); req = http.expectOne(r => r.url === '/cacu/seguimiento');
expect(req.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']);
expect(req.request.params.get('page')).toBe('2');
req.flush({ ...fixtureData, paginacion: { ...fixtureData.paginacion, page: 2 } });
});
it('consulta solo al abrir CaCu, presenta ventana, nulos, calidad y genotipo sin leyendas de prototipo ni prioridad clínica', () => {
fixture.detectChanges(); http.expectNone(()=>true); respond();
const root:HTMLElement=fixture.nativeElement;
@@ -55,7 +55,7 @@ import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
@for (figure of displayFigures; track panelIdentity(figure)) {
<div class="representation-panel">
@if (isDual) { <h3>{{ figureDisplayName(figure, indicador.figuras) }}</h3> }
<app-indicador-figure-panel [dominio]="dominio" [indicador]="indicador" [metadata]="metadata" [figuraId]="figure" [tema]="tema" [applied]="applied" [visible]="visible" [visualProfile]="visualProfile" [localSelection]="localSelection" (metadataRequested)="loadMetadata()" (hierarchySelected)="localSelection = $event" />
<app-indicador-figure-panel [dominio]="dominio" [indicador]="indicador" [metadata]="metadata" [figuraId]="figure" [tema]="tema" [applied]="applied" [independentPeriods]="independentPeriods" [visible]="visible" [visualProfile]="visualProfile" [localSelection]="localSelection" (metadataRequested)="loadMetadata()" (hierarchySelected)="localSelection = $event" />
</div>
}
</div>
@@ -144,6 +144,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
@Input({ required: true }) indicador!: Indicador;
@Input({ required: true }) tema!: Tema;
@Input({ required: true }) applied!: GlobalApplied;
@Input() independentPeriods = false;
@Input() pinned = false;
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
readonly pinChanged = output<void>();
@@ -72,7 +72,6 @@
@if (m.escenarios.length && barsFigure) {
<app-plotly-chart [figure]="barsFigure" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7 · Barras por escenario clínico · ' + m.periodo + ' · ' + selectionLabel" />
}
@for (s of m.escenarios; track s.id) { <p>{{ s.etiqueta }}: {{ scenarioText(s) }}.</p> }
</section>
</div>
}
@@ -46,6 +46,9 @@ describe('EU7 integración Angular y caché compartida', () => {
const kpi = TestBed.inject(IndicadoresSnapshots).datos('cacu', indicador.id, 'semestre', ['2025-S2'], indicador.version).subscribe();
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
flush(); expect(f.componentInstance.model!.total).toBe(946);
const scenarioFigure = f.nativeElement.querySelectorAll('.figure')[1] as HTMLElement;
expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1);
expect((f.componentInstance.barsFigure!.layout['annotations'] as { text: string }[])[0].text).toBe('682');
const general = data.general; const original = structuredClone(applied);
const anormal = Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>).find(b => b.textContent!.includes('Anormal'))!;
anormal.click(); f.detectChanges(); expect(f.componentInstance.selection.grupo).toBe('ANORMAL');
@@ -65,7 +65,6 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
}
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
percentText(value: number | null) { return value === null ? 'No disponible' : value.toFixed(1) + ' %'; }
scenarioText(s: Escenario) { return s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado' : `${s.den} pacientes con resultado`; }
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
ngOnChanges(changes: SimpleChanges) {
@@ -25,7 +25,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
<section class="figure-panel" [attr.aria-labelledby]="titleId">
<h3 class="visually-hidden" [id]="titleId">{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}</h3>
<header class="panel-controls">
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
<p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p>
@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) {
<span class="selection-status" [class.selection-active]="!!generalSelectionContext" tabindex="0" role="status"
[attr.aria-label]="generalSelectionContext ?? 'Distribución completa, sin selección local de la dona.'"
@@ -127,6 +127,7 @@ export class IndicadorFigurePanel implements OnChanges {
@Input({ required: true }) figuraId!: string;
@Input({ required: true }) tema!: Tema;
@Input({ required: true }) applied!: GlobalApplied;
@Input() independentPeriods = false;
@Input() visible = true;
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
@Input() localSelection: DonutSelection = {};
@@ -31,7 +31,7 @@ describe('KPI integración con autoridad global', () => {
function requests() { return http.match(r => r.url.endsWith('/datos')); }
function response(index: number, domain: Dominio = 'cacu', period = '2025-S1'): IndicadorDatos {
const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [
{ periodo: period, grupo: index === 1 && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] };
{ periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] };
}
function apply(periods: string[], tipo: 'mes' | 'semestre' = 'semestre') {
const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] };
@@ -53,12 +53,13 @@ describe('KPI integración con autoridad global', () => {
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]);
expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
});
it('tres tarjetas independientes manejan 404, error y éxito sin cifras anteriores', () => {
load('cacu'); const req = requests(); expect(req).toHaveLength(3); expect(panels().every(p => p.result().loading)).toBe(true);
it('dos KPI reales y un placeholder manejan 404, error y éxito sin cifras anteriores', () => {
load('cacu'); const req = requests(); expect(req).toHaveLength(2); expect(panels().every(p => p.result().loading)).toBe(true);
for (const r of req) { expect(r.request.params.has('tipoPeriodo')).toBe(false); expect(r.request.params.has('tema')).toBe(false); }
req[0].flush('private', { status: 404, statusText: 'Not Found' }); req[1].flush('private', { status: 503, statusText: 'Unavailable' }); req[2].flush(response(2)); fixture.detectChanges();
expect(panels().map(p => p.result().state)).toEqual(['Sin datos del periodo', 'Error de consulta', 'Disponible']);
expect(panels()[2].result().value).toBe(7); expect(fixture.nativeElement.textContent).not.toContain('private');
req[0].flush('private', { status: 404, statusText: 'Not Found' }); req[1].flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
expect(panels().map(p => p.result().state)).toEqual(['Sin datos del periodo', 'Error de consulta']);
panels()[1].retry(); requests()[0].flush(response(1)); fixture.detectChanges();
expect(panels()[1].result().value).toBe(7); expect(fixture.nativeElement.textContent).not.toContain('private');
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
apply(['2025-S2']); expect(panels().every(p => p.result().value === undefined)).toBe(true); requests().forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2')));
});
@@ -67,10 +68,10 @@ describe('KPI integración con autoridad global', () => {
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7]);
expect(panels().map(p => p.result().value)).toEqual([5, 7]);
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true);
apply(['2025-S2']); expect(single.every(r => r.cancelled)).toBe(true); const next = requests(); expect(next).toHaveLength(3);
apply(['2025-S2']); expect(single.every(r => r.cancelled)).toBe(true); const next = requests(); expect(next).toHaveLength(2);
next.forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2')));
apply(['2025-S2']); http.expectNone(() => true);
});
@@ -89,7 +90,7 @@ describe('KPI integración con autoridad global', () => {
it('el catálogo vigente retira los KPI que dejaron de publicarse', () => {
load('cacu', true); expect(panels().map(p => p.definition.id)).toEqual(KPI_BY_DOMAIN.cacu.slice(1).map(d => d.id));
expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(2);
const req = requests(); expect(req).toHaveLength(2); req.forEach((r,i) => r.flush(response(i+1)));
const req = requests(); expect(req).toHaveLength(1); req.forEach((r,i) => r.flush(response(i+1)));
});
it.each([0, 1, 2])('retirar definiciones deja %i tarjetas y conserva filtros y valores retenidos', count => {
load('cacu'); requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges();
@@ -99,18 +100,18 @@ describe('KPI integración con autoridad global', () => {
try {
page.kpisByDomain.cacu = definitions.slice(0, count); page.catalog.set([...page.catalog()]); fixture.detectChanges();
expect(panels()).toHaveLength(count); panels().forEach((panel, i) => expect(panel).toBe(before[i]));
expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7].slice(0, count));
expect(panels().map(p => p.result().value)).toEqual([5, 7].slice(0, count));
expect(page.filters).toBe(state); expect(state).toEqual(snapshot);
const grid = fixture.nativeElement.querySelector('.kpi-grid') as HTMLElement | null;
if (count) {
expect(grid!.children).toHaveLength(count);
expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count));
expect(grid!.children).toHaveLength(count + 1);
expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count + 1));
} else expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull();
http.expectNone(() => true);
page.kpisByDomain.cacu = definitions; page.catalog.set([...page.catalog()]); fixture.detectChanges();
const added = requests(); expect(added).toHaveLength(0);
added.forEach((r, i) => r.flush(response(count + i)));
expect(panels()).toHaveLength(3); expect(state).toEqual(snapshot);
expect(panels()).toHaveLength(2); expect(state).toEqual(snapshot);
} finally { page.kpisByDomain.cacu = definitions; }
});
it('retirar un ID del catálogo conserva los otros KPI y los filtros', () => {
@@ -118,7 +119,7 @@ describe('KPI integración con autoridad global', () => {
const page = fixture.componentInstance, before = panels(), filters = structuredClone(page.filters);
page.catalog.set(page.catalog().slice(1)); fixture.detectChanges();
expect(panels()).toEqual(before.slice(1)); expect(page.filters).toEqual(filters);
expect(panels()).toHaveLength(2); http.expectNone(() => true);
expect(panels()).toHaveLength(1); http.expectNone(() => true);
});
it('CaCu no presenta KPI disponibles durante carga/error y reintenta sin confirmar vacío', () => {
const page = fixture.componentInstance; page.changeDominio('cacu'); fixture.detectChanges();
@@ -138,7 +139,7 @@ describe('KPI integración con autoridad global', () => {
load('cacu'); const before = panels();
const data = response(1);
if (scenario === 'suprimido') data.filas[0]['suprimido'] = 1;
if (scenario === 'nulo') data.filas[0]['valor'] = null;
if (scenario === 'nulo') data.filas[0]['mediana'] = null;
if (scenario === 'sin filas') { data.filas = []; data.periodos = []; }
requests().forEach((r, i) => r.flush(i === 1 ? data : response(i))); fixture.detectChanges();
expect(panels()).toEqual(before); expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(3);
@@ -150,22 +151,22 @@ describe('KPI integración con autoridad global', () => {
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
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: [] })); fixture.detectChanges();
expect(panels()).toHaveLength(3); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
http.expectNone(r => r.url.endsWith('/datos'));
});
it('las seis tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
for (const domain of ['cacu', 'cama'] as const) {
load(domain);
const req = requests(); expect(req).toHaveLength(3);
const req = requests(); expect(req).toHaveLength(KPI_BY_DOMAIN[domain].length);
req.forEach((r, i) => r.flush(response(i, domain)));
fixture.detectChanges();
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
expect(cards).toHaveLength(3);
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', '40.0', '7']);
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', '%', 'días (mediana)']);
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(['Disponible', 'Disponible', 'Disponible']);
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', '7', undefined] : ['5', '40.0', '7']);
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', 'días (mediana)', undefined] : ['pacientes', '%', 'días (mediana)']);
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Disponible', 'Indicador no disponible'] : ['Disponible', 'Disponible', 'Disponible']);
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
expect.stringContaining('2025-S1'), expect.stringContaining('2 de 5'),
expect.stringContaining('2025-S1'),
expect.stringContaining(`5 ${domain === 'cacu' ? 'citologías' : 'mastografías'}; Q1 a Q3: 3 a 9 días.`),
]));
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
@@ -193,7 +194,7 @@ describe('KPI integración con autoridad global', () => {
}
load('cacu', false, ['2025-S1'], true);
expect(fixture.componentInstance.initialPeriodBlocked).toBe(false);
expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7]); http.expectNone(() => true);
expect(panels().map(p => p.result().value)).toEqual([5, 7]); http.expectNone(() => true);
});
it('salir durante el recorrido cancela periodos antiguos y volver reutiliza últimos resueltos', () => {
load('cacu', false, ['2025-S2', '2025-S1'], true);
@@ -213,7 +214,7 @@ describe('KPI integración con autoridad global', () => {
expect(panels().every(p => p.result().state === 'Dato oculto por tamaño')).toBe(true); http.expectNone(() => true);
fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'todos' };
fixture.componentInstance.applyFilters(); fixture.detectChanges();
const latest = requests(); expect(latest).toHaveLength(3);
const latest = requests(); expect(latest).toHaveLength(2);
latest.forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S2'); const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); });
expect(panels().every(p => p.temporalReference === '2025-S2')).toBe(true); http.expectNone(() => true);
});
@@ -0,0 +1,196 @@
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ActivatedRoute, provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IndicadoresPage } from './indicadores-page';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigurePanel } from './indicador-figure-panel';
import { IndicadorFigureCard } from './indicador-figure-card';
import { IndicadorKpiPanel } from './indicador-kpi-panel';
import { IndicadoresMemory } from './indicadores-memory';
import { IndicadoresSnapshots } from './indicadores-snapshots';
import { IndicadoresNumericSummary } from './indicadores-numeric-summary';
import { Indicador, PlotlyFigure } from './indicadores.models';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { figureApplied } from './indicadores-figure-selection';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub {}
const item = (id: string, titulo = id, contrato: Indicador['contrato'] = 'C1'): Indicador => ({
id, titulo, contrato, tipos_periodo: ['semestre', 'mes'],
figuras: contrato === 'C1' ? ['fig_c1_puntos'] : [], version: '1',
});
const catalog = [
item('cacu_eu13', 'Tasa de confirmación histopatológica'),
item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r'),
item('ind1', 'Pacientes con citología anómala'),
item('ordinary', 'Otra gráfica'),
item('cacu_eu7', 'Distribución de resultados citológicos', 'C2'),
];
const periods = ['2025-S1', '2025-S2'];
const multi: PlotlyFigure = { data: [{ type: 'scatter', x: periods, y: [null, 25],
customdata: [[null, 0, 1], [1, 4, 0]], text: ['Suprimido', '1 de 4'], mode: 'markers' }], layout: {} };
describe('CaCu: oportunidad y selección independiente de todos los reportes', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
let page: IndicadoresPage, http: HttpTestingController;
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]),
{ provide: ActivatedRoute, useValue: { snapshot: { data: { dominio: 'cacu' } } } },
provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance;
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
http = TestBed.inject(HttpTestingController);
http.expectOne('/cacu/indicadores').flush(structuredClone(catalog));
// Real inventory and KPI consumers: only the two published KPI request data.
for (;;) {
const requests = http.match(r => r.url.endsWith('/periodos'));
if (!requests.length) break;
for (const r of requests) r.flush({ id: r.request.url.split('/')[3],
periodos: periods.map(periodo => ({ periodo, tipo: 'semestre' })) });
}
fixture.detectChanges();
const requests = http.match(r => r.url.endsWith('/datos'));
expect(requests.map(r => r.request.url)).toEqual([
'/cacu/indicadores/cacu_eu7/datos', '/cacu/indicadores/cacu_dias_toma_diagnostico/datos',
]);
for (const r of requests) {
const id = r.request.url.split('/')[3], contrato = id === 'cacu_eu7' ? 'C2' : 'C3r';
r.flush({ id, contrato, tipo_periodo: 'semestre', periodos: ['2025-S2'], categorias: { A: {} },
filas: [{ periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria: 'A', n: 5, suprimido: 0,
mediana: 7, q1: 3, q3: 9, unidad: 'dias' }] });
}
fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
const cards = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard);
const card = (id: string) => cards().find(c => c.indicador.id === id)!;
const panel = (id: string) => fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel))
.map(e => e.componentInstance as IndicadorFigurePanel).find(p => p.indicador.id === id)!;
function open(...ids: string[]) { ids.forEach(id => card(id).setVisible(true)); fixture.detectChanges(); }
function figure(id: string) { return http.expectOne('/cacu/indicadores/' + id + '/figuras/fig_c1_puntos?tema=claro'); }
function apply(tipo: 'mes' | 'semestre', selected: [string, ...string[]]) {
page.filters!.tipo = tipo;
page.filters!.editors[tipo] = { added: [], draft: { mode: 'explicit', periodos: selected } };
page.applyFilters(); fixture.detectChanges();
}
it('encabezados, tres tarjetas en orden y placeholder inerte sin periodo, unidad ni HTTP', () => {
const root: HTMLElement = fixture.nativeElement;
expect(root.querySelector('#kpi-section-title')?.textContent).toBe('Indicadores de oportunidad');
expect(root.querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
const kpis = Array.from(root.querySelectorAll('.kpi-section app-indicador-kpi-card'));
expect(kpis.map(k => k.querySelector('h3')?.textContent)).toEqual([
'Pacientes evaluadas', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de diagnóstico a tratamiento',
]);
expect(kpis[2].querySelectorAll('p')).toHaveLength(1);
expect(kpis[2].querySelector('p')?.textContent).toBe('Indicador no disponible');
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 3');
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(2);
expect(root.querySelector('.kpi-section')?.textContent).not.toContain('confirmación histopatológica');
expect(card('cacu_eu13')).toBeDefined();
http.expectNone(() => true);
});
it('EU7 primero sin alterar catálogo; búsqueda y fijación prevalecen y conservan identidades y memoria', () => {
const original = page.catalog(), before = cards();
expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id));
expect(before[0].indicador.id).toBe('cacu_eu7');
page.togglePinned(original[0]); fixture.detectChanges();
expect(cards()[0]).toBe(card('cacu_eu13'));
page.changeSearchQuery('anómala'); fixture.detectChanges();
expect(cards()[0].indicador.id).toBe('ind1');
page.changeSearchQuery(''); fixture.detectChanges();
expect(cards()[0].indicador.id).toBe('cacu_eu13');
for (const c of before) expect(card(c.indicador.id)).toBe(c);
expect(page.catalog()).toBe(original);
expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true);
http.expectNone(() => true);
});
it('inicializa las dos figuras en Todos con reporte aunque el filtro general ya sea mensual; conserva carga diferida', () => {
apply('mes', ['2026-01']);
http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush({ id: r.request.url.split('/')[3], contrato: 'C2', tipo_periodo: 'mes', periodos: [], filas: [] }));
http.expectNone(r => /\/(cacu_eu13|ind1)\/(figuras|datos)\b/.test(r.url));
open('cacu_eu13', 'ind1');
for (const id of ['cacu_eu13', 'ind1']) {
const r = figure(id); expect(r.request.params.has('periodos')).toBe(false);
expect(panel(id).applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 });
r.flush(multi);
}
expect(panel('cacu_eu13').applied).not.toBe(panel('ind1').applied);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Selección independiente: Todos con reporte (semestres)');
});
it('Aplicar no altera selección, datos, representación, host ni GET de las independientes; las ordinarias sí cambian', () => {
open('cacu_eu13', 'ind1', 'ordinary');
for (const id of ['cacu_eu13', 'ind1', 'ordinary']) figure(id).flush(multi);
fixture.detectChanges();
const retained = ['cacu_eu13', 'ind1'].map(id => ({ id, card: card(id), panel: panel(id),
applied: panel(id).applied, result: panel(id).result() }));
const hosts = Array.from(fixture.nativeElement.querySelectorAll('app-plotly-chart'));
card('cacu_eu13').localSelection = { parent: 'own' };
card('ind1').localSelection = { parent: 'different' };
for (const [tipo, selected] of [['semestre', ['2025-S1']], ['mes', ['2026-01']]] as const) {
apply(tipo, [...selected]);
http.expectNone(r => /\/(cacu_eu13|ind1)\/(figuras|datos)\b/.test(r.url));
const r = http.expectOne(r => r.url.includes('/ordinary/figuras/'));
expect(r.request.params.get('periodos')).toBe(selected[0]); r.flush(multi);
http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush({ id: r.request.url.split('/')[3],
contrato: 'C2', tipo_periodo: tipo, periodos: [], filas: [] }));
for (const old of retained) {
expect(card(old.id)).toBe(old.card); expect(panel(old.id)).toBe(old.panel);
expect(panel(old.id).applied).toBe(old.applied); expect(panel(old.id).result()).toBe(old.result);
expect(panel(old.id).result().figure).toEqual(multi);
}
}
expect(card('cacu_eu13').localSelection).toEqual({ parent: 'own' });
expect(card('ind1').localSelection).toEqual({ parent: 'different' });
expect(Array.from(fixture.nativeElement.querySelectorAll('app-plotly-chart'))).toEqual(hosts);
expect(panel('ind1').result().figure!.data[0]['x']).toEqual(periods);
expect(panel('ind1').result().figure!.data[0]['y']).toEqual([null, 25]);
});
it('resumen abierto reutiliza snapshots propios y no consulta los periodos del filtro general', () => {
open('cacu_eu13', 'ind1');
figure('cacu_eu13').flush(multi); figure('ind1').flush(multi);
TestBed.inject(IndicadoresSnapshots).expanded.set(true); fixture.detectChanges();
const requests = http.match(r => r.url.endsWith('/datos'));
expect(requests).toHaveLength(2);
for (const r of requests) {
expect(r.request.params.has('periodos')).toBe(false);
r.flush({ id: r.request.url.split('/')[3], contrato: 'C1', tipo_periodo: 'semestre', periodos: periods,
filas: [{ periodo: periods[0], grupo: 'principal', estrato: null, valor: 25, numerador: 1, denominador: 4, suprimido: 0 },
{ periodo: periods[1], grupo: 'principal', estrato: null, valor: 50, numerador: 5, denominador: 10, suprimido: 0 }] });
}
apply('mes', ['2026-01']);
http.expectNone(r => /\/(cacu_eu13|ind1)\/datos/.test(r.url));
http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush({ id: r.request.url.split('/')[3], contrato: 'C2', tipo_periodo: 'mes', periodos: [], filas: [] }));
const summary = fixture.debugElement.query(By.directive(IndicadoresNumericSummary)).componentInstance as IndicadoresNumericSummary;
for (const id of ['cacu_eu13', 'ind1']) {
const selected = page.catalog().find(i => i.id === id)!;
const reading = summary.snapshots.reading('cacu', selected, summary.figureSelection(selected))!;
expect(summary.rows(reading.data!).map(row => row.period)).toEqual(periods);
expect(reading.data!.filas.map(row => row['denominador'])).toEqual([4, 10]);
}
});
it('reintento individual tras error usa Todos; una nueva versión de catálogo puede revalidar sin tocar otra selección', () => {
open('cacu_eu13', 'ind1');
figure('cacu_eu13').flush({}, { status: 503, statusText: 'Unavailable' }); figure('ind1').flush(multi);
const other = panel('ind1').result();
panel('cacu_eu13').requestFigure();
const retry = figure('cacu_eu13'); expect(retry.request.params.has('periodos')).toBe(false); retry.flush({ data: [], layout: {} });
expect(panel('ind1').result()).toBe(other);
page.catalog.update(items => items.map(i => i.id === 'cacu_eu13' ? { ...i, version: '2' } : i)); fixture.detectChanges();
const revalidated = figure('cacu_eu13'); expect(revalidated.request.params.has('periodos')).toBe(false); revalidated.flush(multi);
expect(panel('ind1').result()).toBe(other);
});
it('la política por ID solo afecta CaCu y ninguna otra gráfica', () => {
const general = page.filters!.applied;
for (const domain of ['tea', 'cama'] as const) for (const id of ['cacu_eu13', 'ind1', 'cacu_eu7']) {
expect(figureApplied(domain, id, general)).toBe(general);
}
expect(figureApplied('cacu', 'cacu_eu7', general)).toBe(general);
});
});
@@ -36,12 +36,15 @@ describe('EU7 modelo de presentación del entregable', () => {
it('cada escenario suma 100 % en TOTAL y Anormal conserva 5.0, 24.3, 21.7, 7.8 %', () => {
const m = model(), f = barras(m, {}, 'claro');
m.escenarios.forEach((s, i) => expect(f.data.reduce((n, t) => n + (t['x'] as number[])[i], 0)).toBeCloseTo(100, 8));
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text)).toEqual(m.escenarios.map(s => `${s.den}`));
const selected = barras(m, { grupo: 'ANORMAL' }, 'claro');
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!));
expect((category.layout['annotations'] as { text: string }[]).map(a => a.text))
.toEqual(m.escenarios.map(s => `<b>${(100 * s.celdas['LIEAG'].n! / s.den!).toFixed(1)} %</b> (${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 => {
@@ -225,12 +225,14 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
hovertemplate: `%{y}<br>${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})<extra></extra>` };
}), 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: 36, b: 90 }, showlegend: false,
margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false,
yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true },
xaxis: { title: { text: '% de pacientes del escenario con resultado' }, ticksuffix: ' %', gridcolor: p.grid,
range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 100] },
range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 112],
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 ? `<b>${sumas[i]!.toFixed(1)} %</b> (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${s.den})` : '' })),
: sel.grupo || sel.categoria ? `<b>${sumas[i]!.toFixed(1)} %</b> (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})`
: miles(s.den) })),
}, config: { displayModeBar: false } };
}
@@ -0,0 +1,19 @@
import { Dominio } from './indicadores.models';
import { GlobalApplied } from './indicadores-memory';
// Presentation policy only. Each indicator owns a stable selection and revision;
// no global Apply can invalidate its figure or numeric snapshot. Omitting periodos
// delegates to the existing backend contract for all reported semesters.
const cacuSelections = new Map<string, GlobalApplied>(
['cacu_eu13', 'ind1'].map(id => [id, Object.freeze({
tipo: 'semestre' as const, selection: Object.freeze({ mode: 'todos' as const }), revision: 0,
})]),
);
export function independentFigurePeriods(domain: Dominio, id: string) {
return domain === 'cacu' && cacuSelections.has(id);
}
export function figureApplied(domain: Dominio, id: string, general: GlobalApplied): GlobalApplied {
return domain === 'cacu' ? cacuSelections.get(id) ?? general : general;
}
@@ -33,7 +33,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); }
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
const inventory = http.match(r => r.url.endsWith('/periodos'));
expect(inventory).toHaveLength(4); // The anchor search shares the catalog inventory request.
expect(inventory).toHaveLength(items.length); // The anchor shares the catalog inventory request.
inventory.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })) }));
fixture.detectChanges();
});
@@ -41,14 +41,14 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
function data(index: number, period: string, value = 7) {
const d = definitions[index];
return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: [period], categorias: { A: {} }, filas: [{
periodo: period, grupo: index === 1 && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: value, suprimido: 0,
periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: value, suprimido: 0,
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); }
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 = 2) {
function flushPanels(period: string, expected = definitions.length - 1) {
const requests = http.match(r => r.url.endsWith('/datos'));
expect(requests).toHaveLength(expected);
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period);
@@ -101,7 +101,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[1]] });
expect(page.filters!.editors.semestre!.draft).toEqual(page.filters!.applied.selection);
expect(pending(page.filters!)).toBe(false); expect(editor().selectedPeriods).toEqual([periods[1]]);
expect(panels()).toHaveLength(3);
expect(panels()).toHaveLength(definitions.length);
expect(panels().every(p => p.applied === page.filters!.applied && !p.initialPresentation && p.temporalReference === periods[1])).toBe(true);
expect(panels()[0].result().value).toBe(7); http.expectNone(() => true);
});
@@ -114,13 +114,13 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
});
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(2);
const requests = http.match(r => r.url.endsWith('/datos')); 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);
});
it('aplicación manual posterior y Todos prevalecen sin repetir la búsqueda', () => {
choose(); editor().select([periods[2]]); fixture.detectChanges(); http.expectNone(() => true);
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3);
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length);
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[2]] });
editor().changeMode('todos'); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[0]);
expect(page.filters!.applied.selection.mode).toBe('todos'); expect(panels().every(p => !p.initialPresentation)).toBe(true); http.expectNone(() => true);
@@ -135,7 +135,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
expect(page.filters!.applied).toBe(applied); expect(page.initialPeriodState()).toBe('ready');
});
it('regreso de otro dominio restaura el periodo manual sin imponer el inicial', () => {
choose(); editor().select([periods[2]]); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3);
choose(); editor().select([periods[2]]); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length);
page.changeDominio(otherDomain); http.expectOne('/' + otherDomain + '/indicadores').flush([]); fixture.detectChanges();
page.changeDominio('tea'); if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); }
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
@@ -148,7 +148,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
});
it('Aplicar Todos durante búsqueda cancela y respeta la decisión manual', () => {
const old = request(periods[0]); expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(false);
page.applyFilters(); fixture.detectChanges(); expect(old.cancelled).toBe(true); flushPanels(periods[0], 3);
page.applyFilters(); fixture.detectChanges(); expect(old.cancelled).toBe(true); flushPanels(periods[0], definitions.length);
expect(page.filters!.applied.selection.mode).toBe('todos'); expect(page.initialPeriodBlocked).toBe(false); http.expectNone(() => true);
});
it('error HTTP queda visible, sin datos mezclados, con reintento funcional', () => {
@@ -175,7 +175,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
expect(editor().selectedPeriods).toEqual([periods[2]]); expect(panels()).toHaveLength(0); http.expectNone(() => true);
page.retryCatalog(); http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
expect(editor().selectedPeriods).toEqual([periods[2]]); expect(page.initialPeriodState()).toBe('manual'); http.expectNone(() => true);
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3);
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length);
expect(panels().every(p => p.temporalReference === periods[2])).toBe(true); http.expectNone(() => true);
});
it('un ancla retirada del catálogo requiere selección manual y no consulta datos retirados', () => {
@@ -189,7 +189,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos'));
expect(index).toBeGreaterThan(0); r.flush(data(index, periods[0]));
}); fixture.detectChanges();
expect(panels()).toHaveLength(2); expect(panels().every(p => p.temporalReference === periods[0])).toBe(true); http.expectNone(() => true);
expect(panels()).toHaveLength(definitions.length - 1); expect(panels().every(p => p.temporalReference === periods[0])).toBe(true); http.expectNone(() => true);
});
it('inicializa y restaura los tres dominios con periodos propios sin repetir datos resueltos', () => {
choose();
@@ -205,8 +205,8 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
page.changeDominio(target); http.expectOne('/' + target + '/indicadores').flush(catalog); fixture.detectChanges();
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ periodo: period, tipo: 'semestre' }] }));
const payload = (index: number) => {
const value = data(index, period); value.id = definitions[index].id;
value.filas[0].grupo = index === 1 && target !== 'tea' ? 'total' : 'TOTAL'; return value;
const value = data(0, period); value.id = definitions[index].id; value.contrato = definitions[index].contrato;
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 => {
@@ -1,14 +1,17 @@
import { KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
import { KPI_BY_DOMAIN, KpiDefinition, kpiResult } from './indicadores-kpi';
import { GlobalApplied } from './indicadores-memory';
import { Dominio, IndicadorDatos } from './indicadores.models';
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 0 };
const total = { periodo: '2025-S1', grupo: 'TOTAL', estrato: null, suprimido: 0 };
// Keep C1 numerical-contract coverage even though CaCu no longer presents a C1 KPI.
const definitions = { ...KPI_BY_DOMAIN, cacu: [KPI_BY_DOMAIN.cacu[0],
{ id: 'cacu_eu13', title: 'Confirmación', contrato: 'C1', unit: '%' } as KpiDefinition, KPI_BY_DOMAIN.cacu[1]] };
function data(domain: Dominio, index: number, filas: Record<string, unknown>[]): IndicadorDatos {
const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: Object.fromEntries(filas.filter(row => typeof row['categoria'] === 'string').map(row => [row['categoria'], {}])), filas };
const d = definitions[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: Object.fromEntries(filas.filter(row => typeof row['categoria'] === 'string').map(row => [row['categoria'], {}])), filas };
}
describe.each(['tea', 'cacu', 'cama'] as const)('KPI %s', domain => {
const c1Group = domain === 'tea' ? 'TOTAL' : 'total';
const run = (index: number, rows: Record<string, unknown>[]) => kpiResult(data(domain, index, rows), KPI_BY_DOMAIN[domain][index], domain, applied);
const run = (index: number, rows: Record<string, unknown>[]) => kpiResult(data(domain, index, rows), definitions[domain][index], domain, applied);
it('C2 suma categorías disjuntas del único TOTAL incluyendo SIN_DATO y cero', () => {
expect(run(0, [{ ...total, categoria: 'A', n: 5 }, { ...total, categoria: 'SIN_DATO', n: 0 }]).value).toBe(5);
expect(run(0, [{ ...total, categoria: 'A', n: 0 }]).value).toBe(0);
@@ -14,7 +14,6 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
],
cacu: [
{ id: 'cacu_eu7', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' },
{ id: 'cacu_eu13', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' },
{ id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
],
cama: [
@@ -4,6 +4,7 @@ import { describePeriods, filterCompatibility, GlobalApplied } from './indicador
import { KpiDefinition } from './indicadores-kpi';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { numericRows } from './indicadores-numeric-rows';
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
@Component({
selector: 'app-indicadores-numeric-summary',
@@ -27,17 +28,17 @@ import { numericRows } from './indicadores-numeric-rows';
}
}
@for (item of catalog; track item.id) {
@let reading = snapshots.reading(dominio, item, applied);
@let reading = snapshots.reading(dominio, item, figureSelection(item));
@let compatible = compatibility(item);
@if (compatible.compatible && reading?.status === 'ready' && reading?.data; as data) {
@for (row of rows(data); track $index) {
<tr><th scope="row">{{ item.titulo }}</th><td>{{ row.period }}</td><td>{{ row.group }} · {{ row.category }}</td>
<td>{{ row.value }} <span class="detail">{{ row.detail }}</span></td><td>{{ row.state }} {{ data.notas?.join(' ') }}</td></tr>
} @empty {
<tr><th scope="row">{{ item.titulo }}</th><td>{{ period }}</td><td>—</td><td>Sin filas publicadas</td><td>{{ data.notas?.join(' ') }}</td></tr>
<tr><th scope="row">{{ item.titulo }}</th><td>{{ figurePeriod(item) }}</td><td>—</td><td>Sin filas publicadas</td><td>{{ data.notas?.join(' ') }}</td></tr>
}
} @else {
<tr><th scope="row">{{ item.titulo }}</th><td>{{ period }}</td><td>—</td><td>No disponible</td>
<tr><th scope="row">{{ item.titulo }}</th><td>{{ figurePeriod(item) }}</td><td>—</td><td>No disponible</td>
<td>{{ !compatible.compatible ? compatible.reason : reading?.status === 'loading' ? 'Cargando…' : reading?.status === 'error' ? 'Error de consulta: ' + reading?.message : 'Pendiente: consulta la gráfica para cargar sus números.' }}
@if (reading?.status === 'error') { <button type="button" (click)="snapshots.retries.update(increment)" [attr.aria-label]="'Reintentar números de ' + item.titulo">Reintentar</button> }</td></tr>
}
@@ -75,7 +76,13 @@ export class IndicadoresNumericSummary implements OnDestroy {
get period() { return describePeriods(this.applied.tipo, this.applied.selection); }
key(item: Indicador) { return snapshotKey(this.dominio, item, this.applied); }
find(id: string) { return this.catalog.find(item => item.id === id); }
compatibility(item: Indicador) { return filterCompatibility(this.applied, item.tipos_periodo); }
figureSelection(item: Indicador) { return figureApplied(this.dominio, item.id, this.applied); }
figurePeriod(item: Indicador) {
const selection = this.figureSelection(item);
return (independentFigurePeriods(this.dominio, item.id) ? 'Selección independiente: ' : '')
+ describePeriods(selection.tipo, selection.selection);
}
compatibility(item: Indicador) { return filterCompatibility(this.figureSelection(item), item.tipos_periodo); }
toggle(event: Event) { this.snapshots.expanded.set((event.target as HTMLDetailsElement).open); }
ngOnDestroy() { this.snapshots.expanded.set(false); }
}
@@ -16,7 +16,7 @@
@if (!catalogLoading() && filters; as state) {
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
<h2 id="global-filters-title" class="section-title">Filtros generales de {{ domainLabels[dominio] }}</h2>
<p class="section-description">La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.</p>
<p class="section-description">{{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}</p>
<app-indicador-period-filters [state]="state" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
(retryAvailability)="retryAvailability()"
(edited)="editFilters()" (apply)="applyFilters()" />
@@ -40,19 +40,22 @@
@let kpis = availableKpis;
@if (kpis.length && !initialPeriodBlocked) {
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
<h2 id="kpi-section-title" class="section-title">Indicadores destacados</h2>
<div class="kpi-grid" [style.--kpi-count]="kpis.length">
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : 'Indicadores destacados' }}</h2>
<div class="kpi-grid" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 1 : 0)">
@for (definition of kpis; track dominio + ':' + definition.id) {
<app-indicador-kpi-panel [dominio]="dominio" [definition]="definition" [indicador]="kpiIndicator(definition.id)"
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
}
@if (dominio === 'cacu') {
<app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible" />
}
</div>
</section>
}
<section class="graphic-section" aria-labelledby="graphic-section-title">
<div class="catalog-heading">
<h2 id="graphic-section-title" class="section-title">Indicadores gráficos</h2>
<h2 id="graphic-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2>
@if (!catalogLoading() && !catalogError() && catalog().length) {
<p class="catalog-count" role="status">{{ catalog().length }} indicadores publicados</p>
}
@@ -90,7 +93,7 @@
}
<div class="catalog-grid">
@for (item of searchResults().items; track cardIdentity(item)) {
<app-indicador-catalog-card [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="filters!.applied"
<app-indicador-catalog-card [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
}
</div>
@@ -18,6 +18,8 @@ import { IndicadorPeriodFilters } from './indicador-period-filters';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { KPI_BY_DOMAIN } from './indicadores-kpi';
import { IndicadorKpiPanel } from './indicador-kpi-panel';
import { IndicadorKpiCard } from './indicador-kpi-card';
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
import { indicatorIdentity } from './indicadores-identities';
import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos';
import { httpMessage } from './indicadores-http';
@@ -30,7 +32,7 @@ type DashboardSection = 'resumen' | 'seguimiento' | 'datos';
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNumericSummary],
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNumericSummary],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
@@ -241,6 +243,8 @@ export class IndicadoresPage {
dominio: Dominio = 'tea';
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
readonly kpisByDomain = KPI_BY_DOMAIN;
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
kpiIndicator(id: string) { return this.catalog().find(item => item.id === id); }
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
private readonly catalogRequests = new Subject<void>();
@@ -248,7 +252,11 @@ export class IndicadoresPage {
readonly searchQuery = signal('');
readonly searchVisible = computed(() => this.catalog().length >= 5);
readonly searchResults = computed(() => {
const items = this.catalog();
const catalog = this.catalog();
// Stable presentation priority; search matches and pins still take precedence.
const items = this.dominio === 'cacu'
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
: catalog;
const query = this.normalizeSearch(this.searchQuery());
const prioritize = (group: Indicador[]) => [
...group.filter(item => this.isPinned(item)),
@@ -34,7 +34,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
function data(index: number, domain: Dominio, period: string, suppressed = false): IndicadorDatos {
const d = KPI_BY_DOMAIN[domain][index];
return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [{
periodo: period, grupo: index === 1 ? 'total' : 'TOTAL', estrato: null, categoria: 'A',
periodo: period, grupo: d.contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, categoria: 'A',
n: 0, valor: 0, numerador: 0, denominador: 5, mediana: 0, q1: 0, q3: 0, unidad: 'dias', suprimido: suppressed ? 1 : 0,
}] };
}
@@ -56,9 +56,9 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
const anchor = http.expectOne(r => r.url.endsWith('/' + KPI_BY_DOMAIN[domain][0].id + '/datos'));
const positive = data(0, domain, '2026-S1'); positive.filas[0]['n'] = 4; anchor.flush(positive); fixture.detectChanges();
const requests = flushDatos(domain);
expect(requests.map(r => r.request.params.get('periodos'))).toEqual(['2026-S1', '2026-S1']);
expect(panels().map(p => p.temporalReference)).toEqual(['2026-S1', '2026-S1', '2026-S1']);
expect(panels().map(p => p.result().value)).toEqual([4, '0.0', 0]);
expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPI_BY_DOMAIN[domain].slice(1).map(() => '2026-S1'));
expect(panels().map(p => p.temporalReference)).toEqual(KPI_BY_DOMAIN[domain].map(() => '2026-S1'));
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);
@@ -89,7 +89,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
expect(fixture.nativeElement.textContent).toContain('Existe reporte en al menos un indicador');
expect(fixture.componentInstance.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true);
fixture.componentInstance.applyFilters(); fixture.detectChanges();
const single = flushDatos('cacu'); expect(single).toHaveLength(3);
const single = flushDatos('cacu'); expect(single).toHaveLength(2);
expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true);
control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true);
fixture.componentInstance.applyFilters(); fixture.detectChanges();
@@ -17,6 +17,9 @@
<option [ngValue]="undefined">Todos</option>
@for (s of statuses; track s.codigo) { <option [value]="s.codigo">{{ s.etiqueta }}</option> }
</select></label>
<label>Ordenar por prioridad <select name="prioridad" disabled>
<option>No disponible</option>
</select></label>
<label>Registros por página <input name="size" type="number" min="1" max="200" required [(ngModel)]="draft.page_size" /></label>
<button type="submit" [disabled]="status === 'loading'">Consultar</button>
</form>