diff --git a/src/app/features/indicadores/indicador-eu7-escenario.html b/src/app/features/indicadores/indicador-eu7-escenario.html index d084249..26db2f9 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.html +++ b/src/app/features/indicadores/indicador-eu7-escenario.html @@ -48,14 +48,14 @@

Distribución de resultados, {{ m.periodo }}

@if (m.total !== null && m.total > 0 && donutFigure) { - + } @else {

{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado disponible para la dona.' }}

}

{{ sinDatoNote }}

{{ selectionLabel }} por escenario clínico, {{ m.periodo }}

Porcentaje del total válido de cada escenario; excluye «Sin dato».

@if (m.escenarios.length && barsFigure) { - + }
diff --git a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts index 0120d8f..a0e8c86 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts +++ b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts @@ -14,7 +14,7 @@ import { Indicador } from './indicadores.models'; @Component({ selector: 'app-plotly-chart', template: '' }) class ChartStub { - figure = input(); label = input(); showNotes = input(); + figure = input(); label = input(); showNotes = input(); animated = input(); plotClick = output(); } describe('EU7 integración Angular y caché compartida', () => { @@ -46,6 +46,7 @@ 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); + expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => (chart.componentInstance as ChartStub).animated())).toEqual([true, true]); 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'); @@ -70,10 +71,13 @@ describe('EU7 integración Angular y caché compartida', () => { } f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } }); f.detectChanges(); flush(); expect(f.componentInstance.model!.total).toBe(1892); expect(f.componentInstance.model!.escenarios[0].den).toBe(1364); + const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance as ChartStub); f.componentInstance.select('grupos', 1); f.componentInstance.changePeriod(1); f.detectChanges(); expect(f.componentInstance.selection).toEqual({}); expect(f.componentInstance.model!.periodo).toBe('2025-S2'); expect(f.componentInstance.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682); expect(f.componentInstance.barsFigure!.layout['annotations']).toBeDefined(); + expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance)).toEqual(charts); + expect(charts.map(chart => chart.animated())).toEqual([true, true]); expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2'); expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true); }); diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts index fd35bd1..4ed77e2 100644 --- a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts +++ b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts @@ -42,8 +42,11 @@ describe('EU7 modelo de presentación del entregable', () => { expect(m.escenarios.map((s, i) => selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0).toFixed(1))) .toEqual(['5.0', '24.3', '21.7', '7.8']); const category = barras(m, { categoria: 'LIEAG' }, 'claro'); - expect(category.data).toHaveLength(1); - expect(category.data[0]['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!)); + // Same traces in every selection (animation identity); unselected ones are zero-width. + expect(category.data.map(t => t['uid'])).toEqual(f.data.map(t => t['uid'])); + const lieag = category.data.find(t => t['uid'] === 'LIEAG')!; + expect(lieag['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!)); + expect(category.data.filter(t => t !== lieag).every(t => (t['x'] as number[]).every(v => v === 0) && t['hoverinfo'] === 'skip')).toBe(true); expect((category.layout['annotations'] as { text: string }[]).map(a => a.text)) .toEqual(m.escenarios.map(s => `${percentNumber(100 * s.celdas['LIEAG'].n! / s.den!)} % (${s.celdas['LIEAG'].n}/${s.den})`)); expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]); @@ -74,7 +77,10 @@ describe('EU7 modelo de presentación del entregable', () => { else if (kind === 'total suprimido') Object.assign((data.escenarios['totales_estrato'] as any[])[0], { n: 123456, suprimido: 1 }); else Object.assign(row, { n: kind === 'nulo' ? null : 123456, suprimido: kind === 'nulo' ? 0 : 1 }); const m = model(), f = barras(m, { categoria: 'LIEAG' }, 'claro'); - expect(m.escenarios[0].den).toBeNull(); expect(f.data[0]['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]); + expect(m.escenarios[0].den).toBeNull(); expect(f.data.find(t => t['uid'] === 'LIEAG')!['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]); + expect(f.data.every(t => (t['x'] as unknown[])[0] === null)).toBe(true); + expect(f.data.filter(t => t['uid'] !== 'LIEAG').every(t => + t['hoverinfo'] === 'skip' && (t['customdata'] as unknown[]).length === 0)).toBe(true); expect(JSON.stringify(f)).not.toContain('123456'); expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull(); }); @@ -95,6 +101,7 @@ describe('EU7 modelo de presentación del entregable', () => { (data.escenarios['totales_estrato'] as any[]).forEach(t => t.n = 0); const m = model(); expect(m.total).toBe(0); expect(dona(m, {}, 'claro').data).toEqual([]); expect(barras(m, {}, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true); + expect(barras(m, { categoria: 'LIEAG' }, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true); expect(barras(m, {}, 'claro').layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: 'Sin pacientes con resultado' })])); }); it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => { @@ -102,4 +109,20 @@ describe('EU7 modelo de presentación del entregable', () => { const m = model(); expect(m.vacio).toBe(true); expect(m.total).toBe(0); expect(m.escenarios).toEqual([]); expect(m.celdas['NORMAL'].n).toBeNull(); }); + it('selección jerárquica y Volver conservan UID, orden, denominadores y datos fuente', () => { + const original = structuredClone(data), m = model(), snapshot = structuredClone(m); + const ids = m.categorias.map(c => c.id); + for (const selection of [{}, { grupo: 'ANORMAL' }, { grupo: 'ANORMAL', categoria: 'LIEAG' }, { categoria: 'LIEAG' }, {}]) { + const f = barras(m, selection, 'claro'); + expect(f.data.map(t => t['uid'])).toEqual(ids); + expect(new Set(f.data.map(t => t['uid'])).size).toBe(ids.length); + f.data.forEach((t, i) => { + if (t['hoverinfo'] === 'skip') { + expect(t['customdata']).toEqual([]); expect(t['text']).toEqual(m.escenarios.map(() => '')); + } else expect(t['x']).toEqual(m.escenarios.map(s => porcentaje(s, ids[i]))); + }); + dona(m, selection, 'claro'); + } + expect(m).toEqual(snapshot); expect(data).toEqual(original); + }); }); diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.ts b/src/app/features/indicadores/indicadores-eu7-escenario.ts index 4324199..aca81aa 100644 --- a/src/app/features/indicadores/indicadores-eu7-escenario.ts +++ b/src/app/features/indicadores/indicadores-eu7-escenario.ts @@ -217,13 +217,20 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id); const y = m.escenarios.map(s => escapar(s.etiqueta)); const sumas = m.escenarios.map(s => s.den === null || s.den === 0 ? null : visibles.reduce((n, c) => n + porcentaje(s, c)!, 0)); - return { data: m.categorias.filter(c => visibles.includes(c.id)).map(c => { - const x = m.escenarios.map(s => porcentaje(s, c.id)); - return { type: 'bar', orientation: 'h', name: escapar(c.etiqueta), y, x, - marker: { color: c.color, line: { color: p.background, width: 1 } }, - text: x.map(v => v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle', - customdata: m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]), - hovertemplate: `%{y}
${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})` }; + // Every category keeps its trace (same uid and count) so a selection animates; + // an unselected category is a zero-width bar without text or hover, never data. + return { data: m.categorias.map(c => { + const visible = visibles.includes(c.id); + const x = m.escenarios.map(s => { + const value = porcentaje(s, c.id); + return value === null ? null : visible ? value : 0; + }); + return { type: 'bar', orientation: 'h', uid: c.id, name: escapar(c.etiqueta), y, x, + marker: { color: c.color, line: { color: p.background, width: visible ? 1 : 0 } }, + text: x.map(v => visible && v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle', + customdata: visible ? m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]) : [], + ...(visible ? { hovertemplate: `%{y}
${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})` } + : { hoverinfo: 'skip' }) }; }), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65), paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text }, margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false, diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts index b783757..ecd3f67 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts @@ -9,6 +9,8 @@ import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures'; import { PacienteDetalle, PacienteDetalleProvider } from './paciente-detalle.models'; import { PACIENTE_DETALLE_PROVIDER, PacienteDetalleMockProvider } from './paciente-detalle.provider'; import { PacienteDetalleState } from './paciente-detalle.state'; +import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; +import { riesgoCacuEjemplo } from './paciente-riesgo.testing'; const pacientes = seguimientoResponse(fixtureData).items; @@ -145,8 +147,9 @@ describe('Ficha individual desde Seguimiento CaCu', () => { expect(Array.from(detail.querySelectorAll('.history-card button'), button => button.textContent?.trim())).toEqual(['Agregar condición', 'Agregar procedimiento']); expect(detail.querySelector('.history-card')!.compareDocumentPosition(detail.querySelector('.tests-card')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); expect(detail.querySelector('.tests-card')!.compareDocumentPosition(detail.querySelector('.risks-card')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(detail.textContent).toContain('Valores ilustrativos · Sin evaluación clínica'); - expect(detail.querySelectorAll('app-paciente-riesgo-tabla tbody tr')).toHaveLength(4); + expect(detail.textContent).toContain('Riesgo individual no disponible para esta paciente.'); + expect(detail.querySelectorAll('app-paciente-riesgo-tabla table')).toHaveLength(0); + expect(detail.textContent).not.toContain('Valores ilustrativos'); volver(); expect(root.querySelector('app-paciente-detalle')).toBeNull(); expect(root.querySelector('form')!.closest('[hidden]')).toBeNull(); @@ -201,7 +204,7 @@ describe('Ficha individual desde Seguimiento CaCu', () => { it('muestra ausencia de ficha sin asignar a otro paciente los antecedentes anteriores', () => { expect(abrir().textContent).toContain('Antecedente de tamizaje cervical'); - const tablaIlustrativa = root.querySelector('app-paciente-riesgo-tabla table')!.textContent; + const riesgoNoDisponible = root.querySelector('app-paciente-riesgo-tabla')!.textContent; volver(); const detail = abrir(2); expect(detail.textContent).toContain(pacientes[2].id_seudonimo); @@ -211,7 +214,8 @@ describe('Ficha individual desde Seguimiento CaCu', () => { expect(detail.textContent).not.toContain('Colposcopia (demostración)'); expect(detail.textContent).toContain('Normal'); // Received study is still available. expect(detail.textContent).not.toContain('ficha sintética'); - expect(detail.querySelector('app-paciente-riesgo-tabla table')!.textContent).toBe(tablaIlustrativa); + expect(detail.querySelector('app-paciente-riesgo-tabla')!.textContent).toBe(riesgoNoDisponible); + expect(detail.querySelector('app-paciente-riesgo-tabla table')).toBeNull(); expect(detail.querySelectorAll('app-paciente-riesgo-tabla [aria-selected]')).toHaveLength(0); http.expectNone(() => true); }); @@ -234,6 +238,24 @@ describe('Ficha individual desde Seguimiento CaCu', () => { http.expectNone(() => true); }); + it('monta el contrato solo por inyección de prueba y no lo conserva en la siguiente ficha', () => { + const provider = TestBed.inject(PACIENTE_RIESGO_PROVIDER); + const obtener = vi.spyOn(provider, 'obtener').mockReturnValueOnce(of(riesgoCacuEjemplo())); + try { + const detail = abrir(); + const tarjeta = detail.querySelector('app-paciente-riesgo-tabla')!; + expect(tarjeta.textContent).toContain('Información simulada'); + expect(tarjeta.querySelectorAll('tbody tr')).toHaveLength(3); + expect(tarjeta.textContent).not.toContain(pacientes[0].id_seudonimo); + expect(obtener).toHaveBeenCalledExactlyOnceWith(); + volver(); + const otra = abrir(1); + expect(otra.textContent).toContain('Riesgo individual no disponible para esta paciente.'); + expect(otra.querySelector('app-paciente-riesgo-tabla table')).toBeNull(); + http.expectNone(() => true); + } finally { obtener.mockRestore(); } + }); + it('distingue fuentes, nulos, falsos, ceros y listas sin registros sin inferir condiciones', () => { let detail = abrir(); expect(detail.textContent).toContain('Últimos resultados'); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts index 94fa339..dfdb390 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts @@ -218,8 +218,9 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => { it('agrega sin fixture, conserva las tres secciones al navegar y aísla pacientes', async () => { abrir(2); - const tablaIlustrativa = root.querySelector('app-paciente-riesgo-tabla table')!.textContent; - expect(root.querySelectorAll('app-paciente-riesgo-tabla thead th')).toHaveLength(6); + const riesgoNoDisponible = root.querySelector('app-paciente-riesgo-tabla')!.textContent; + expect(root.querySelector('app-paciente-riesgo-tabla table')).toBeNull(); + expect(riesgoNoDisponible).toContain('Riesgo individual no disponible para esta paciente.'); expect(root.textContent).toContain('Información no disponible'); for (const tipo of acciones) { const { ref } = await abrirDialogo(tipo.texto); @@ -230,7 +231,7 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => { await confirmar(); } expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3); - expect(root.querySelector('app-paciente-riesgo-tabla table')!.textContent).toBe(tablaIlustrativa); + expect(root.querySelector('app-paciente-riesgo-tabla')!.textContent).toBe(riesgoNoDisponible); expect(root.textContent).toContain('Recomendaciones no disponibles'); volver(); abrir(0); expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(0); @@ -257,7 +258,8 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => { expect(root.textContent).toContain('Último resultado de VPH'); expect(root.textContent).toContain('NEGATIVO'); expect(root.textContent).toContain('VPH 16/18 detectado'); - expect(root.textContent).toContain('Valores ilustrativos · Sin evaluación clínica'); + expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.'); + expect(root.querySelector('app-paciente-riesgo-tabla table')).toBeNull(); http.expectNone(() => true); }); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index 49cfa6b..a5e3c7e 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -1,37 +1,68 @@ -

Estimaciones de riesgo

-

Valores ilustrativos · Sin evaluación clínica

+

Riesgo individual CaCu

@let lectura = estado(); @switch (lectura.tipo) { - @case ('cargando') {

Cargando estimaciones de riesgo…

} - @case ('vacio') {

Sin estimaciones de riesgo disponibles.

} - @case ('no-disponible') {

Estimaciones de riesgo no disponibles.

} - @case ('error') {

No se pudieron cargar las estimaciones de riesgo.

} + @case ('cargando') {

Cargando riesgo individual…

} + @case ('no-disponible') { +

Riesgo individual no disponible para esta paciente.

+

La consulta de riesgo individual aún no está habilitada.

+ } + @case ('error') {

No se pudo validar o cargar el riesgo individual.

} @case ('disponible') { -
- - - - - - - - - - - - @for (fila of lectura.datos.filas; track fila.id) { - - - - - - - - - } - -
Ejemplos ilustrativos de estimaciones de riesgo
Antecedentes precolposcopiaAntecedentes poscolposcopiaResultado VPH actualCitología actualRiesgo inmediato CIN3+ (%)Riesgo CIN3+ a 5 años (%)
{{ fila.antecedentesPrecolposcopia }}{{ fila.antecedentesPoscolposcopia }}{{ fila.resultadoVphActual }}{{ fila.citologiaActual }}{{ fila.riesgoInmediatoPorcentaje === null ? 'No disponible' : (fila.riesgoInmediatoPorcentaje | number:'1.1-2') + ' %' }}{{ fila.riesgoCin3A5AnosPorcentaje === null ? 'No disponible' : (fila.riesgoCin3A5AnosPorcentaje | number:'1.1-2') + ' %' }}
-
+

Información simulada · Entorno DEV · Sin evaluación clínica

+ @if (lectura.datos.cohorte; as cohorte) { +
Cohorte
+ +
+ Variables del modelo PIMM +

Códigos técnicos del modelo; no constituyen un diagnóstico.

+ +
+ } @else { +

Sin membresía en la cohorte vigente.

+ } + @if (lectura.datos.riesgo; as riesgo) { +
Modelo y evaluación
+ + @if (riesgo.horizontes.length) { +
+ + + + + + + + + + @for (h of riesgo.horizontes; track h.horizonte_anios) { + + + + + + + } + +
Probabilidades simuladas por horizonte desde la fecha índice
Horizonte (años)Probabilidad (%)Intervalo de confianza (%)Estado de evaluación
{{ h.horizonte_anios }}{{ h.probabilidad * 100 | number:'1.0-4' }} %@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }{{ h.estado === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}
+
+ } @else {

Sin horizontes evaluados en el lote vigente.

} + } @else {

Sin riesgo disponible: no hay lote vigente.

} } }

Recomendaciones no disponibles.

diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss index b5b49a3..90a76f3 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss @@ -1,15 +1,20 @@ :host { display: block; min-width: 0; max-width: 100%; } h4 { margin-block: 0 .5rem; font-size: 1.05rem; } -.illustrative-label, .recommendations { color: var(--issste-text-secondary); font-size: .9rem; margin-block: .5rem 1rem; } +h5 { margin-block: 1rem .5rem; font-size: 1rem; } +.simulated-label { border-inline-start: 3px solid var(--issste-accent); padding: .75rem; font-weight: 600; } +.availability, .recommendations { color: var(--issste-text-secondary); font-size: .9rem; margin-block: .5rem 1rem; } +.metadata { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 13rem), 1fr)); gap: 1rem; } +.metadata div { min-width: 0; } +dt { color: var(--issste-text-secondary); font-size: .9rem; } +dd { margin: .3rem 0 0; overflow-wrap: anywhere; } +summary { cursor: pointer; padding-block: .75rem; } .risk-scroll { width: 100%; min-width: 0; max-width: 100%; max-height: 28rem; overflow: auto; border: 1px solid var(--issste-border); border-radius: .5rem; box-sizing: border-box; } -.risk-scroll:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; } -table { width: 100%; min-width: 58rem; border-collapse: separate; border-spacing: 0; text-align: start; font-size: .9rem; } +.risk-scroll:focus-visible, summary:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; } +table { width: 100%; min-width: 36rem; border-collapse: separate; border-spacing: 0; text-align: start; font-size: .9rem; } caption { text-align: start; padding: .75rem; color: var(--issste-text-secondary); } -th, td { padding: .85rem .75rem; vertical-align: top; border-bottom: 1px solid var(--issste-border); overflow-wrap: break-word; } -th { position: sticky; top: 0; background: var(--issste-background, var(--issste-surface)); font-weight: 600; z-index: 1; } -th:nth-child(-n+2) { min-width: 10rem; } -th:nth-child(n+3) { min-width: 7rem; } -td { background: var(--issste-surface); } -tbody tr:last-child td { border-bottom: 0; } -.percentage { font-variant-numeric: tabular-nums; white-space: nowrap; } +th, td { padding: .85rem .75rem; vertical-align: top; border-bottom: 1px solid var(--issste-border); overflow-wrap: anywhere; } +thead th { position: sticky; top: 0; background: var(--issste-background, var(--issste-surface)); font-weight: 600; z-index: 1; } +tbody th, td { background: var(--issste-surface); } +tbody tr:last-child > * { border-bottom: 0; } +.percentage, .interval { font-variant-numeric: tabular-nums; white-space: nowrap; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts index 065729e..ed650ff 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -1,6 +1,7 @@ import { Component, inject } from '@angular/core'; import { DecimalPipe } from '@angular/common'; import { PacienteRiesgoState } from './paciente-riesgo.state'; +import { tieneIntervalo } from './paciente-riesgo.validation'; @Component({ selector: 'app-paciente-riesgo-tabla', @@ -11,4 +12,5 @@ import { PacienteRiesgoState } from './paciente-riesgo.state'; }) export class PacienteRiesgoTabla { readonly estado = inject(PacienteRiesgoState).estado; + readonly tieneIntervalo = tieneIntervalo; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.fixtures.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.fixtures.ts deleted file mode 100644 index ef5e3bc..0000000 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.fixtures.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { EstimacionesRiesgo } from './paciente-riesgo.models'; - -/** Invented values for layout only. Not copied from CCSM, validated or patient-derived. */ -export const ESTIMACIONES_RIESGO_ILUSTRATIVAS: EstimacionesRiesgo = { - origen: 'ilustrativo', - filas: [ - { id: 'ejemplo-1', antecedentesPrecolposcopia: 'Bajo grado', antecedentesPoscolposcopia: 'Prueba conjunta negativa', - resultadoVphActual: 'Positivo', citologiaActual: 'ASC-US / LSIL', riesgoInmediatoPorcentaje: 2.4, riesgoCin3A5AnosPorcentaje: 6.8 }, - { id: 'ejemplo-2', antecedentesPrecolposcopia: 'Bajo grado', antecedentesPoscolposcopia: 'Prueba conjunta negativa', - resultadoVphActual: 'Positivo', citologiaActual: 'NILM', riesgoInmediatoPorcentaje: 0.8, riesgoCin3A5AnosPorcentaje: 3.2 }, - { id: 'ejemplo-3', antecedentesPrecolposcopia: 'Sin información de ejemplo', antecedentesPoscolposcopia: 'Sin información de ejemplo', - resultadoVphActual: 'Negativo', citologiaActual: 'NILM', riesgoInmediatoPorcentaje: 0.2, riesgoCin3A5AnosPorcentaje: 0.9 }, - { id: 'ejemplo-4', antecedentesPrecolposcopia: 'Alto grado', antecedentesPoscolposcopia: 'Control de ejemplo', - resultadoVphActual: 'Positivo', citologiaActual: 'Alto grado', riesgoInmediatoPorcentaje: 7.6, riesgoCin3A5AnosPorcentaje: 12.4 }, - ], -}; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index 84c738b..832a217 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -1,23 +1,50 @@ import { Observable } from 'rxjs'; -/** Presentation model, not a WebApi contract or a clinical decision rule. */ -export interface EstimacionRiesgo { - id: string; - antecedentesPrecolposcopia: string; - antecedentesPoscolposcopia: string; - resultadoVphActual: string; - citologiaActual: string; - riesgoInmediatoPorcentaje: number | null; - riesgoCin3A5AnosPorcentaje: number | null; +export type EstadoEvaluacionCacu = 'preliminary' | 'final'; +export type TipoCensuraCacu = 'prevalente' | 'incidente' | 'izquierda' | 'derecha' | 'derechaBasal' | 'no_informativo'; + +export interface CohorteRiesgoCacu { + url: string; + version: string; + fecha_indice: string; + tipo_censura: TipoCensuraCacu | null; + c: number | null; + l: number | null; + r: number | null; + pap_0: string | null; + hpv_0: string | null; } -export interface EstimacionesRiesgo { - origen: 'ilustrativo'; - filas: readonly EstimacionRiesgo[]; + +export interface HorizonteRiesgoCacu { + horizonte_anios: number; + /** Transport values remain probabilities in [0, 1], never percentages. */ + probabilidad: number; + ic_bajo?: number | null; + ic_alto?: number | null; + estado: EstadoEvaluacionCacu; } -/** No patient input: these examples must never be matched to a selected patient. */ + +export interface LoteRiesgoCacu { + lote_id: number; + modelo_nombre: string; + modelo_version: string; + evaluado_en: string; + estado_lote: EstadoEvaluacionCacu; + horizontes: HorizonteRiesgoCacu[]; +} + +/** DEV-only contract from cacu_riesgo_paciente.md, 2026-10-28. */ +export interface RiesgoPacienteCacu { + simulado: true; + cohorte: CohorteRiesgoCacu | null; + riesgo: LoteRiesgoCacu | null; +} + +/** Deliberately no patient argument until secure identity resolution is authorized. */ export interface PacienteRiesgoProvider { - obtener(): Observable; + obtener(): Observable; } + export type PacienteRiesgoEstado = - | { tipo: 'cargando' | 'vacio' | 'no-disponible' | 'error' } - | { tipo: 'disponible'; datos: EstimacionesRiesgo }; + | { tipo: 'cargando' | 'no-disponible' | 'error' } + | { tipo: 'disponible'; datos: RiesgoPacienteCacu }; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts index 16b95b8..c04a30a 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts @@ -1,14 +1,8 @@ -import { Injectable, InjectionToken, inject } from '@angular/core'; -import { defer, of } from 'rxjs'; -import { ESTIMACIONES_RIESGO_ILUSTRATIVAS } from './paciente-riesgo.fixtures'; +import { InjectionToken } from '@angular/core'; +import { of } from 'rxjs'; import { PacienteRiesgoProvider } from './paciente-riesgo.models'; -@Injectable({ providedIn: 'root' }) -export class PacienteRiesgoIlustrativoProvider implements PacienteRiesgoProvider { - obtener() { return defer(() => of(structuredClone(ESTIMACIONES_RIESGO_ILUSTRATIVAS))); } -} - -// Future adapters can replace this token; no HTTP route or patient matching is assumed. +// No HTTP, fixtures or identity conversion. A real adapter requires separate authorization. export const PACIENTE_RIESGO_PROVIDER = new InjectionToken('PacienteRiesgoProvider', { - providedIn: 'root', factory: () => inject(PacienteRiesgoIlustrativoProvider), + providedIn: 'root', factory: () => ({ obtener: () => of(null) }), }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts index affe99c..1cee25a 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -2,26 +2,12 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { of, Subject, throwError } from 'rxjs'; -import { ESTIMACIONES_RIESGO_ILUSTRATIVAS } from './paciente-riesgo.fixtures'; -import { EstimacionesRiesgo, PacienteRiesgoProvider } from './paciente-riesgo.models'; -import { PACIENTE_RIESGO_PROVIDER, PacienteRiesgoIlustrativoProvider } from './paciente-riesgo.provider'; +import { PacienteRiesgoProvider } from './paciente-riesgo.models'; +import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; +import { riesgoCacuEjemplo } from './paciente-riesgo.testing'; import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; -describe('P0-C.2: proveedor ilustrativo independiente', () => { - it('lee sin HttpClient ni paciente y devuelve copias independientes del fixture', () => { - const provider = TestBed.inject(PacienteRiesgoIlustrativoProvider); - const baseline = structuredClone(ESTIMACIONES_RIESGO_ILUSTRATIVAS); - provider.obtener().subscribe(data => { - expect(data).toEqual(baseline); - data.filas[0].riesgoInmediatoPorcentaje = 99; - }); - provider.obtener().subscribe(data => expect(data).toEqual(baseline)); - expect(ESTIMACIONES_RIESGO_ILUSTRATIVAS).toEqual(baseline); - expect(baseline.filas).toHaveLength(4); - }); -}); - -describe('P0-C.2: tabla accesible y estados de lectura', () => { +describe('RIESGO-CACU-02: presentación y aislamiento', () => { function setup(provider?: PacienteRiesgoProvider) { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), ...(provider ? [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: provider }] : [])] }); @@ -29,67 +15,137 @@ describe('P0-C.2: tabla accesible y estados de lectura', () => { fixture.detectChanges(); return fixture; } - afterEach(() => { TestBed.inject(HttpTestingController).verify(); }); - it('renderiza seis encabezados, cuatro filas sin selección y porcentajes solo ilustrativos', () => { - const f = setup(), root: HTMLElement = f.nativeElement; - expect([...root.querySelectorAll('thead th')].map(th => th.textContent)).toEqual([ - 'Antecedentes precolposcopia', 'Antecedentes poscolposcopia', 'Resultado VPH actual', 'Citología actual', - 'Riesgo inmediato CIN3+ (%)', 'Riesgo CIN3+ a 5 años (%)', - ]); - expect([...root.querySelectorAll('th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); - expect(root.querySelectorAll('tbody tr')).toHaveLength(4); - expect(root.querySelectorAll('tbody td')).toHaveLength(24); - expect(root.querySelector('caption')!.textContent).toContain('ilustrativos'); - expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-ilustrativo'); - expect(root.querySelector('#riesgo-ilustrativo')!.textContent).toBe('Valores ilustrativos · Sin evaluación clínica'); - expect(root.querySelectorAll('[aria-selected], button, a, input')).toHaveLength(0); - expect([...root.querySelectorAll('.percentage')].every(td => td.textContent!.trim().endsWith('%'))).toBe(true); - expect(root.textContent).toContain('Recomendaciones no disponibles'); + afterEach(() => { TestBed.inject(HttpTestingController).expectNone(() => true); + TestBed.inject(HttpTestingController).verify(); }); - it('contiene el desplazamiento y conserva anchos mínimos y encabezados, con foco de teclado', () => { + + it('ejecución normal sin fixtures, HTTP, identidad o controles de preview', () => { const f = setup(), root: HTMLElement = f.nativeElement; + expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.'); + expect(root.textContent).toContain('aún no está habilitada'); + expect(root.textContent).toContain('Recomendaciones no disponibles'); + expect(root.textContent).not.toMatch(/simulad|ilustrativ|modelo-cacu|CIN3|2\.4|6\.8/); + expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0); + TestBed.inject(PACIENTE_RIESGO_PROVIDER).obtener().subscribe(v => expect(v).toBeNull()); + }); + + it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => { + const data = riesgoCacuEjemplo(), obtener = vi.fn(() => of(data)); + data.riesgo!.horizontes[1].estado = 'preliminary'; + const baseline = structuredClone(data); + const f = setup({ obtener }), root: HTMLElement = f.nativeElement; + expect(obtener).toHaveBeenCalledExactlyOnceWith(); + expect(root.querySelectorAll('thead th')).toHaveLength(4); + expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); + expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3); + expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']); + expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %'); + expect(root.textContent).toContain('Final (final)'); + expect(root.textContent).toContain('Preliminar (preliminary)'); + for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', 'cacu/cohorte_vigilancia', '0.2.0', '2023-04-15', 'incidente', 'ASC-US', 'POSITIVO']) { + expect(root.textContent).toContain(value); + } + expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-simulado'); + expect(root.querySelector('#riesgo-simulado')!.textContent).toContain('Información simulada · Entorno DEV'); + expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/); + // Internal batch key stays in the contract, never in a UI label. + expect(root.textContent).not.toContain('lote_id'); + expect(data).toEqual(baseline); + }); + + it('mantiene tabla desplazable, foco de teclado y detalles técnicos accesibles', () => { + const f = setup({ obtener: () => of(riesgoCacuEjemplo()) }), root: HTMLElement = f.nativeElement; const scroll = root.querySelector('.risk-scroll')!; - expect(scroll.tabIndex).toBe(0); expect(scroll.getAttribute('role')).toBe('region'); + expect(scroll.tabIndex).toBe(0); + expect(scroll.getAttribute('role')).toBe('region'); expect(scroll.getAttribute('aria-label')).toContain('tabla desplazable'); - // jsdom verifies the responsive CSS contract; viewport geometry still needs Chrome review. expect(getComputedStyle(scroll).overflow).toBe('auto'); expect(getComputedStyle(scroll).maxWidth).toBe('100%'); - expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('58rem'); - expect(getComputedStyle(root.querySelector('th')!).position).toBe('sticky'); + expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem'); + expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky'); + expect(root.querySelector('details summary')!.textContent).toBe('Variables del modelo PIMM'); + expect(root.textContent).toContain('no constituyen un diagnóstico'); }); - it('sustituye el fixture por inyección sin calcular porcentajes ni convertir null en cero', () => { - const data = structuredClone(ESTIMACIONES_RIESGO_ILUSTRATIVAS); - data.filas = [{ ...data.filas[0], riesgoInmediatoPorcentaje: 0, riesgoCin3A5AnosPorcentaje: null }]; - const obtener = vi.fn(() => of(data)), f = setup({ obtener }); - expect(obtener).toHaveBeenCalledExactlyOnceWith(); - const cells = [...f.nativeElement.querySelectorAll('.percentage')] as HTMLElement[]; - expect(cells.map(c => c.textContent)).toEqual(['0.0 %', 'No disponible']); - TestBed.inject(HttpTestingController).expectNone(() => true); + + it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => { + const data = riesgoCacuEjemplo(); + data.riesgo!.estado_lote = 'preliminary'; + data.riesgo!.horizontes = [ + { horizonte_anios: 0.5, probabilidad: 0, ic_bajo: 0, ic_alto: 0, estado: 'preliminary' }, + { horizonte_anios: 8, probabilidad: 1, ic_bajo: null, ic_alto: 1, estado: 'final' }, + { horizonte_anios: 12.25, probabilidad: 0.00123, estado: 'final' }, + ]; + const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement; + expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']); + expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['0 %', '100 %', '0.123 %']); + expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['0 % – 0 %', 'No disponible', 'No disponible']); + expect(root.textContent).toContain('Preliminar (preliminary)'); }); - it.each([ - { data: { origen: 'ilustrativo', filas: [] } as EstimacionesRiesgo, text: 'Sin estimaciones de riesgo disponibles.' }, - { data: null, text: 'Estimaciones de riesgo no disponibles.' }, - ])('representa ausencia explícita: $text', ({ data, text }) => { + + it('preserva variables nulas y el cero basal sin convertirlos en hallazgos', () => { + const data = riesgoCacuEjemplo(); + data.cohorte = { ...data.cohorte!, c: 0, l: null, r: null, pap_0: null, hpv_0: null, tipo_censura: null }; const f = setup({ obtener: () => of(data) }); - expect(f.nativeElement.textContent).toContain(text); - expect(f.nativeElement.querySelector('table')).toBeNull(); - expect(f.nativeElement.textContent).toContain('Recomendaciones no disponibles'); + const valores = [...f.nativeElement.querySelectorAll('details dd')].map((d: any) => d.textContent); + expect(valores).toEqual(['No disponible', '0', 'No disponible', 'No disponible', 'No disponible', 'No disponible']); + expect(f.nativeElement.textContent).not.toMatch(/undefined|null/); }); - it('distingue carga y error sin filtrar mensajes internos, y cancela al desmontarse', () => { - const source = new Subject(); - const f = setup({ obtener: () => source }); - expect(f.nativeElement.textContent).toContain('Cargando estimaciones de riesgo'); - source.error(new Error('private')); f.detectChanges(); - expect(f.nativeElement.querySelector('[role="alert"]')!.textContent).toContain('No se pudieron cargar'); - expect(f.nativeElement.textContent).not.toContain('private'); + + it.each(['cohorte', 'riesgo', 'horizontes', 'ambos'])('distingue ausencia de %s', caso => { + const data = riesgoCacuEjemplo(); + if (caso === 'cohorte' || caso === 'ambos') data.cohorte = null; + if (caso === 'riesgo' || caso === 'ambos') data.riesgo = null; + if (caso === 'horizontes') data.riesgo!.horizontes = []; + const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement; + if (!data.cohorte) expect(root.textContent).toContain('Sin membresía en la cohorte vigente'); + if (!data.riesgo) expect(root.textContent).toContain('Sin riesgo disponible: no hay lote vigente'); + if (caso === 'horizontes') expect(root.textContent).toContain('Sin horizontes evaluados'); + if (caso !== 'cohorte') expect(root.querySelector('table')).toBeNull(); + expect(root.textContent).toContain('Información simulada'); + expect(root.textContent).toContain('Recomendaciones no disponibles'); + }); + + it.each([false, 'true', undefined])('no expone una respuesta no simulada (%s)', simulado => { + const data = { ...riesgoCacuEjemplo(), simulado }; + const f = setup({ obtener: () => of(data) }); + expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull(); + expect(f.nativeElement.textContent).not.toContain('modelo-cacu'); expect(f.nativeElement.querySelector('table')).toBeNull(); + }); + + it('rechaza probabilidades inválidas sin presentar parcialmente la cohorte', () => { + const data = riesgoCacuEjemplo(); data.riesgo!.horizontes[0].probabilidad = 12; + const f = setup({ obtener: () => of(data) }); + expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull(); + expect(f.nativeElement.querySelectorAll('table, dl')).toHaveLength(0); + }); + + it('representa carga y cancela la suscripción al desmontarse', () => { + const source = new Subject(), f = setup({ obtener: () => source }); + expect(f.nativeElement.textContent).toContain('Cargando riesgo individual'); + expect(source.observed).toBe(true); f.destroy(); expect(source.observed).toBe(false); }); - it('un error inmediato del adaptador también mantiene las recomendaciones ausentes', () => { - const f = setup({ obtener: () => throwError(() => new Error('private')) }); + + it('aísla estado y fixture entre instancias sin reutilizar información', () => { + const source = new Subject(), f = setup({ obtener: () => source }); + const data = riesgoCacuEjemplo(); source.next(data); f.detectChanges(); + data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges(); + expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %'); + f.destroy(); + const otra = TestBed.createComponent(PacienteRiesgoTabla); otra.detectChanges(); + expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual'); + expect(otra.nativeElement.querySelector('table')).toBeNull(); + expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08); + otra.destroy(); expect(source.observed).toBe(false); + }); + + it.each(['observable', 'sincrono'])('oculta detalles internos del error %s', tipo => { + const error = new Error('private pac_id=4821'); + const f = setup({ obtener: () => { if (tipo === 'sincrono') throw error; return throwError(() => error); } }); + expect(f.nativeElement.querySelector('[role="alert"]')!.textContent).toContain('No se pudo validar o cargar'); + expect(f.nativeElement.textContent).not.toMatch(/private|4821|pac_id/); expect(f.nativeElement.textContent).toContain('Recomendaciones no disponibles'); - expect(f.nativeElement.textContent).not.toContain('private'); - TestBed.inject(HttpTestingController).expectNone(() => true); }); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts index 23efcd8..5a109fa 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts @@ -1,14 +1,16 @@ import { inject, Injectable } from '@angular/core'; import { toSignal } from '@angular/core/rxjs-interop'; -import { catchError, map, of } from 'rxjs'; +import { catchError, defer, map, of } from 'rxjs'; import { PacienteRiesgoEstado } from './paciente-riesgo.models'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; +import { riesgoPacienteResponse } from './paciente-riesgo.validation'; @Injectable() export class PacienteRiesgoState { - readonly estado = toSignal(inject(PACIENTE_RIESGO_PROVIDER).obtener().pipe( + private readonly provider = inject(PACIENTE_RIESGO_PROVIDER); + readonly estado = toSignal(defer(() => this.provider.obtener()).pipe( map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' } - : datos.filas.length ? { tipo: 'disponible', datos } : { tipo: 'vacio' }), + : { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }), catchError(() => of({ tipo: 'error' })), ), { initialValue: { tipo: 'cargando' } as PacienteRiesgoEstado }); } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts new file mode 100644 index 0000000..511c042 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts @@ -0,0 +1,21 @@ +import { RiesgoPacienteCacu } from './paciente-riesgo.models'; + +/** TEST ONLY. Exact external contract example; never belongs to the selected patient. */ +export function riesgoCacuEjemplo(): RiesgoPacienteCacu { + return { + simulado: true, + cohorte: { + url: 'cacu/cohorte_vigilancia', version: '0.2.0', fecha_indice: '2023-04-15', + tipo_censura: 'incidente', c: 0, l: 0.164, r: 0.548, pap_0: 'ASC-US', hpv_0: 'POSITIVO', + }, + riesgo: { + lote_id: 12, modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', + evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', + horizontes: [ + { horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12, estado: 'final' }, + { horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28, estado: 'final' }, + { horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44, estado: 'final' }, + ], + }, + }; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts new file mode 100644 index 0000000..7716d4a --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts @@ -0,0 +1,123 @@ +import { riesgoCacuEjemplo } from './paciente-riesgo.testing'; +import { riesgoPacienteResponse, tieneIntervalo } from './paciente-riesgo.validation'; +import { TipoCensuraCacu } from './paciente-riesgo.models'; + +describe('RIESGO-CACU-02: frontera del contrato DEV', () => { + it('conserva todos los campos del ejemplo externo y copia los objetos', () => { + const entrada = riesgoCacuEjemplo(); + const salida = riesgoPacienteResponse(entrada); + expect(salida).toEqual(entrada); + salida.riesgo!.horizontes[0].probabilidad = 0; + salida.cohorte!.c = -999; + expect(entrada).toEqual(riesgoCacuEjemplo()); + }); + + it('admite campos aditivos sin eliminarlos ni renombrarlos', () => { + const entrada = { ...riesgoCacuEjemplo(), futuro: { estado: null } }; + expect(riesgoPacienteResponse(entrada)).toEqual(entrada); + }); + + it.each(['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo', null])( + 'preserva tipo_censura %s sin inferir etiquetas clínicas', tipo => { + const entrada = riesgoCacuEjemplo(); + entrada.cohorte!.tipo_censura = tipo as TipoCensuraCacu | null; + expect(riesgoPacienteResponse(entrada).cohorte!.tipo_censura).toBe(tipo); + }, + ); + + it('preserva los nulos independientes y el sentinel basal del contrato', () => { + const entrada = riesgoCacuEjemplo(); + entrada.cohorte = { ...entrada.cohorte!, tipo_censura: null, c: -999, l: null, r: null, pap_0: null, hpv_0: null }; + expect(riesgoPacienteResponse(entrada)).toEqual(entrada); + entrada.riesgo = null; + entrada.cohorte.c = null; + expect(riesgoPacienteResponse(entrada)).toEqual(entrada); + entrada.cohorte = null; + expect(riesgoPacienteResponse(entrada)).toEqual({ simulado: true, cohorte: null, riesgo: null }); + }); + + it('no impone dependencia entre cohorte nullable y riesgo nullable', () => { + const entrada = riesgoCacuEjemplo(); + entrada.cohorte = null; + expect(riesgoPacienteResponse(entrada)).toEqual(entrada); + }); + + it.each([[], [2.5], [0, 0.5, 7, 12]])('acepta horizontes dinámicos/parciales/vacíos %j', (...anios: number[]) => { + const entrada = riesgoCacuEjemplo(); + entrada.riesgo!.horizontes = anios.map((horizonte_anios, i) => ({ + horizonte_anios, probabilidad: i % 2, estado: i % 2 ? 'preliminary' : 'final', + })); + expect(riesgoPacienteResponse(entrada)).toEqual(entrada); + }); + + it.each([ + {}, { ic_bajo: null, ic_alto: null }, { ic_bajo: 0, ic_alto: null }, + { ic_bajo: null, ic_alto: 1 }, { ic_bajo: 0 }, { ic_alto: 1 }, + ])('conserva IC incompletos sin generar límites: %j', limites => { + const entrada = riesgoCacuEjemplo(); + entrada.riesgo!.horizontes = [{ horizonte_anios: 2, probabilidad: 0.5, estado: 'preliminary', ...limites }]; + const salida = riesgoPacienteResponse(entrada); + expect(salida).toEqual(entrada); + expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(false); + }); + + it.each([0, 1])('acepta probabilidad y límites extremos %s sin convertir el transporte a porcentaje', p => { + const entrada = riesgoCacuEjemplo(); + entrada.riesgo!.estado_lote = 'preliminary'; + entrada.riesgo!.horizontes = [{ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p, estado: 'preliminary' }]; + const salida = riesgoPacienteResponse(entrada); + expect(salida).toEqual(entrada); + expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(true); + }); + + const invalidos: [string, (v: any) => void][] = [ + ['no simulado', v => v.simulado = false], + ['simulado string', v => v.simulado = 'true'], + ['sin simulado', v => delete v.simulado], + ['sin cohorte', v => delete v.cohorte], + ['sin riesgo', v => delete v.riesgo], + ['cohorte lista', v => v.cohorte = []], + ['URL ajena', v => v.cohorte.url = 'otra'], + ['versión ausente', v => delete v.cohorte.version], + ['fecha inválida', v => v.cohorte.fecha_indice = '2026-02-30'], + ['enum PIMM desconocido', v => v.cohorte.tipo_censura = 'diagnostico'], + ['basal string', v => v.cohorte.c = '0'], + ['variable no finita', v => v.cohorte.l = Infinity], + ['variable omitida', v => delete v.cohorte.r], + ['pap no textual', v => v.cohorte.pap_0 = 5], + ['hpv no textual', v => v.cohorte.hpv_0 = false], + ['lote fraccionario', v => v.riesgo.lote_id = 1.5], + ['lote string', v => v.riesgo.lote_id = '12'], + ['modelo omitido', v => delete v.riesgo.modelo_nombre], + ['versión no textual', v => v.riesgo.modelo_version = 2], + ['evaluación fecha imposible', v => v.riesgo.evaluado_en = '2026-02-30T00:00:00Z'], + ['evaluación sin UTC', v => v.riesgo.evaluado_en = '2026-10-01T00:00:00-06:00'], + ['hora inválida', v => v.riesgo.evaluado_en = '2026-10-01T25:00:00Z'], + ['estado lote desconocido', v => v.riesgo.estado_lote = 'confirmado'], + ['sin horizontes', v => delete v.riesgo.horizontes], + ['horizontes nulos', v => v.riesgo.horizontes = null], + ['horizonte nulo', v => v.riesgo.horizontes[0] = null], + ['horizonte string', v => v.riesgo.horizontes[0].horizonte_anios = '1'], + ['horizonte no finito', v => v.riesgo.horizontes[0].horizonte_anios = NaN], + ['horizontes desordenados', v => v.riesgo.horizontes.reverse()], + ['horizontes repetidos', v => v.riesgo.horizontes[1].horizonte_anios = 1], + ['probabilidad negativa', v => v.riesgo.horizontes[0].probabilidad = -0.01], + ['probabilidad mayor a uno', v => v.riesgo.horizontes[0].probabilidad = 1.01], + ['probabilidad string', v => v.riesgo.horizontes[0].probabilidad = '0.08'], + ['probabilidad nula', v => v.riesgo.horizontes[0].probabilidad = null], + ['probabilidad no finita', v => v.riesgo.horizontes[0].probabilidad = NaN], + ['estado horizonte inválido', v => v.riesgo.horizontes[0].estado = 'FINAL'], + ['IC bajo inválido', v => v.riesgo.horizontes[0].ic_bajo = -0.01], + ['IC alto inválido', v => v.riesgo.horizontes[0].ic_alto = 1.01], + ['IC string', v => v.riesgo.horizontes[0].ic_alto = '0.12'], + ['IC invertido', v => Object.assign(v.riesgo.horizontes[0], { ic_bajo: 0.12, ic_alto: 0.05 })], + ['IC fuera de probabilidad', v => v.riesgo.horizontes[0].ic_alto = 0.07], + ]; + it.each(invalidos)('rechaza %s sin coerción ni datos parciales', (_, mutar) => { + const entrada = riesgoCacuEjemplo(); mutar(entrada); + expect(() => riesgoPacienteResponse(entrada)).toThrow('Respuesta de riesgo individual DEV inválida'); + }); + it.each([null, undefined, [], 0, 'respuesta'])('rechaza cuerpo inválido %j', entrada => { + expect(() => riesgoPacienteResponse(entrada)).toThrow(); + }); +}); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts new file mode 100644 index 0000000..e26ba5a --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts @@ -0,0 +1,58 @@ +import { isoDate } from '../cacu-seguimiento.models'; +import { HorizonteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models'; + +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); +const nullableNumber = (v: unknown) => v === null || finite(v); +const nullableText = (v: unknown) => v === null || typeof v === 'string'; +const text = (v: unknown) => typeof v === 'string'; +const estado = (v: unknown) => v === 'preliminary' || v === 'final'; +const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1; +const censuras = ['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo']; + +function utcTimestamp(v: unknown) { + return typeof v === 'string' + && /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|\+00:00)$/.test(v) + && isoDate(v.slice(0, 10)) && Number.isFinite(Date.parse(v)); +} + +function cohorteValida(v: unknown) { + return v === null || record(v) + && v['url'] === 'cacu/cohorte_vigilancia' && text(v['version']) && isoDate(v['fecha_indice']) + && (v['tipo_censura'] === null || censuras.includes(v['tipo_censura'] as string)) + && nullableNumber(v['c']) && nullableNumber(v['l']) && nullableNumber(v['r']) + && nullableText(v['pap_0']) && nullableText(v['hpv_0']); +} + +function horizonteValido(v: unknown) { + if (!record(v) || !finite(v['horizonte_anios']) || !probability(v['probabilidad']) || !estado(v['estado'])) return false; + for (const key of ['ic_bajo', 'ic_alto']) { + if (Object.hasOwn(v, key) && v[key] !== null && !probability(v[key])) return false; + } + // Missing/null endpoints are preserved. A complete interval must contain the probability. + return !(probability(v['ic_bajo']) && probability(v['ic_alto'])) + || v['ic_bajo'] <= v['probabilidad'] && v['probabilidad'] <= v['ic_alto']; +} + +function riesgoValido(v: unknown) { + if (v === null) return true; + if (!record(v) || !Number.isSafeInteger(v['lote_id']) || !text(v['modelo_nombre']) || !text(v['modelo_version']) + || !utcTimestamp(v['evaluado_en']) || !estado(v['estado_lote']) || !Array.isArray(v['horizontes'])) return false; + const horizontes = v['horizontes']; + return horizontes.every(horizonteValido) + && horizontes.every((h, i) => i === 0 || horizontes[i - 1]['horizonte_anios'] < h['horizonte_anios']); +} + +/** Validate at the boundary. Reject real data, coercions and malformed fields; retain additive fields. */ +export function riesgoPacienteResponse(v: unknown): RiesgoPacienteCacu { + if (!record(v) || v['simulado'] !== true || !cohorteValida(v['cohorte']) || !riesgoValido(v['riesgo'])) { + throw new Error('Respuesta de riesgo individual DEV inválida'); + } + return structuredClone(v) as unknown as RiesgoPacienteCacu; +} + +/** Presentation helper: an incomplete interval must never become a fabricated range. */ +export function tieneIntervalo(h: HorizonteRiesgoCacu): boolean { + return probability(h.ic_bajo) && probability(h.ic_alto) + && h.ic_bajo <= h.probabilidad && h.probabilidad <= h.ic_alto; +} diff --git a/src/app/shared/plotly/plotly-chart.spec.ts b/src/app/shared/plotly/plotly-chart.spec.ts index 75b325d..52dfadd 100644 --- a/src/app/shared/plotly/plotly-chart.spec.ts +++ b/src/app/shared/plotly/plotly-chart.spec.ts @@ -26,6 +26,27 @@ describe('PlotlyChart lifecycle', () => { fixture.destroy(); expect(disconnect).toHaveBeenCalled(); expect(mocks.purge).toHaveBeenCalled(); vi.unstubAllGlobals(); }); + it.each([[false, true], [true, false]])('animated respeta prefers-reduced-motion=%s (transición: %s) y es opcional', async (reduce, transition) => { + vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({ matches: reduce })); + const settle = async () => { await fixture.whenStable(); for (let i = 0; i < 40; i++) await Promise.resolve(); }; + const fixture = TestBed.createComponent(PlotlyChart); + fixture.componentRef.setInput('animated', true); + fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [1] }], layout: {} }); + fixture.detectChanges(); await settle(); + fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [2] }], layout: {} }); + fixture.detectChanges(); await settle(); + expect(mocks.react).toHaveBeenCalledTimes(2); + expect(mocks.react.mock.calls[1][2]['transition'] !== undefined).toBe(transition); + fixture.destroy(); vi.unstubAllGlobals(); + }); + it('sin animated las actualizaciones no llevan transición', async () => { + const fixture = TestBed.createComponent(PlotlyChart); + fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [1] }], layout: {} }); + fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 40; i++) await Promise.resolve(); + fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [2] }], layout: {} }); + fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 40; i++) await Promise.resolve(); + expect(mocks.react.mock.calls[1][2]['transition']).toBeUndefined(); fixture.destroy(); + }); it('muestra error asíncrono y se recupera con reintento', async () => { mocks.react.mockRejectedValueOnce(new Error('render failed')); const fixture = TestBed.createComponent(PlotlyChart); diff --git a/src/app/shared/plotly/plotly-chart.ts b/src/app/shared/plotly/plotly-chart.ts index 22925d3..2212a1b 100644 --- a/src/app/shared/plotly/plotly-chart.ts +++ b/src/app/shared/plotly/plotly-chart.ts @@ -5,6 +5,10 @@ import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; import { PlotlyController } from './plotly-controller'; import { PLOTLY_LOADER } from './plotly-runtime'; +function prefersReducedMotion(): boolean { + return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches; +} + @Component({ selector: 'app-plotly-chart', imports: [MatButtonModule, MatProgressBarModule], @@ -27,6 +31,8 @@ import { PLOTLY_LOADER } from './plotly-runtime'; export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { @Input() showNotes = true; @Input() label = 'Figura estadística'; + // Opt-in: updates of the same visible figure move smoothly instead of redrawing. + @Input() animated = false; @Input({ required: true }) figure!: PlotlyFigure; @ViewChild('host', { static: true }) host!: ElementRef; readonly renderError = output(); @@ -57,7 +63,7 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { this.controller = new PlotlyController(this.host.nativeElement, this.loadPlotly, state => { this.status.set(state); if (state === 'error') this.renderError.emit(); - }, event => this.plotClick.emit(event)); + }, event => this.plotClick.emit(event), { animate: () => this.animated && !prefersReducedMotion() }); if (typeof ResizeObserver !== 'undefined') { this.observer = new ResizeObserver(this.windowResize); this.observer.observe(this.host.nativeElement); diff --git a/src/app/shared/plotly/plotly-controller.spec.ts b/src/app/shared/plotly/plotly-controller.spec.ts index da71695..0fb746c 100644 --- a/src/app/shared/plotly/plotly-controller.spec.ts +++ b/src/app/shared/plotly/plotly-controller.spec.ts @@ -1,6 +1,6 @@ import { syntheticFigures } from '../../features/indicadores/indicadores.synthetic-fixtures'; import { vi } from 'vitest'; -import { PlotlyController } from './plotly-controller'; +import { cubicInOut, pieFrame, piesInterpolable, PlotlyController, TRANSITION_MS } from './plotly-controller'; import { PlotlyRuntime } from './plotly-runtime'; import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; function deferred() { @@ -151,6 +151,33 @@ describe('PlotlyController con Plotly instalado', () => { runtime = (module.default ?? module) as typeof runtime; } finally { canvas.mockRestore(); } }); + it('Plotly real acepta las transiciones de barras y los fotogramas de pies y termina en la figura destino', async () => { + const host = document.createElement('div'); + document.body.append(host); + let clock = 0, controller: PlotlyController | undefined; + const ready = () => new Promise((resolve, reject) => { pending = { resolve, reject }; }); + let pending!: { resolve: () => void; reject: (e: Error) => void }; + try { + controller = new PlotlyController(host, () => Promise.resolve(runtime), state => { + if (state === 'ready') pending?.resolve(); + if (state === 'error') pending?.reject(new Error('Plotly transition failed')); + }, undefined, { animate: () => true, nextFrame: () => Promise.resolve(clock += 150) }); + const bars = (x: number[]): PlotlyFigure => ({ data: x.map((v, i) => ({ type: 'bar', uid: 'c' + i, orientation: 'h', x: [v], y: ['A'] })), layout: { barmode: 'stack' } }); + let done = ready(); controller.setFigure(bars([40, 60])); await done; + done = ready(); controller.setFigure(bars([0, 60])); await done; + expect((host as unknown as { data: { x: number[] }[] }).data.map(t => t.x)).toEqual([[0], [60]]); + controller.destroy(); controller = undefined; + const pies = (values: number[]): PlotlyFigure => ({ data: [{ type: 'pie', name: 'grupos', values, marker: { colors: ['rgba(1,2,3,1)', 'rgba(4,5,6,1)'] } }], layout: {} }); + controller = new PlotlyController(host, () => Promise.resolve(runtime), state => { + if (state === 'ready') pending?.resolve(); + if (state === 'error') pending?.reject(new Error('Plotly pie frames failed')); + }, undefined, { animate: () => true, nextFrame: () => Promise.resolve(clock += 150) }); + done = ready(); controller.setFigure(pies([10, 0])); await done; + done = ready(); controller.setFigure(pies([3, 7])); await done; + expect((host as unknown as { data: { values: number[] }[] }).data[0].values).toEqual([3, 7]); + expect(host.style.visibility).toBe('visible'); + } finally { controller?.destroy(); host.remove(); } + }); it('usa propiedades admitidas por el esquema de Plotly 4.1.2', () => { expect(runtime.version).toBe('4.1.2'); const config = runtime.PlotSchema.get().config; @@ -212,3 +239,183 @@ describe('PlotlyController con Plotly instalado', () => { }); }); + +describe('PlotlyController transiciones opcionales', () => { + const pie = (values: number[], alpha = 1): PlotlyFigure => ({ data: [ + { type: 'pie', name: 'centro', values: [1], text: ['Total'] }, + { type: 'pie', name: 'grupos', values, text: values.map(String), marker: { colors: values.map(() => `rgba(10,20,30,${alpha})`) } }, + ], layout: { height: 440 } }); + const bars = (x: number[]): PlotlyFigure => ({ data: x.map((v, i) => ({ type: 'bar', uid: 'c' + i, x: [v], y: ['A'] })), layout: {} }); + let host: HTMLElement, plotly: PlotlyRuntime, clock: number, animate: boolean; + let state: ReturnType void>>; + const nextFrame = () => Promise.resolve(clock += 100); + beforeEach(() => { + host = document.createElement('div'); clock = 0; animate = true; + plotly = { react: vi.fn().mockResolvedValue(undefined), purge: vi.fn(), Plots: { resize: vi.fn().mockResolvedValue(undefined) }, + addFrames: vi.fn().mockResolvedValue(undefined), deleteFrames: vi.fn().mockResolvedValue(undefined) }; + state = vi.fn(); + }); + const controller = () => new PlotlyController(host, () => Promise.resolve(plotly), state, undefined, { animate: () => animate, nextFrame }); + async function settleLong() { for (let i = 0; i < 80; i++) await Promise.resolve(); } + + it('easing cubic-in-out y fotogramas intermedios de pies: valores y alfa se mueven, textos esperan', () => { + expect([0, .5, 1].map(cubicInOut)).toEqual([0, .5, 1]); + expect(cubicInOut(.25)).toBeLessThan(.25); expect(cubicInOut(.75)).toBeGreaterThan(.75); + const from = pie([10, 0], .3), to = pie([4, 6], 1); + expect(piesInterpolable(from, to)).toBe(true); + expect(piesInterpolable(from, bars([1]))).toBe(false); + expect(piesInterpolable(from, { ...to, data: [to.data[0]] })).toBe(false); + const half = pieFrame(from, to, .5); + expect(half.data[0]['values']).toEqual([1]); + expect(half.data[0]['text']).toEqual(['']); + expect(half.data[1]['values']).toEqual([7, 3]); expect(half.data[1]['text']).toEqual(['', '']); + expect((half.data[1]['marker'] as { colors: string[] }).colors).toEqual(['rgba(10,20,30,0.65)', 'rgba(10,20,30,0.65)']); + expect(to.data[1]['values']).toEqual([4, 6]); + for (const trace of half.data) { + expect(trace['textinfo']).toBe('none'); expect(trace['hoverinfo']).toBe('skip'); + expect(trace['hovertemplate']).toBeNull(); expect(trace['customdata']).toEqual([]); + } + // Same values, only dimming (a selection that keeps the totals): colors move, texts stay. + const dimmed = pieFrame(pie([4, 6], .3), pie([4, 6], 1), .5); + expect(dimmed.data[1]['values']).toEqual([4, 6]); expect(dimmed.data[1]['text']).toEqual(['4', '6']); + expect((dimmed.data[1]['marker'] as { colors: string[] }).colors).toEqual(['rgba(10,20,30,0.65)', 'rgba(10,20,30,0.65)']); + expect(pieFrame(pie([4, 6]), pie([4, 6]), .5).data[1]).toEqual(pie([4, 6]).data[1]); + }); + it('la dona interpola en varios react sin ocultar el host ni pasar por carga, y termina en la figura exacta', async () => { + const c = controller(); + c.setFigure(pie([10, 0])); await settleLong(); + expect(host.style.visibility).toBe('visible'); state.mockClear(); vi.mocked(plotly.react).mockClear(); + const target = pie([4, 6]); + c.setFigure(target); + expect(host.style.visibility).toBe('visible'); expect(state).not.toHaveBeenCalledWith('loading'); + await settleLong(); + const calls = vi.mocked(plotly.react).mock.calls; + // 100 ms per frame over TRANSITION_MS, plus the exact final figure. + expect(calls.length).toBe(Math.ceil(TRANSITION_MS / 100)); + const values = calls.map(call => call[1][1]['values'] as number[]); + expect(values[0][0]).toBeLessThan(10); expect(values[0][0]).toBeGreaterThan(4); + for (let i = 1; i < values.length - 1; i++) expect(values[i][0]).toBeLessThan(values[i - 1][0]); + expect(calls.at(-1)![1]).toEqual(target.data); expect(calls.at(-1)![2]).toEqual(target.layout); + expect(state).toHaveBeenLastCalledWith('ready'); expect(host.style.visibility).toBe('visible'); + }); + it('las barras usan layout.transition de 450 ms cubic-in-out en un solo react', async () => { + const c = controller(); + c.setFigure(bars([1, 2])); await settleLong(); + expect(vi.mocked(plotly.react).mock.calls[0][2]['transition']).toBeUndefined(); + c.setFigure(bars([3, 0])); await settleLong(); + expect(plotly.react).toHaveBeenCalledTimes(2); + expect(vi.mocked(plotly.react).mock.calls[1][2]['transition']).toEqual({ duration: TRANSITION_MS, easing: 'cubic-in-out' }); + }); + it('sin animación (opción desactivada o movimiento reducido) conserva el renderizado oculto original', async () => { + animate = false; + const c = controller(); + c.setFigure(pie([10, 0])); await settleLong(); state.mockClear(); + c.setFigure(pie([4, 6])); + expect(host.style.visibility).toBe('hidden'); expect(state).toHaveBeenCalledWith('loading'); + await settleLong(); + expect(plotly.react).toHaveBeenCalledTimes(2); + expect(vi.mocked(plotly.react).mock.calls[1][2]['transition']).toBeUndefined(); + }); + it('una selección nueva interrumpe la animación y parte del último fotograma dibujado', async () => { + const c = controller(); + c.setFigure(pie([10, 0])); await settleLong(); vi.mocked(plotly.react).mockClear(); + c.setFigure(pie([0, 10])); + for (let i = 0; i < 6; i++) await Promise.resolve(); + c.setFigure(pie([10, 0])); + await settleLong(); + const last = vi.mocked(plotly.react).mock.calls.at(-1)!; + expect(last[1][1]['values']).toEqual([10, 0]); + expect(state).toHaveBeenLastCalledWith('ready'); + }); + + it('no interpola pies con nulos, otra identidad u orden de categorías', () => { + const source = pie([10, 0]); + const changed = pie([5, 5]); changed.data[1]['values'] = [null, 5]; + expect(piesInterpolable(source, changed)).toBe(false); + changed.data[1]['values'] = [5, 5]; changed.data[1]['name'] = 'otro'; + expect(piesInterpolable(source, changed)).toBe(false); + source.data[1]['labels'] = ['A', 'B']; + const reordered = pie([5, 5]); reordered.data[1]['labels'] = ['B', 'A']; + expect(piesInterpolable(source, reordered)).toBe(false); + }); + it('ningún cuadro geométrico expone conteos, plantillas, tooltips ni el total destino adelantado', async () => { + const source = pie([10, 0]), target = pie([4, 6]); + target.data.forEach(trace => Object.assign(trace, { customdata: [[4, 40], [6, 60]], + hovertemplate: '%{value} / %{customdata[0]}', hovertext: ['4', '6'], texttemplate: '%{value}' })); + const original = structuredClone(target), c = controller(); + c.setFigure(source); await settleLong(); vi.mocked(plotly.react).mockClear(); + c.setFigure(target); await settleLong(); + const calls = vi.mocked(plotly.react).mock.calls; + for (const call of calls.slice(0, -1)) for (const trace of call[1]) { + expect(trace['hoverinfo']).toBe('skip'); expect(trace['hovertemplate']).toBeNull(); + expect(trace['customdata']).toEqual([]); expect(trace['hovertext']).toEqual([]); + expect(trace['texttemplate']).toBe(''); expect(trace['textinfo']).toBe('none'); + expect((trace['text'] as string[]).every(text => text === '')).toBe(true); + } + expect(calls.at(-1)![1]).toEqual(target.data); expect(target).toEqual(original); c.destroy(); + }); + it('interrumpe tras un react pendiente y usa el último cuadro completado sin renders concurrentes', async () => { + const frames: ((time: number) => void)[] = []; + const c = new PlotlyController(host, () => Promise.resolve(plotly), state, undefined, + { animate: () => true, nextFrame: () => new Promise(resolve => frames.push(resolve)) }); + const step = async (time: number) => { expect(frames.length).toBeGreaterThan(0); frames.shift()!(time); await settleLong(); }; + c.setFigure(pie([10, 0])); await settleLong(); state.mockClear(); vi.mocked(plotly.react).mockClear(); + const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise); + c.setFigure(pie([0, 10])); await settleLong(); await step(0); await step(150); + const drawn = vi.mocked(plotly.react).mock.calls[0][1][1]['values'] as number[]; + c.setFigure(pie([8, 2])); c.resize(); await settleLong(); + expect(plotly.react).toHaveBeenCalledTimes(1); expect(plotly.Plots.resize).not.toHaveBeenCalled(); + pending.resolve(); await settleLong(); + await step(200); // Discard stale frame; start the latest transition. + await step(250); await step(400); + const resumed = vi.mocked(plotly.react).mock.calls[1][1][1]['values'] as number[]; + expect(resumed[0]).toBeCloseTo(drawn[0] + (8 - drawn[0]) * cubicInOut(150 / TRANSITION_MS)); + await step(700); + expect(vi.mocked(plotly.react).mock.calls.at(-1)![1]).toEqual(pie([8, 2]).data); + expect(state.mock.calls).toEqual([['ready']]); expect(plotly.Plots.resize).toHaveBeenCalledTimes(1); c.destroy(); + }); + it('movimiento reducido durante la dona termina inmediatamente con datos exactos', async () => { + const frames: ((time: number) => void)[] = []; + const c = new PlotlyController(host, () => Promise.resolve(plotly), state, undefined, + { animate: () => animate, nextFrame: () => new Promise(resolve => frames.push(resolve)) }); + c.setFigure(pie([10, 0])); await settleLong(); vi.mocked(plotly.react).mockClear(); + const target = pie([4, 6]); c.setFigure(target); await settleLong(); + frames.shift()!(0); await settleLong(); animate = false; + frames.shift()!(150); await settleLong(); + expect(plotly.react).toHaveBeenCalledTimes(1); expect(vi.mocked(plotly.react).mock.calls[0][1]).toEqual(target.data); + expect(state).toHaveBeenLastCalledWith('ready'); c.destroy(); + }); + it('destruir mientras espera un fotograma no vuelve a dibujar ni a emitir ready', async () => { + let frame!: (time: number) => void; + const c = new PlotlyController(host, () => Promise.resolve(plotly), state, undefined, + { animate: () => true, nextFrame: () => new Promise(resolve => frame = resolve) }); + c.setFigure(pie([10, 0])); await settleLong(); state.mockClear(); vi.mocked(plotly.react).mockClear(); + c.setFigure(pie([0, 10])); await settleLong(); c.destroy(); frame(0); await settleLong(); frame(100); await settleLong(); + expect(plotly.react).not.toHaveBeenCalled(); expect(state).not.toHaveBeenCalled(); + expect(host.style.visibility).toBe('hidden'); + }); + it.each(['uid', 'escenario', 'nulo', 'trazas'])('barras con cambio de %s se redibujan exactamente sin interpolación', async kind => { + const c = controller(), target = bars([3, 4]); + c.setFigure(bars([1, 2])); await settleLong(); + if (kind === 'uid') target.data[0]['uid'] = 'otro'; + if (kind === 'escenario') target.data[0]['y'] = ['Otro']; + if (kind === 'nulo') target.data[0]['x'] = [null]; + if (kind === 'trazas') target.data.pop(); + state.mockClear(); c.setFigure(target); + expect(host.style.visibility).toBe('hidden'); expect(state).toHaveBeenCalledWith('loading'); + await settleLong(); + expect(vi.mocked(plotly.react).mock.calls[1][2]['transition']).toBeUndefined(); + expect(vi.mocked(plotly.react).mock.calls[1][1]).toEqual(target.data); c.destroy(); + }); + it('barras rápidas se serializan, descartan destinos intermedios y nunca anuncian ready obsoleto', async () => { + const c = controller(); c.setFigure(bars([1, 2])); await settleLong(); state.mockClear(); + const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise); + c.setFigure(bars([0, 2])); await settleLong(); + c.setFigure(bars([3, 0])); c.setFigure(bars([4, 5])); await settleLong(); + expect(plotly.react).toHaveBeenCalledTimes(2); expect(state).not.toHaveBeenCalled(); + pending.resolve(); await settleLong(); + expect(plotly.react).toHaveBeenCalledTimes(3); + expect(vi.mocked(plotly.react).mock.calls.at(-1)![1]).toEqual(bars([4, 5]).data); + expect(state.mock.calls).toEqual([['ready']]); expect(host.style.visibility).toBe('visible'); c.destroy(); + }); +}); diff --git a/src/app/shared/plotly/plotly-controller.ts b/src/app/shared/plotly/plotly-controller.ts index 2a98f3f..9286055 100644 --- a/src/app/shared/plotly/plotly-controller.ts +++ b/src/app/shared/plotly/plotly-controller.ts @@ -6,6 +6,75 @@ interface EventHost extends HTMLElement { removeListener?: (name: string, listener: (event: unknown) => void) => void; } +export const TRANSITION_MS = 450; +export interface PlotlyControllerOptions { + // Evaluated per update: animate only an update of an already visible figure. + animate?: () => boolean; + // Resolves on the next animation frame with its timestamp (injectable for tests). + nextFrame?: () => Promise; +} +const nextAnimationFrame = () => new Promise(resolve => requestAnimationFrame(resolve)); +// Plotly's 'cubic-in-out', reproduced for the interpolated pie frames. +export function cubicInOut(t: number): number { + return t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; +} +const RGBA = /^rgba\((\d+),(\d+),(\d+),([\d.]+)\)$/; +function mixColor(from: unknown, to: unknown, t: number): unknown { + const a = typeof from === 'string' ? RGBA.exec(from.replace(/\s/g, '')) : null; + const b = typeof to === 'string' ? RGBA.exec(to.replace(/\s/g, '')) : null; + if (!a || !b) return to; + const v = [1, 2, 3, 4].map(i => Number(a[i]) + (Number(b[i]) - Number(a[i])) * t); + return `rgba(${v.slice(0, 3).map(Math.round).join(',')},${+v[3].toFixed(3)})`; +} +const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(n => typeof n === 'number' && Number.isFinite(n)); +/** Pies cannot use layout.transition: both figures must have the same pies and value shapes. */ +export function piesInterpolable(from: PlotlyFigure, to: PlotlyFigure): boolean { + return to.data.length > 0 && from.data.length === to.data.length && to.data.every((trace, i) => { + const old = from.data[i]; + return trace['type'] === 'pie' && old['type'] === 'pie' && trace['name'] === old['name'] + && JSON.stringify(trace['labels']) === JSON.stringify(old['labels']) + && numbers(trace['values']) && numbers(old['values']) && trace['values'].length === old['values'].length; + }); +} +/** One intermediate pie frame: values and rgba colors move, texts wait for the final frame. */ +export function pieFrame(from: PlotlyFigure, to: PlotlyFigure, t: number): PlotlyFigure { + const moving = to.data.some((trace, i) => (trace['values'] as number[]) + .some((v, j) => v !== (from.data[i]['values'] as number[])[j])); + return { ...to, data: to.data.map((trace, i) => { + const a = from.data[i]['values'] as number[], b = trace['values'] as number[]; + const oldMarker = from.data[i]['marker'] as Record | undefined; + const marker = trace['marker'] as Record | undefined; + const oldColors = oldMarker?.['colors'], colors = marker?.['colors']; + const sameValues = a.every((v, j) => v === b[j]); + const mixColors = !!marker && Array.isArray(colors) && Array.isArray(oldColors) && oldColors.length === colors.length + && colors.some((c, j) => c !== oldColors[j]); + if (sameValues && !mixColors && !moving) return trace; + // Geometry is illustrative until the exact target render. Hide all clinical + // readouts (including the centre) and never attach counts to moving slices. + return { ...trace, ...(sameValues ? {} : { values: b.map((v, j) => a[j] + (v - a[j]) * t) }), + ...(moving ? { text: b.map(() => ''), textinfo: 'none', texttemplate: '', + hoverinfo: 'skip', hovertemplate: null, hovertext: [], customdata: [] } : {}), + ...(mixColors ? { marker: { ...marker, colors: (colors as unknown[]).map((c, j) => mixColor((oldColors as unknown[])[j], c, t)) } } : {}) }; + }) }; +} +const transitionable = (figure: PlotlyFigure) => figure.data.length > 0 + && figure.data.every(trace => ['bar', 'scatter'].includes(String(trace['type'] ?? 'scatter'))); +// A changed catalogue, scenario axis or availability mask is an exact redraw. +// In particular, never tween a published value into an unavailable/suppressed one. +function cartesianInterpolable(from: PlotlyFigure, to: PlotlyFigure): boolean { + return transitionable(from) && transitionable(to) && from.data.length === to.data.length + && to.data.every((trace, i) => { + const old = from.data[i]; + if (trace['type'] !== old['type'] || trace['uid'] !== old['uid']) return false; + return ['x', 'y'].every(axis => { + const a = old[axis], b = trace[axis]; + if (!Array.isArray(a) || !Array.isArray(b)) return a === b; + return a.length === b.length && b.every((v, j) => + typeof v === 'number' && typeof a[j] === 'number' ? true : v === a[j]); + }); + }); +} + // One serialized queue owns the host. A completed stale operation cannot expose // its graph or overwrite a newer react operation. Resize uses the same queue. export class PlotlyController { @@ -18,17 +87,28 @@ export class PlotlyController { private plotly?: PlotlyRuntime; private frameCount = 0; private listenerAttached = false; + // Last figure drawn on the host (target or intermediate frame); origin of the next transition. + private shown?: PlotlyFigure; + private animating = false; private readonly handleClick = (event: unknown) => { if (!this.destroyed && !this.busy && this.rendered === this.version) this.click?.(event); }; constructor(private host: HTMLElement, private load: () => Promise, private state: (state: 'loading' | 'ready' | 'error') => void, - private click?: (event: unknown) => void) {} + private click?: (event: unknown) => void, + private options: PlotlyControllerOptions = {}) {} + private get config() { return { responsive: false, displaylogo: false, showSendToCloud: false, modeBarButtonsToRemove: ['sendChartToCloud'] }; } setFigure(figure: PlotlyFigure) { if (this.destroyed) return; this.desired = figure; this.version++; + // A visible figure that will animate stays on screen; hiding it is the flash + // between selections. Every other update keeps the original hidden render. + this.animating = this.rendered >= 0 && this.host.style.visibility === 'visible' && !!this.shown && !!this.options.animate?.() + && !this.shown.frames?.length && !figure.frames?.length + && (piesInterpolable(this.shown, figure) || cartesianInterpolable(this.shown, figure)); + if (this.animating) return void this.drain(); this.host.style.visibility = 'hidden'; this.state('loading'); void this.drain(); @@ -55,15 +135,33 @@ export class PlotlyController { try { if (this.rendered !== version && this.desired) { // Plotly may mutate inputs; clone the complete JSON without changing values. - const figure = structuredClone(this.desired); + const target = structuredClone(this.desired); + const figure = structuredClone(target); if (this.frameCount) await this.plotly.deleteFrames(this.host, Array.from({ length: this.frameCount }, (_, i) => i)); this.frameCount = 0; if (this.destroyed) break; - await this.plotly.react(this.host, figure.data, figure.layout, { - ...figure.config, responsive: false, displaylogo: false, - showSendToCloud: false, - modeBarButtonsToRemove: ['sendChartToCloud'], - }); + const animate = this.animating && !!this.options.animate?.() && !!this.shown + && !this.shown.frames?.length && !figure.frames?.length; + const config = { ...figure.config, ...this.config }; + if (animate && piesInterpolable(this.shown!, figure)) { + const from = this.shown!, nextFrame = this.options.nextFrame ?? nextAnimationFrame; + const start = await nextFrame(); + for (;;) { + const t = Math.min(1, ((await nextFrame()) - start) / TRANSITION_MS); + if (this.destroyed || version !== this.version || !this.options.animate?.() || t >= 1) break; + const frame = pieFrame(from, figure, cubicInOut(t)); + const copy = structuredClone(frame); + await this.plotly.react(this.host, copy.data, copy.layout, config); + this.shown = frame; + } + if (this.destroyed) break; + if (version !== this.version) continue; + } + const layout = animate && this.shown && cartesianInterpolable(this.shown, figure) + && figure.layout['transition'] === undefined + ? { ...figure.layout, transition: { duration: TRANSITION_MS, easing: 'cubic-in-out' } } : figure.layout; + await this.plotly.react(this.host, figure.data, layout, config); + this.shown = target; if (!this.destroyed && !this.listenerAttached && this.click && (this.host as EventHost).on) { (this.host as EventHost).on!('plotly_click', this.handleClick); this.listenerAttached = true; @@ -88,6 +186,7 @@ export class PlotlyController { if (version !== this.version) continue; this.rendered = version; this.resizePending = false; + this.shown = undefined; this.host.style.visibility = 'hidden'; this.state('error'); }