refactor(indicadores): extraer componente de figura UX-03
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
@if (selected) {
|
||||
<section class="interpretation" aria-label="Cómo leer esta figura">
|
||||
<h2>Cómo leer esta figura · {{ selected?.contrato }}</h2>
|
||||
<ul>
|
||||
@for (line of interpretation; track $index) { <li>{{ line }}</li> }
|
||||
</ul>
|
||||
<p class="period-note">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.</p>
|
||||
</section>
|
||||
}
|
||||
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" aria-label="Resultado de la selección" [attr.aria-busy]="state.status === 'loading'">
|
||||
@if (state.status === 'loading') {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando figura" />
|
||||
<p class="state" role="status">Cargando figura…</p>
|
||||
} @else if (state.status === 'error') {
|
||||
<div class="state" role="alert"><p>{{ state.message }}</p>
|
||||
<button mat-stroked-button (click)="retry.emit()">Reintentar solicitud</button></div>
|
||||
} @else if (state.figure; as figure) {
|
||||
@if (hasNoVisibleValues(figure)) {
|
||||
<p class="state" role="status">No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.</p>
|
||||
}
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<p class="figure-id">Figura: {{ figuraId }}</p>
|
||||
<app-plotly-chart [figure]="state.presentationFigure!" />
|
||||
} @else {
|
||||
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
|
||||
}
|
||||
</mat-card>
|
||||
@@ -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; } }
|
||||
@@ -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<typeof TestBed.createComponent<IndicadorFigureCard>>;
|
||||
let react: ReturnType<typeof vi.fn>;
|
||||
let purge: ReturnType<typeof vi.fn>;
|
||||
let disconnect: ReturnType<typeof vi.fn>;
|
||||
let observe: ReturnType<typeof vi.fn>;
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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<Record<string, readonly string[]>> = {
|
||||
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<void>();
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -62,31 +62,8 @@
|
||||
<p>Sin periodos explícitos, el servicio consulta únicamente {{ selected?.tipos_periodo?.[0] }}; no combina meses y semestres.</p>
|
||||
<p class="contract">Contrato: {{ selected?.contrato }} · Las figuras conservan las notas y categorías del servicio.</p>
|
||||
</mat-card>
|
||||
@if (selected) {
|
||||
<section class="interpretation" aria-labelledby="interpretation-title">
|
||||
<h2 id="interpretation-title">Cómo leer esta figura · {{ selected?.contrato }}</h2>
|
||||
<ul>
|
||||
@for (line of interpretation; track $index) { <li>{{ line }}</li> }
|
||||
</ul>
|
||||
<p class="period-note">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.</p>
|
||||
</section>
|
||||
}
|
||||
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" aria-label="Resultado de la selección" [attr.aria-busy]="result().status === 'loading'">
|
||||
@if (result().status === 'loading') {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando figura" />
|
||||
<p class="state" role="status">Cargando figura…</p>
|
||||
} @else if (result().status === 'error') {
|
||||
<div class="state" role="alert"><p>{{ result().message }}</p>
|
||||
<button mat-stroked-button (click)="requestFigure()">Reintentar solicitud</button></div>
|
||||
} @else if (result().figure; as figure) {
|
||||
@if (hasNoVisibleValues(figure)) {
|
||||
<p class="state" role="status">No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.</p>
|
||||
}
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<app-plotly-chart [figure]="result().presentationFigure!" />
|
||||
} @else {
|
||||
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
|
||||
}
|
||||
</mat-card>
|
||||
<app-indicador-figure-card [state]="result()" [selected]="selected"
|
||||
[figuraId]="figuraId" [dominio]="dominio" [tema]="tema"
|
||||
(retry)="requestFigure()" />
|
||||
}
|
||||
</section>
|
||||
|
||||
@@ -10,20 +10,12 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
.periods { grid-column: 1 / -1; margin-bottom: 1rem; }
|
||||
mat-form-field { width: 100%; min-width: 0; }
|
||||
.contract { color: var(--mat-sys-on-surface-variant); margin: .5rem 0 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); }
|
||||
.validation { color: var(--mat-sys-error); }
|
||||
.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; }
|
||||
@media (max-width: 850px) { .fields { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@media (max-width: 550px) {
|
||||
.fields { grid-template-columns: minmax(0, 1fr); }
|
||||
.indicator { grid-column: auto; }
|
||||
.filters, .interpretation { padding: 1rem; }
|
||||
.filters { padding: 1rem; }
|
||||
h1 { font: var(--mat-sys-headline-medium); }
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { Component } from '@angular/core';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure'], template: '' })
|
||||
@@ -22,7 +23,7 @@ describe('IndicadoresPage', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadoresPage, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresPage);
|
||||
page = fixture.componentInstance;
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
@@ -94,10 +95,12 @@ describe('IndicadoresPage', () => {
|
||||
const req = http.expectOne(r => r.url.includes('/synthetic_future/figuras/fig_c2_apiladas'));
|
||||
expect(req.request.params.has('periodos')).toBe(false);
|
||||
req.flush({ data: [{ type: 'bar', y: [50, null] }], layout: { barmode: 'stack' } });
|
||||
expect(page.interpretation.join(' ')).toContain('composición porcentual');
|
||||
fixture.detectChanges();
|
||||
expect((fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard).interpretation.join(' ')).toContain('composición porcentual');
|
||||
page.selectFigura('fig_c1_puntos');
|
||||
http.expectOne(r => r.url.includes('/fig_c1_puntos')).flush({ data: [], layout: {} });
|
||||
expect(page.interpretation.join(' ')).toContain('no entregan intervalos Wilson efectivos');
|
||||
fixture.detectChanges();
|
||||
expect((fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard).interpretation.join(' ')).toContain('no entregan intervalos Wilson efectivos');
|
||||
});
|
||||
it('presenta carga y elige una primera figura válida desde el catálogo', () => {
|
||||
expect(page.catalogLoading()).toBe(true);
|
||||
@@ -225,7 +228,7 @@ describe('IndicadoresPage', () => {
|
||||
expect(page.result().message).toContain(message);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('error privado');
|
||||
page.requestFigure();
|
||||
fixture.nativeElement.querySelector('app-indicador-figure-card button').click();
|
||||
figure().flush({ data: [], layout: {} });
|
||||
expect(page.result().status).toBe('ready');
|
||||
});
|
||||
|
||||
@@ -10,10 +10,10 @@ import { MatInputModule } from '@angular/material/input';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { Dominio, DOMINIOS, isDominio, TipoPeriodo, FigureSelection, hasNoVisibleValues, Indicador, parsePeriodos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { Dominio, DOMINIOS, isDominio, TipoPeriodo, FigureSelection, Indicador, parsePeriodos, Tema } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { figureTitle, presentationFigure } from './indicadores.presentation';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { presentationFigure } from './indicadores.presentation';
|
||||
import { FigureState, IndicadorFigureCard } from './indicador-figure-card';
|
||||
|
||||
export function httpMessage(error: unknown, catalog = false): string {
|
||||
if (!(error instanceof HttpErrorResponse)) return 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.';
|
||||
@@ -23,31 +23,9 @@ export function httpMessage(error: unknown, catalog = false): string {
|
||||
if (error.status >= 500) return 'El servicio encontró un error interno. Intenta nuevamente más tarde.';
|
||||
return 'No se pudo completar la solicitud. Intenta nuevamente.';
|
||||
}
|
||||
// Presentation only: contract semantics documented in G3 and G5C.
|
||||
const CONTRACT_INTERPRETATIONS: Readonly<Record<string, readonly string[]>> = {
|
||||
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.'];
|
||||
|
||||
type FigureState = { status: 'idle' | 'loading' | 'ready' | 'error'; figure?: PlotlyFigure; presentationFigure?: PlotlyFigure; message?: string };
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, PlotlyChart],
|
||||
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, IndicadorFigureCard],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
@@ -65,8 +43,6 @@ export class IndicadoresPage {
|
||||
readonly catalogLoading = signal(true);
|
||||
readonly catalogError = signal('');
|
||||
readonly result = signal<FigureState>({ status: 'idle' });
|
||||
readonly hasNoVisibleValues = hasNoVisibleValues;
|
||||
readonly figureTitle = figureTitle;
|
||||
indicadorId = '';
|
||||
figuraId = '';
|
||||
periodMode: 'todos' | 'manual' = 'todos';
|
||||
@@ -75,25 +51,6 @@ export class IndicadoresPage {
|
||||
tema: Tema = 'claro';
|
||||
get selected(): Indicador | undefined { return this.catalog().find(item => item.id === this.indicadorId); }
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
constructor() {
|
||||
const initialDomain: unknown = this.route?.snapshot.data['dominio'];
|
||||
if (isDominio(initialDomain)) this.dominio = initialDomain;
|
||||
|
||||
Reference in New Issue
Block a user