Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.
+
+}
+
+ @if (state.status === 'loading') {
+
+
Cargando figura…
+ } @else if (state.status === 'error') {
+
{{ state.message }}
+
+ } @else if (state.figure; as figure) {
+ @if (hasNoVisibleValues(figure)) {
+
No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.
+ }
+
+
Figura: {{ figuraId }}
+
+ } @else {
+
{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}
+ }
+
diff --git a/src/app/features/indicadores/indicador-figure-card.scss b/src/app/features/indicadores/indicador-figure-card.scss
new file mode 100644
index 0000000..576c8a6
--- /dev/null
+++ b/src/app/features/indicadores/indicador-figure-card.scss
@@ -0,0 +1,12 @@
+:host { display: block; min-width: 0; }
+.interpretation { padding: 1rem 1.25rem; margin-bottom: 1.5rem; border-radius: 8px; background: var(--mat-sys-surface-container-low); color: var(--mat-sys-on-surface); font: var(--mat-sys-body-medium); line-height: 1.5; overflow-wrap: anywhere; }
+.interpretation h2 { margin: 0 0 .5rem; font: var(--mat-sys-title-small); }
+.interpretation ul { margin: 0; padding-left: 1.25rem; }
+.interpretation li + li { margin-top: .25rem; }
+.period-note { margin: .75rem 0 0; color: var(--mat-sys-on-surface-variant); }
+.figure-card { overflow: hidden; min-width: 0; }
+.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); overflow-wrap: anywhere; }
+.state { padding: 1.25rem; margin: 0; }
+.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
+.figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; }
+@media (max-width: 550px) { .interpretation { padding: 1rem; } }
diff --git a/src/app/features/indicadores/indicador-figure-card.spec.ts b/src/app/features/indicadores/indicador-figure-card.spec.ts
new file mode 100644
index 0000000..d2e4d6d
--- /dev/null
+++ b/src/app/features/indicadores/indicador-figure-card.spec.ts
@@ -0,0 +1,131 @@
+import { TestBed } from '@angular/core/testing';
+import { By } from '@angular/platform-browser';
+import { vi } from 'vitest';
+import { FigureState, IndicadorFigureCard } from './indicador-figure-card';
+import { Indicador, PlotlyFigure } from './indicadores.models';
+import { presentationFigure } from './indicadores.presentation';
+import { PlotlyChart } from '../../shared/plotly/plotly-chart';
+import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
+
+describe('IndicadorFigureCard', () => {
+ const selected: Indicador = { id: 'i1', titulo: 'Indicador de prueba', contrato: 'C1', figuras: ['fig_c1_puntos'], tipos_periodo: ['semestre'] };
+ let fixture: ReturnType>;
+ let react: ReturnType;
+ let purge: ReturnType;
+ let disconnect: ReturnType;
+ let observe: ReturnType;
+ beforeEach(() => {
+ react = vi.fn().mockResolvedValue(undefined);
+ purge = vi.fn();
+ disconnect = vi.fn();
+ observe = vi.fn();
+ vi.stubGlobal('ResizeObserver', class { observe = observe; disconnect = disconnect; });
+ TestBed.configureTestingModule({
+ imports: [IndicadorFigureCard],
+ providers: [{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve({
+ react, purge, Plots: { resize: vi.fn().mockResolvedValue(undefined) },
+ addFrames: vi.fn().mockResolvedValue(undefined), deleteFrames: vi.fn().mockResolvedValue(undefined),
+ }) }],
+ });
+ fixture = TestBed.createComponent(IndicadorFigureCard);
+ fixture.componentRef.setInput('selected', selected);
+ fixture.componentRef.setInput('figuraId', 'fig_c1_puntos');
+ fixture.componentRef.setInput('dominio', 'tea');
+ fixture.componentRef.setInput('tema', 'claro');
+ fixture.componentRef.setInput('state', { status: 'idle' });
+ });
+ afterEach(() => { fixture.destroy(); vi.unstubAllGlobals(); });
+ function state(value: FigureState) { fixture.componentRef.setInput('state', value); fixture.detectChanges(); }
+ async function settle() {
+ await fixture.whenStable();
+ for (let i = 0; i < 12; i++) await Promise.resolve();
+ fixture.detectChanges();
+ }
+ function ready(original: PlotlyFigure) {
+ const copy = presentationFigure(original, { indicador: selected.id, figura: 'fig_c1_puntos', tema: 'claro' });
+ state({ status: 'ready', figure: original, presentationFigure: copy });
+ return copy;
+ }
+ it('muestra carga, error y emite reintento sin coordinar HTTP', () => {
+ state({ status: 'loading' });
+ expect(fixture.nativeElement.querySelector('mat-card').getAttribute('aria-busy')).toBe('true');
+ expect(fixture.nativeElement.textContent).toContain('Cargando figura');
+ const retry = vi.fn();
+ fixture.componentInstance.retry.subscribe(retry);
+ state({ status: 'error', message: 'La figura o los reportes no están disponibles para esta selección.' });
+ expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('reportes no están disponibles');
+ fixture.nativeElement.querySelector('button').click();
+ expect(retry).toHaveBeenCalledTimes(1);
+ expect(fixture.debugElement.query(By.directive(PlotlyChart))).toBeNull();
+ });
+ it('presenta selección incompleta y un indicador sin figuras', () => {
+ state({ status: 'idle' });
+ expect(fixture.nativeElement.textContent).toContain('Completa una selección válida');
+ fixture.componentRef.setInput('selected', { ...selected, figuras: [] });
+ fixture.detectChanges();
+ expect(fixture.nativeElement.textContent).toContain('El indicador no tiene figuras disponibles');
+ });
+ it('presenta título del JSON, identificación secundaria y conserva datos incluso si Plotly los muta', async () => {
+ const original: PlotlyFigure = {
+ data: [{ type: 'scatter', y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], x: { dtype: 'i1', bdata: 'AAE=' } }],
+ layout: { title: { text: 'Título publicado', font: { size: 20 } }, annotations: [{ text: 'Nota de supresión' }] },
+ config: { staticPlot: false }, frames: [], extra: { preserved: true },
+ };
+ const snapshot = JSON.stringify(original);
+ react.mockImplementation(async (_host, data, layout) => {
+ data[0].y[0] = 0;
+ layout.annotations[0].text = 'Cambio interno de Plotly';
+ });
+ const copy = ready(original);
+ await settle();
+ expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Título publicado');
+ expect(fixture.nativeElement.querySelector('.figure-id').textContent).toContain('fig_c1_puntos');
+ expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.figure).toBe(copy);
+ expect(JSON.stringify(original)).toBe(snapshot);
+ expect(copy.data).toEqual(original.data);
+ expect(copy.layout['annotations']).toEqual(original.layout['annotations']);
+ });
+ it('distingue resultado sin puntos del error y mantiene valores binarios indeterminados', async () => {
+ ready({ data: [{ y: [null] }], layout: {} });
+ await settle();
+ expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
+ expect(fixture.debugElement.query(By.directive(PlotlyChart))).not.toBeNull();
+ ready({ data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' } }], layout: {} });
+ await settle();
+ expect(fixture.nativeElement.textContent).not.toContain('No hay valores visibles');
+ });
+ it.each(['cacu', 'cama'])('conserva advertencias específicas de %s durante la carga', dominio => {
+ fixture.componentRef.setInput('dominio', dominio);
+ state({ status: 'loading' });
+ expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('no entregan intervalos Wilson efectivos');
+ expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('suprimidos no representan tasas observadas de 0 %');
+ });
+ it('conserva el error y reintento de renderizado dentro de PlotlyChart', async () => {
+ react.mockRejectedValueOnce(new Error('render'));
+ ready({ data: [{ y: [42] }], layout: {} });
+ await settle();
+ expect(fixture.nativeElement.textContent).toContain('No se pudo representar la figura');
+ const retry = vi.fn();
+ fixture.componentInstance.retry.subscribe(retry);
+ fixture.nativeElement.querySelector('button').click();
+ await settle();
+ expect(react).toHaveBeenCalledTimes(2);
+ expect(retry).not.toHaveBeenCalled();
+ expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.status()).toBe('ready');
+ });
+ it('destruye Plotly al abandonar el resultado y al destruir la card', async () => {
+ ready({ data: [{ y: [42] }], layout: {} });
+ await settle();
+ const firstHost = fixture.nativeElement.querySelector('.plot');
+ expect(observe).toHaveBeenCalledWith(firstHost);
+ state({ status: 'loading' });
+ expect(purge).toHaveBeenCalledWith(firstHost);
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ ready({ data: [{ y: [50] }], layout: {} });
+ await settle();
+ const secondHost = fixture.nativeElement.querySelector('.plot');
+ fixture.destroy();
+ expect(purge).toHaveBeenCalledWith(secondHost);
+ expect(disconnect).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts
new file mode 100644
index 0000000..70ce42d
--- /dev/null
+++ b/src/app/features/indicadores/indicador-figure-card.ts
@@ -0,0 +1,74 @@
+import { Component, Input, output } from '@angular/core';
+import { MatButtonModule } from '@angular/material/button';
+import { MatCardModule } from '@angular/material/card';
+import { MatProgressBarModule } from '@angular/material/progress-bar';
+import { Dominio, hasNoVisibleValues, Indicador, PlotlyFigure, Tema } from './indicadores.models';
+import { figureTitle } from './indicadores.presentation';
+import { PlotlyChart } from '../../shared/plotly/plotly-chart';
+
+// The page owns requests; the card receives the original and its presentation copy.
+export interface FigureState {
+ status: 'idle' | 'loading' | 'ready' | 'error';
+ figure?: PlotlyFigure;
+ presentationFigure?: PlotlyFigure;
+ message?: string;
+}
+
+// Presentation only: contract semantics documented in G3 and G5C.
+const CONTRACT_INTERPRETATIONS: Readonly> = {
+ C1: [
+ 'El punto representa la proporción observada.',
+ 'En las figuras TEA con intervalos calculados, la línea vertical representa el intervalo de confianza Wilson al 95 %. No se infieren intervalos cuando faltan.',
+ 'Los intervalos amplios pueden deberse a denominadores pequeños.',
+ 'Un porcentaje observado del 100 % no implica certeza poblacional.',
+ ],
+ C2: [
+ 'Las barras muestran la composición porcentual de cada grupo y periodo.',
+ 'Las categorías corresponden a la distribución de cada grupo y periodo.',
+ 'SIN_DATO, cuando aparece, es una categoría legítima de la representación.',
+ ],
+ C3r: [
+ 'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.',
+ 'Los límites de dibujo no representan necesariamente extremos observados.',
+ 'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.',
+ ],
+};
+const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las notas de la figura; no se infiere su significado estadístico.'];
+
+@Component({
+ selector: 'app-indicador-figure-card',
+ standalone: true,
+ imports: [MatButtonModule, MatCardModule, MatProgressBarModule, PlotlyChart],
+ templateUrl: './indicador-figure-card.html',
+ styleUrl: './indicador-figure-card.scss',
+})
+export class IndicadorFigureCard {
+ @Input({ required: true }) state!: FigureState;
+ @Input() selected?: Indicador;
+ @Input({ required: true }) figuraId!: string;
+ @Input({ required: true }) dominio!: Dominio;
+ @Input({ required: true }) tema!: Tema;
+ readonly retry = output();
+ readonly hasNoVisibleValues = hasNoVisibleValues;
+ readonly figureTitle = figureTitle;
+
+ get interpretation(): readonly string[] {
+ const contract = this.figuraId.startsWith('fig_c1') ? 'C1'
+ : this.figuraId.startsWith('fig_c2') ? 'C2'
+ : this.figuraId.startsWith('fig_c3r') ? 'C3r' : this.selected?.contrato;
+ if (contract === 'C2' && this.dominio !== 'tea') return [
+ 'Las barras muestran la composición porcentual de las categorías publicadas para cada periodo.',
+ 'SIN_DATO, cuando aparece, es una categoría legítima de la representación.',
+ 'Los valores nulos o suprimidos no representan porcentajes observados de 0 %.',
+ ];
+ if (contract === 'C1' && this.dominio !== 'tea') return [
+ 'Los puntos representan porcentajes observados; el eje horizontal muestra el periodo.',
+ 'Estas figuras no entregan intervalos Wilson efectivos; no se interpretan sus barras como intervalos al 95 %.',
+ 'Los puntos suprimidos no representan tasas observadas de 0 %. Consulta las notas del servicio.',
+ 'Un porcentaje observado del 100 % no implica certeza poblacional.',
+ ];
+ return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract)
+ ? [...CONTRACT_INTERPRETATIONS[contract], 'Los puntos suprimidos no representan tasas observadas de 0 %.'] : UNKNOWN_INTERPRETATION;
+ }
+
+}
diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html
index a96810b..f13df21 100644
--- a/src/app/features/indicadores/indicadores-page.html
+++ b/src/app/features/indicadores/indicadores-page.html
@@ -62,31 +62,8 @@
Sin periodos explícitos, el servicio consulta únicamente {{ selected?.tipos_periodo?.[0] }}; no combina meses y semestres.
Contrato: {{ selected?.contrato }} · Las figuras conservan las notas y categorías del servicio.
- @if (selected) {
-
-
Cómo leer esta figura · {{ selected?.contrato }}
-
- @for (line of interpretation; track $index) {
{{ line }}
}
-
-
Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.