From 3e3ec5fd032f7effb2677d54e3bb3fffff147601 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 03:54:00 -0600 Subject: [PATCH] CaCu history: no reserved panels, no notice, and widening the periods twice no longer drops the second answer The times to treatment and the risk by band had a reserved panel each, and the tab carried a notice about clinical validation: both go. Widening the window from 5 to 10 to 'Todos' before the first answer arrived dropped the second answer (it was compared with the load it started from), so the periods did not update. An answer now joins whatever load is current, and a period two widenings asked for is kept once. Co-Authored-By: Claude Sonnet 5.5 --- .../indicadores/indicador-kpi-panel.spec.ts | 2 +- .../indicadores-cacu-final.spec.ts | 4 +- .../indicadores-historico-cacu-fhir.spec.ts | 11 ++-- ...indicadores-historico-cacu-paneles.spec.ts | 54 +++++++++---------- .../indicadores-historico-config.ts | 18 +------ .../indicadores/indicadores-historico.ts | 19 +++++-- .../indicadores-kpi-resultado.spec.ts | 3 +- .../indicadores/indicadores-page.html | 7 ++- 8 files changed, 52 insertions(+), 66 deletions(-) diff --git a/src/app/features/indicadores/indicador-kpi-panel.spec.ts b/src/app/features/indicadores/indicador-kpi-panel.spec.ts index 9e5ede1..429e79c 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.spec.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.spec.ts @@ -187,7 +187,7 @@ describe('KPI integración con autoridad global', () => { expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', undefined, '7', undefined, undefined]); expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', undefined, 'días (mediana)', undefined, undefined]); expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' - ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Integración pendiente', 'Integración pendiente'] + ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']); expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([ expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'), diff --git a/src/app/features/indicadores/indicadores-cacu-final.spec.ts b/src/app/features/indicadores/indicadores-cacu-final.spec.ts index acaf5ff..bc3a893 100644 --- a/src/app/features/indicadores/indicadores-cacu-final.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-final.spec.ts @@ -87,8 +87,8 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', ( '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', ]); for (const kpi of kpis.slice(3)) { - expect(kpi.querySelector('.kpi-state')?.textContent?.trim()).toBe('Integración pendiente'); - expect(kpi.textContent).toContain('aún no está publicado'); + expect(kpi.querySelectorAll('p')).toHaveLength(1); + expect(kpi.querySelector('p')?.textContent).toBe('Indicador no disponible'); } expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 5'); expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(3); diff --git a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts index 7e62a94..638f857 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts @@ -89,14 +89,9 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => { expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato); } }); - it('los paneles reservados llevan los ids FHIR esperados y ninguno se activa por estar en el catálogo', () => { - const reservados = HISTORICO_CACU.filter(p => disponibilidadDe(p) !== 'activo'); - expect(reservados.map(p => [p.id, p.fhir, disponibilidadDe(p)])).toEqual([ - ['cacu_dias_toma_tratamiento', ['CACU-DIAS-TOMA-TRATAMIENTO'], 'integracion_pendiente'], - ['cacu_dias_diagnostico_tratamiento', ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'], 'integracion_pendiente'], - ['cacu_riesgo_banda', ['CACU-RIESGO-BANDA'], 'pendiente_validacion'], - ]); - // The risk bands are in the catalog and stay reserved. + it('todos los paneles del Histórico están activos; las medidas sin panel siguen en el catálogo', () => { + expect(HISTORICO_CACU.filter(p => disponibilidadDe(p) !== 'activo')).toEqual([]); + expect(HISTORICO_CACU.map(p => p.id)).not.toContain('cacu_riesgo_banda'); expect(indicadorDeMeasure(medida('CACU-RIESGO-BANDA')).id).toBe('cacu_riesgo_banda'); }); }); diff --git a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts index fbca39c..adfd981 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts @@ -1,6 +1,5 @@ -// Covers CaCu's history tab: the six active panels and the three reserved ones, what is requested and when (nothing -// until the tab is open, nothing for a reserved panel, only the latest periods at first), the states of a panel, and -// the notice. Responses are synthetic, shaped like /cacu/indicadores//periodos and /datos. +// Covers CaCu's history tab: its six panels (the times to treatment and the risk by band have none), what is requested +// and when (nothing until the tab is open, only the latest periods at first), the states of a panel, and the notice. Responses are synthetic, shaped like /cacu/indicadores//periodos and /datos. import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -9,7 +8,7 @@ import { By } from '@angular/platform-browser'; import { MatDialog } from '@angular/material/dialog'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { IndicadoresHistorico } from './indicadores-historico'; -import { AVISO_CACU, HISTORICO_CACU } from './indicadores-historico-config'; +import { HISTORICO_CACU } from './indicadores-historico-config'; import { Indicador } from './indicadores.models'; @Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) @@ -20,10 +19,11 @@ const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025- const CONTRATOS: Record = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r', cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' }; const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']; -const RESERVADOS = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']; +// Measures the catalog can publish that the history has no panel for. +const SIN_PANEL = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']; const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador; -// Every measure the catalog could publish, reserved ones included: publishing them must not activate them. -const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item); +// Every measure the catalog could publish: publishing the ones without a panel must not add one. +const CATALOGO = [...ACTIVOS, ...SIN_PANEL].map(item); function datos(id: string, tipo: string, periodos: string[], opciones: { contrato?: string; sinPoblacion?: string } = {}) { const contrato = opciones.contrato ?? CONTRATOS[id]; @@ -91,36 +91,30 @@ describe('Histórico de CaCu', () => { fixture.detectChanges(); } expect([...vistos].sort()).toEqual([...ACTIVOS].sort()); - for (const reservado of RESERVADOS) expect(vistos.has(reservado)).toBe(false); + for (const id of SIN_PANEL) expect(vistos.has(id)).toBe(false); }); - it('dibuja nueve paneles en orden: seis con gráfica y tres reservados sin consultar', () => { + it('dibuja seis paneles en orden, todos con gráfica, aunque el catálogo publique medidas sin panel', () => { montar(CATALOGO, true); responder(); expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(p => p.titulo)); - expect(paneles()).toHaveLength(9); + expect(paneles()).toHaveLength(6); expect(graficas()).toHaveLength(6); - const reservados = paneles().slice(6); - expect(reservados.every(p => !p.querySelector('app-plotly-chart') && !p.querySelector('mat-progress-bar'))).toBe(true); - expect(reservados.map(p => p.querySelector('[data-reservado]')?.getAttribute('data-reservado'))).toEqual(['integracion', 'integracion', 'validacion']); - expect(reservados[0].textContent).toContain('Integración pendiente'); - expect(reservados[2].textContent).toContain('Pendiente de validación'); - // Title and description, no figures, no invented numbers. - expect(reservados[2].textContent).toContain('banda de riesgo de CIN2+'); - expect(reservados.every(p => !/\d+ de \d+|0 %|rango/i.test(p.querySelector('p.rango')?.textContent ?? ''))).toBe(true); + expect(root().querySelector('[data-reservado]')).toBeNull(); + for (const titulo of ['Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento', 'Riesgo CIN2+ por banda']) expect(root().textContent).not.toContain(titulo); }); - it('un panel reservado sigue reservado aunque el catálogo no lo publique ni lo publique', () => { - // Pins down: the state of a reserved panel comes from the config alone. - for (const catalogo of [ACTIVOS.map(item), CATALOGO]) { - montar(catalogo, true); responder(); - expect(paneles().slice(6).map(p => p.querySelector('[data-reservado]')?.getAttribute('data-reservado'))).toEqual(['integracion', 'integracion', 'validacion']); - fixture.destroy(); TestBed.resetTestingModule(); - } + it('ampliar dos veces seguidas (de 5 a 10 y a «Todos») sin esperar la primera respuesta deja todos los periodos', () => { + // Fails if the second answer is dropped because the first one arrived before it: the periods stop at the 10. + montar(CATALOGO, true); responder(); + pedidos.length = 0; + fixture.componentInstance.elegirVentana(10); fixture.detectChanges(); + fixture.componentInstance.elegirVentana(0); fixture.detectChanges(); + responder(); + expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)'); + expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12); }); - it('el aviso de validación clínica y supresión se ve siempre', () => { + it('el Histórico de CaCu no lleva un aviso de validación clínica', () => { montar(); - const aviso = root().querySelector('[data-aviso="historico"]')!; - expect(aviso.textContent).toBe(AVISO_CACU); - expect(aviso.textContent).toContain('validación clínica'); - expect(aviso.textContent).toContain('supresión'); + expect(root().querySelector('[data-aviso="historico"]')).toBeNull(); + expect(root().textContent).not.toContain('supresión estadística'); }); it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => { // Pins down the first request: the page asks for the latest five months, not the twelve it could. diff --git a/src/app/features/indicadores/indicadores-historico-config.ts b/src/app/features/indicadores/indicadores-historico-config.ts index d5e4b09..94ce483 100644 --- a/src/app/features/indicadores/indicadores-historico-config.ts +++ b/src/app/features/indicadores/indicadores-historico-config.ts @@ -51,14 +51,10 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [ { id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' }, ]; -// Whether CaCu offers the history tab. The panels carry no clinical validation and no suppression policy yet (see -// `AVISO_CACU`): while they wait, this is the switch that takes the tab out. +// Whether CaCu offers the history tab: the switch that takes it out. export const HISTORICO_CACU_HABILITADO = true; -export const AVISO_CACU = 'Los resultados de CaCu están sujetos a validación clínica y a la política institucional de supresión estadística. ' - + 'Los conjuntos clínicos, los horizontes y los umbrales son provisionales. No los use para decidir.'; - -// CaCu's history. The first six read the measures `dev` publishes; the last three are reserved. +// CaCu's history: the six measures `dev` publishes. The times to treatment and the risk by band have no panel here. export const HISTORICO_CACU: readonly PanelHistorico[] = [ { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', grafica: 'barras_apiladas' }, { id: 'ind1', titulo: 'Pacientes con citología anómala', contrato: 'C1', grafica: 'linea_porcentaje' }, @@ -66,15 +62,6 @@ export const HISTORICO_CACU: readonly PanelHistorico[] = [ { id: 'cacu_confirmacion_citologia', titulo: 'Resultado de biopsia tras citología de alto grado', contrato: 'C2', grafica: 'barras_apiladas' }, { id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' }, - { id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', estado: 'integracion_pendiente', - fhir: ['CACU-DIAS-TOMA-TRATAMIENTO'], - descripcion: 'Días de la toma de la citología al primer tratamiento. La medida no está en el catálogo de dev.' }, - { id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', estado: 'integracion_pendiente', - fhir: ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'], - descripcion: 'Días del diagnóstico que resuelve la citología al primer tratamiento. La medida no está en el catálogo de dev.' }, - { id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas', estado: 'pendiente_validacion', - fhir: ['CACU-RIESGO-BANDA'], - descripcion: 'Pacientes de la cohorte de vigilancia por banda de riesgo de CIN2+. El horizonte, el modelo y los cortes no están aprobados.' }, ]; const HISTORICOS: Readonly>> = { @@ -86,7 +73,6 @@ const HISTORICOS: Readonly>> = { periodosIniciales: 5, conciliarC2: true, c2SinPoblacionSinDato: true, - aviso: AVISO_CACU, }, }; diff --git a/src/app/features/indicadores/indicadores-historico.ts b/src/app/features/indicadores/indicadores-historico.ts index 1de8561..8c59933 100644 --- a/src/app/features/indicadores/indicadores-historico.ts +++ b/src/app/features/indicadores/indicadores-historico.ts @@ -28,9 +28,12 @@ const CASOS = 'M28_casos_por_estado'; const PERSONALIZADO = -1; // What two answers for the same indicator give together: the periods, rows and reports of both. function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos { - const reportes = [...(Array.isArray(a['reportes']) ? a['reportes'] : []), ...(Array.isArray(b['reportes']) ? b['reportes'] : [])]; + // A period both have (two widenings asked for it) is kept once, from `a`. + const nuevos = b.periodos.filter(p => !a.periodos.includes(p)); + const deNuevos = (fila: unknown) => !fila || typeof fila !== 'object' || !('periodo' in fila) || nuevos.includes(String((fila as { periodo: unknown }).periodo)); + const reportes = [...(Array.isArray(a['reportes']) ? a['reportes'] : []), ...(Array.isArray(b['reportes']) ? b['reportes'].filter(deNuevos) : [])]; const unidades = { ...(a['unidades_periodo'] as object | undefined), ...(b['unidades_periodo'] as object | undefined) }; - return { ...a, periodos: [...a.periodos, ...b.periodos.filter(p => !a.periodos.includes(p))], filas: [...a.filas, ...b.filas], + return { ...a, periodos: [...a.periodos, ...nuevos], filas: [...a.filas, ...b.filas.filter(deNuevos)], ...(reportes.length ? { reportes } : {}), ...(a['unidades_periodo'] || b['unidades_periodo'] ? { unidades_periodo: unidades } : {}) }; } @@ -331,13 +334,19 @@ export class IndicadoresHistorico { const faltan = this.necesarios(carga.disponibles).filter(p => !carga.datos.periodos.includes(p)); if (!faltan.length) continue; this.service.datos(this.dominio(), item.id, tipo, faltan).pipe(takeUntilDestroyed(this.destruccion)).subscribe({ + // The load may have been replaced by an earlier widening's answer: what counts is that the item is still ready, and + // `unir` keeps a period once if two widenings asked for it. Comparing with the load this request started from + // dropped the second answer when the first arrived before it (5 -> 10 -> Todos). next: datos => this.cargas.update(actual => { const vigente = actual[tipo]?.[item.id]; - return vigente?.estado === 'listo' && vigente === carga + return vigente?.estado === 'listo' ? { ...actual, [tipo]: { ...actual[tipo], [item.id]: { ...vigente, datos: unir(vigente.datos, datos) } } } : actual; }), - error: error => this.cargas.update(actual => actual[tipo]?.[item.id] === carga - ? { ...actual, [tipo]: { ...actual[tipo], [item.id]: { estado: 'error', mensaje: httpMessage(error) } } } : actual), + error: error => this.cargas.update(actual => { + const vigente = actual[tipo]?.[item.id]; + return vigente?.estado === 'listo' && faltan.some(p => !vigente.datos.periodos.includes(p)) + ? { ...actual, [tipo]: { ...actual[tipo], [item.id]: { estado: 'error', mensaje: httpMessage(error) } } } : actual; + }), }); } } diff --git a/src/app/features/indicadores/indicadores-kpi-resultado.spec.ts b/src/app/features/indicadores/indicadores-kpi-resultado.spec.ts index 7ce6983..c41e96c 100644 --- a/src/app/features/indicadores/indicadores-kpi-resultado.spec.ts +++ b/src/app/features/indicadores/indicadores-kpi-resultado.spec.ts @@ -130,8 +130,7 @@ describe('P0-C.1: cinco tarjetas de oportunidad', () => { 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.querySelector('.kpi-state')?.textContent?.trim()).toBe('Integración pendiente'); - expect(card.textContent).toContain('aún no está publicado'); + 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-page.html b/src/app/features/indicadores/indicadores-page.html index 7961ceb..b03db42 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -52,7 +52,7 @@ @if (resumen) { } -
+
@for (card of kpis; track dominio + ':' + card.definition.id) { @if (card.pending) { } } - @if (dominio === 'cama') { + @if (dominio === 'cacu') { + + + } @else if (dominio === 'cama') { }