feat(indicadores): agregar prototipo de dashboard TEA

Implementa el prototipo del dashboard de indicadores TEA.

- Integra catálogo y figuras mediante WebApi.
- Incorpora visualizaciones interactivas con Plotly.js.
- Agrega controles de indicadores, figuras, periodos y temas.
- Implementa estados de carga, errores y diseño responsive.
- Incluye explicaciones para los contratos C1, C2 y C3r.
- Incorpora pruebas unitarias y de integración de componentes.

Prototipo para investigación con datos sintéticos.
This commit is contained in:
Angel Capetillo Zavala
2026-10-12 10:43:00 -06:00
parent 3605d23fc0
commit a66205b725
22 changed files with 990 additions and 3 deletions
@@ -0,0 +1,178 @@
import { vi } from 'vitest';
import { PlotlyController } from './plotly-controller';
import { PlotlyRuntime } from './plotly-runtime';
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
function deferred() {
let resolve!: (value?: unknown) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<unknown>((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
}
async function settle() { for (let i = 0; i < 12; i++) await Promise.resolve(); }
const fig = (value: number): PlotlyFigure => ({ data: [{ type: 'scatter', y: [value, null] }], layout: { annotations: [{ text: 'No usar para decisiones clínicas' }] } });
describe('PlotlyController async', () => {
let host: HTMLElement;
let plotly: PlotlyRuntime;
let state: ReturnType<typeof vi.fn<(state: 'loading' | 'ready' | 'error') => void>>;
let controller: PlotlyController;
beforeEach(() => {
host = document.createElement('div');
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();
controller = new PlotlyController(host, () => Promise.resolve(plotly), state);
});
it('conserva valores y anotaciones, aislando mutaciones de Plotly', async () => {
const figure = fig(0);
vi.mocked(plotly.react).mockImplementation(async (_host, data) => { data[0]['y'] = [123]; });
controller.setFigure(figure); await settle();
expect(figure.data[0]['y']).toEqual([0, null]);
expect(plotly.react).toHaveBeenCalledWith(host, expect.any(Array), figure.layout, expect.objectContaining({ displaylogo: false }));
expect(host.style.visibility).toBe('visible');
expect(state).toHaveBeenLastCalledWith('ready');
});
it('desactiva el envío externo sin alterar el JSON ni las opciones locales recibidas', async () => {
const figure: PlotlyFigure = {
...fig(1),
config: { showSendToCloud: true, displaylogo: true, scrollZoom: true, doubleClick: 'reset+autosize' },
frames: [{ name: 'uno', data: [{ y: [2, null] }] }],
};
const original = JSON.stringify(figure);
controller.setFigure(figure); await settle();
expect(plotly.react).toHaveBeenCalledWith(host, figure.data, figure.layout, {
responsive: false, displaylogo: false, showSendToCloud: false,
modeBarButtonsToRemove: ['sendChartToCloud'], scrollZoom: true, doubleClick: 'reset+autosize',
});
expect(plotly.addFrames).toHaveBeenCalledWith(host, figure.frames);
expect(JSON.stringify(figure)).toBe(original);
});
it('elige sólo la figura reciente si la importación sigue pendiente', async () => {
const load = deferred();
controller = new PlotlyController(host, () => load.promise as Promise<PlotlyRuntime>, state);
controller.setFigure(fig(1)); controller.setFigure(fig(2));
load.resolve(plotly); await settle();
expect(plotly.react).toHaveBeenCalledTimes(1);
expect(vi.mocked(plotly.react).mock.calls[0][1][0]['y']).toEqual([2, null]);
});
it('serializa react y oculta completados obsoletos', async () => {
const old = deferred(); const latest = deferred();
vi.mocked(plotly.react).mockReturnValueOnce(old.promise).mockReturnValueOnce(latest.promise);
controller.setFigure(fig(1)); await settle();
controller.setFigure(fig(2));
expect(plotly.react).toHaveBeenCalledTimes(1);
old.resolve(); await settle();
expect(plotly.react).toHaveBeenCalledTimes(2);
expect(host.style.visibility).toBe('hidden');
expect(state).not.toHaveBeenCalledWith('ready');
latest.resolve(); await settle();
expect(host.style.visibility).toBe('visible');
expect(state).toHaveBeenLastCalledWith('ready');
});
it('ignora rechazo antiguo y representa la siguiente figura', async () => {
const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise);
controller.setFigure(fig(1)); await settle(); controller.setFigure(fig(2));
pending.reject(new Error('old')); await settle();
expect(state).not.toHaveBeenCalledWith('error');
expect(state).toHaveBeenLastCalledWith('ready');
});
it('maneja error asíncrono y permite reintentar', async () => {
vi.mocked(plotly.react).mockRejectedValueOnce(new Error('failed'));
controller.setFigure(fig(1)); await settle();
expect(state).toHaveBeenLastCalledWith('error');
expect(host.style.visibility).toBe('hidden');
controller.setFigure(fig(1)); await settle();
expect(state).toHaveBeenLastCalledWith('ready');
});
it('maneja importación fallida y recupera el cargador', async () => {
const load = vi.fn().mockRejectedValueOnce(new Error()).mockResolvedValue(plotly);
controller = new PlotlyController(host, load, state);
controller.setFigure(fig(1)); await settle(); expect(state).toHaveBeenLastCalledWith('error');
controller.setFigure(fig(1)); await settle(); expect(state).toHaveBeenLastCalledWith('ready');
});
it('purga al destruir y nuevamente tras terminar react pendiente', async () => {
const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise);
controller.setFigure(fig(1)); await settle();
controller.destroy(); expect(plotly.purge).toHaveBeenCalledTimes(1);
pending.resolve(); await settle(); expect(plotly.purge).toHaveBeenCalledTimes(2);
expect(state).not.toHaveBeenCalledWith('ready');
controller.setFigure(fig(2)); controller.resize(); await settle();
expect(plotly.react).toHaveBeenCalledTimes(1);
expect(plotly.Plots.resize).not.toHaveBeenCalled();
});
it('no renderiza tras destruir durante la importación', async () => {
const pending = deferred(); controller = new PlotlyController(host, () => pending.promise as Promise<PlotlyRuntime>, state);
controller.setFigure(fig(1)); controller.destroy(); pending.resolve(plotly); await settle();
expect(plotly.react).not.toHaveBeenCalled(); expect(plotly.purge).toHaveBeenCalledWith(host);
});
it('serializa resize y el siguiente react', async () => {
controller.setFigure(fig(1)); await settle();
const resize = deferred(); vi.mocked(plotly.Plots.resize).mockReturnValueOnce(resize.promise);
controller.resize(); await settle(); controller.setFigure(fig(2));
expect(plotly.react).toHaveBeenCalledTimes(1);
resize.resolve(); await settle(); expect(plotly.react).toHaveBeenCalledTimes(2);
});
it('conserva frames y los retira al cambiar figura', async () => {
controller.setFigure({ ...fig(1), frames: [{ name: 'uno', data: [] }] }); await settle();
expect(plotly.addFrames).toHaveBeenCalledWith(host, [{ name: 'uno', data: [] }]);
controller.setFigure(fig(2)); await settle();
expect(plotly.deleteFrames).toHaveBeenCalledWith(host, [0]);
});
});
// Exercise the installed bundle in jsdom: no cloud action is clicked.
describe('PlotlyController con Plotly instalado', () => {
let runtime: PlotlyRuntime & {
version: string;
PlotSchema: { get(): { config: Record<string, { valType: string }> } };
};
beforeAll(async () => {
// jsdom has no canvas renderer; cartesian SVG only needs this import-time probe.
const canvas = vi.spyOn(HTMLCanvasElement.prototype, 'getContext')
.mockReturnValue({ measureText: () => ({ width: 0 }) } as unknown as CanvasRenderingContext2D);
try {
const module = await import('plotly.js-cartesian-dist-min');
runtime = (module.default ?? module) as typeof runtime;
} finally { canvas.mockRestore(); }
});
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;
expect(config['showSendToCloud'].valType).toBe('boolean');
expect(config['displaylogo'].valType).toBe('boolean');
expect(config['modeBarButtonsToRemove'].valType).toBe('any');
});
it.each([
['C1', { type: 'scatter', x: [1, 2], y: [3, 4] }],
['C2', { type: 'bar', x: ['grupo'], y: [100] }],
['C3r', { type: 'box', x: ['grupo'], q1: [23.5], median: [45], q3: [55], lowerfence: [23.5], upperfence: [55] }],
])('genera la modebar %s sin envío externo y conserva zoom/pan/restauración', async (_contract, trace) => {
const host = document.createElement('div');
document.body.append(host);
const figure: PlotlyFigure = { data: [trace], layout: { width: 600, height: 400 } };
const original = JSON.stringify(figure);
let controller!: PlotlyController;
try {
await new Promise<void>((resolve, reject) => {
controller = new PlotlyController(host, () => Promise.resolve(runtime), state => {
if (state === 'ready') resolve();
if (state === 'error') reject(new Error('Plotly failed to render'));
});
controller.setFigure(figure);
});
const buttons = Array.from(host.querySelectorAll<HTMLElement>('.modebar-btn'));
const titles = buttons.map(button => button.getAttribute('data-title'));
expect(titles).not.toContain('Share chart...');
expect(titles).toEqual(expect.arrayContaining(['Zoom', 'Pan', 'Zoom in', 'Zoom out', 'Autoscale', 'Reset axes', 'Download plot as a PNG']));
expect(host.querySelector('.modebar a[href]')).toBeNull();
const rendered = host as unknown as HTMLElement & { _fullLayout: { dragmode: string } };
for (const [title, mode] of [['Pan', 'pan'], ['Zoom', 'zoom']]) {
buttons.find(button => button.getAttribute('data-title') === title)!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
await vi.waitFor(() => expect(rendered._fullLayout.dragmode).toBe(mode));
}
expect(JSON.stringify(figure)).toBe(original);
} finally {
controller?.destroy(); host.remove();
}
});
});