fix(TEA): ajustar indicadores y trazabilidad #25
@@ -28,7 +28,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
function load(items = [item('a'), item('b')], domain = 'tea') {
|
||||
function load(items = [item('M23_pacientes_evaluados'), item('M24_confirmacion_diagnostico')], domain = 'tea') {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
||||
}
|
||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
||||
@@ -55,7 +55,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('un editor general de %s sin KPI no publicados ni HTTP inicial', domain => {
|
||||
if (domain !== 'tea') { http.expectOne('/tea/indicadores'); page.changeDominio(domain); }
|
||||
load(undefined, domain);
|
||||
load([item('sin_kpi')], domain);
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
|
||||
const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf<HTMLElement>;
|
||||
expect(sections[0].querySelector('#global-filters-title')!.textContent!.trim()).toBe('Filtros');
|
||||
@@ -73,7 +73,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
expect(panels()[0].result()).toBe(result); expect(page.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true);
|
||||
});
|
||||
it('aplicar actualiza todas las activadas sin abrir pendientes ni KPI', () => {
|
||||
load([item('a'), item('b'), item('c')]); open(0); open(1); respond();
|
||||
load([item('M23_pacientes_evaluados'), item('M24_confirmacion_diagnostico'), item('M21_diagnosticados_con_eeg')]); open(0); open(1); respond();
|
||||
const before = cards(); draft('semestre', ['2025-S1']); apply();
|
||||
expect(cards()).toEqual(before); expect(cards()[2].visible).toBe(false);
|
||||
const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(2);
|
||||
@@ -91,28 +91,28 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
it('tarjeta activada después recibe el último aplicado y solo su primera consulta', () => {
|
||||
load(); draft('semestre', ['2025-S2']); apply(); http.expectNone(() => true);
|
||||
cards()[1].setVisible(true); fixture.detectChanges();
|
||||
const r = request('b'); expect(r.request.params.get('periodos')).toBe('2025-S2'); r.flush({ data: [], layout: {} });
|
||||
const r = request('M24_confirmacion_diagnostico'); expect(r.request.params.get('periodos')).toBe('2025-S2'); r.flush({ data: [], layout: {} });
|
||||
cards()[1].setVisible(true); fixture.detectChanges(); http.expectNone(() => true);
|
||||
});
|
||||
it('fuera del viewport difiere aplicado y al volver usa revisión vigente', () => {
|
||||
load(); open(); respond(); const panel = panels()[0];
|
||||
cards()[0].setVisible(false); fixture.detectChanges(); draft('semestre', ['2025-S1']); apply();
|
||||
expect(fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance).toBe(panel); expect(panel.result().status).toBe('deferred'); http.expectNone(() => true);
|
||||
open(); const r = request('a'); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} });
|
||||
open(); const r = request('M23_pacientes_evaluados'); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('restaurada abierta espera visibilidad y usa revisión vigente al activarse', () => {
|
||||
load(); open(); respond(); page.changeDominio('cacu'); load(undefined, 'cacu');
|
||||
page.changeDominio('tea'); load();
|
||||
expect(cards()[0].visible).toBe(false); draft('semestre', ['2025-S1']); apply(); http.expectNone(() => true);
|
||||
cards()[0].setVisible(true); fixture.detectChanges();
|
||||
expect(panels()[0].applied.revision).toBe(1); const r = request('a'); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} });
|
||||
expect(panels()[0].applied.revision).toBe(1); const r = request('M23_pacientes_evaluados'); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('mensual compartido consulta compatibles y retira resultado anterior del incompatible', () => {
|
||||
load([item('a', ['semestre']), item('b')]); open(0); open(1); respond();
|
||||
load([item('M23_pacientes_evaluados', ['semestre']), item('M24_confirmacion_diagnostico')]); open(0); open(1); respond();
|
||||
const panel = panels()[0], host = fixture.nativeElement.querySelector('app-plotly-chart');
|
||||
draft('mes', ['2025-01']); apply();
|
||||
expect(panel.result().status).toBe('incompatible'); expect(panel.result().figure).toBeUndefined();
|
||||
http.expectNone(r => r.url.includes('/a/figuras/')); const r = request('b');
|
||||
http.expectNone(r => r.url.includes('/M23_pacientes_evaluados/figuras/')); const r = request('M24_confirmacion_diagnostico');
|
||||
expect(r.request.params.get('periodos')).toBe('2025-01'); expect(r.request.params.has('tipoPeriodo')).toBe(false);
|
||||
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('intervalo de análisis mensual');
|
||||
expect((host as HTMLElement).parentElement!.hidden).toBe(true);
|
||||
@@ -120,28 +120,28 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
||||
});
|
||||
it('incompatibilidad cancela solicitud pendiente y no queda cargando', () => {
|
||||
load([item('a', ['semestre']), item('b')]); open(); const old = request('a');
|
||||
load([item('M23_pacientes_evaluados', ['semestre']), item('M24_confirmacion_diagnostico')]); open(); const old = request('M23_pacientes_evaluados');
|
||||
draft('mes', ['2025-01']); apply(); expect(old.cancelled).toBe(true); expect(panels()[0].result().status).toBe('incompatible');
|
||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); http.expectNone(() => true);
|
||||
});
|
||||
it('dos revisiones cancelan respuestas anteriores y carga oculta resultado previo conservando host', () => {
|
||||
load(); open(); respond(); const host = fixture.nativeElement.querySelector('app-plotly-chart');
|
||||
draft('semestre', ['2025-S1']); apply(); const old = request('a');
|
||||
draft('semestre', ['2025-S1']); apply(); const old = request('M23_pacientes_evaluados');
|
||||
expect(panels()[0].result().figure).toBeUndefined(); expect((host as HTMLElement).parentElement!.hidden).toBe(true);
|
||||
editor().year = '2025'; editor().unit = 'S2'; editor().add(); apply(); const current = request('a');
|
||||
editor().year = '2025'; editor().unit = 'S2'; editor().add(); apply(); const current = request('M23_pacientes_evaluados');
|
||||
expect(old.cancelled).toBe(true); current.flush({ data: [{ y: [7] }], layout: {} }); fixture.detectChanges();
|
||||
expect(panels()[0].result().figure!.data[0]['y']).toEqual([7]); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(host);
|
||||
expect((host as HTMLElement).parentElement!.hidden).toBe(false);
|
||||
});
|
||||
it('404 y reintento individual usan aplicado vigente y conservan borrador y otra figura', () => {
|
||||
load(); open(0); open(1); respond(); draft('semestre', ['2025-S1']); apply();
|
||||
request('a').flush('private', { status: 404, statusText: 'Not Found' }); request('b').flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
request('M23_pacientes_evaluados').flush('private', { status: 404, statusText: 'Not Found' }); request('M24_confirmacion_diagnostico').flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
const other = panels()[1].result(); editor().select([]); panels()[0].requestFigure();
|
||||
const retry = request('a'); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||
const retry = request('M23_pacientes_evaluados'); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||
retry.flush({ data: [], layout: {} }); expect(panels()[1].result()).toBe(other); expect(editor().entry.draft.mode).toBe('empty');
|
||||
});
|
||||
it('dominio durante carga cancela saliente y restaura borrador separado del aplicado', () => {
|
||||
load(); open(); respond(); draft('semestre', ['2025-S1']); apply(); const outgoing = request('a');
|
||||
load(); open(); respond(); draft('semestre', ['2025-S1']); apply(); const outgoing = request('M23_pacientes_evaluados');
|
||||
editor().year = '2025'; editor().unit = 'S2'; editor().add(); page.changeDominio('cacu'); fixture.detectChanges();
|
||||
expect(outgoing.cancelled).toBe(true); load(undefined, 'cacu'); expect(page.filters!.applied.selection.mode).toBe('todos');
|
||||
draft('mes', ['2026-01']); apply(); page.changeDominio('tea'); load();
|
||||
@@ -152,15 +152,15 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
});
|
||||
it('catálogo nuevo revalida sin recortar ni sustituir mensual aplicado', () => {
|
||||
load(); draft('mes', ['2025-01']); apply(); open(); respond();
|
||||
page.retryCatalog(); fixture.detectChanges(); load([item('a', ['semestre'])]);
|
||||
page.retryCatalog(); fixture.detectChanges(); load([item('M23_pacientes_evaluados', ['semestre'])]);
|
||||
expect(page.filters!.applied.tipo).toBe('mes'); expect(page.filters!.applied.revision).toBe(1);
|
||||
cards()[0].setVisible(true); fixture.detectChanges();
|
||||
expect(panels()[0].result().status).toBe('incompatible'); http.expectNone(() => true);
|
||||
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true);
|
||||
editor().changeTipo('semestre'); apply(); request('a').flush({ data: [], layout: {} }); expect(page.filters!.applied.revision).toBe(2);
|
||||
editor().changeTipo('semestre'); apply(); request('M23_pacientes_evaluados').flush({ data: [], layout: {} }); expect(page.filters!.applied.revision).toBe(2);
|
||||
});
|
||||
it('orden del catálogo no permite simular Todos mensual', () => {
|
||||
load([item('a', ['mes', 'semestre'])]); open(); expect(panels()[0].result().status).toBe('incompatible'); http.expectNone(() => true);
|
||||
draft('mes', ['2025-01']); apply(); request('a').flush({ data: [], layout: {} });
|
||||
load([item('M23_pacientes_evaluados', ['mes', 'semestre'])]); open(); expect(panels()[0].result().status).toBe('incompatible'); http.expectNone(() => true);
|
||||
draft('mes', ['2025-01']); apply(); request('M23_pacientes_evaluados').flush({ data: [], layout: {} });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -142,21 +142,16 @@ describe('Histórico: pies de figura de CaMa y resultado experimental de EEG en
|
||||
expect(figura({ ...base('C2', MESES, cats), id: 'cama_birads_456_paciente' } as IndicadorDatos).comoLeer).toBe('');
|
||||
expect(figura({ ...base('C2', MESES, cats), id: 'otro' } as IndicadorDatos).comoLeer).toContain('Cada barra es el total');
|
||||
});
|
||||
it('M30 dibuja EEG anormal y EEG normal como dos líneas complementarias', () => {
|
||||
// Fails if the normal line stops mirroring the abnormal one over the same denominator, or if a period without
|
||||
// evaluable children is drawn as normal (it stays a gap), or if the caption changes.
|
||||
it('M30 dibuja solo la línea de EEG anormal publicada', () => {
|
||||
const m30 = figura({ ...base('C1', MESES, [fila('2025-01', { valor: 62.5, numerador: 5, denominador: 8, ic_bajo: 30.6, ic_alto: 86.3 }),
|
||||
fila('2025-02', { valor: null, numerador: null, denominador: 0, ic_bajo: null, ic_alto: null })]), id: 'M30_resultado_eeg' } as IndicadorDatos);
|
||||
const f = m30.figure as unknown as Fig;
|
||||
const lineas = f.data.filter(t => t['mode'] === 'lines+markers');
|
||||
expect(lineas.map(t => t['name'])).toEqual(['EEG anormal', 'EEG normal']);
|
||||
expect(lineas.map(t => t['name'])).toEqual(['EEG anormal']);
|
||||
expect(lineas[0]['y']).toEqual([62.5, null, null, null]);
|
||||
expect(lineas[1]['y']).toEqual([37.5, null, null, null]);
|
||||
expect(JSON.stringify(lineas[0]['text'])).toContain('5 de 8');
|
||||
expect(JSON.stringify(lineas[1]['text'])).toContain('3 de 8');
|
||||
expect(f.data.find(t => t['name'] === 'Intervalo de confianza')!['y']).toEqual([86.3, 30.6]);
|
||||
expect(f.data.find(t => t['name'] === 'Intervalo de confianza (normal)')!['y']).toEqual([69.4, 13.7]);
|
||||
expect(m30.comoLeer).toBe('La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.');
|
||||
expect(m30.comoLeer).toBe('Línea de EEG anormal: se detecta alguna alteración.');
|
||||
expect(m30.notaMetodologica).toContain('La clasificación de EEG normal está pendiente de validación.');
|
||||
expect(m30.sinDato).toEqual(['feb 2025', 'mar 2025', 'abr 2025']);
|
||||
});
|
||||
|
||||
@@ -102,12 +102,10 @@ function colorDeLinea(id: string, tema: Tema) {
|
||||
}
|
||||
|
||||
export const M30_RESULTADO_EEG = 'M30_resultado_eeg';
|
||||
// Normal takes the cool side of the palette and abnormal the warm one, as in the other domains' compositions.
|
||||
const NORMAL_EEG = C2_PALETTE.frios[3], ANORMAL_EEG = C2_PALETTE.calidos[0];
|
||||
|
||||
const PIE_PORCENTAJE: Readonly<Record<string, string>> = {
|
||||
cama_confirmacion_birads45: 'La línea representa el porcentaje de confirmación histopatológica.',
|
||||
[M30_RESULTADO_EEG]: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
|
||||
[M30_RESULTADO_EEG]: 'Línea de EEG anormal: se detecta alguna alteración.',
|
||||
};
|
||||
const PIE_MEDIANA: Readonly<Record<string, string>> = Object.fromEntries(['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico'].map(id => [id,
|
||||
'La línea representa la mediana de los días de tamizaje a diagnóstico en cada periodo analizado. La banda sombreada incluye del primer al tercer cuartil.']));
|
||||
@@ -119,19 +117,9 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
const periodos = validar(data);
|
||||
// A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here.
|
||||
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0);
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje');
|
||||
const trazo = data.id === M30_RESULTADO_EEG ? { linea: ANORMAL_EEG, relleno: ANORMAL_EEG + '40' } : colorDeLinea(data.id, tema);
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), trazo = colorDeLinea(data.id, tema);
|
||||
const resultadoEeg = data.id === M30_RESULTADO_EEG;
|
||||
const nombre = resultadoEeg ? 'EEG anormal' : 'Porcentaje';
|
||||
const complemento = (llave: string) => campo(validas, llave).map(v => v === null ? null : Math.round(10 * (100 - v)) / 10);
|
||||
// EEG results are two complementary lines; the normal one mirrors the abnormal share and its interval.
|
||||
const normal = data.id === M30_RESULTADO_EEG ? [
|
||||
banda(periodos.map(etiquetaPeriodo), complemento('ic_alto'), complemento('ic_bajo'), 'Intervalo de confianza (normal)', NORMAL_EEG, NORMAL_EEG + '40'),
|
||||
{ type: 'scatter', mode: 'lines+markers', name: 'EEG normal', x: periodos.map(etiquetaPeriodo), y: complemento('valor'), connectgaps: false,
|
||||
line: { color: NORMAL_EEG, width: 2 }, marker: { color: NORMAL_EEG },
|
||||
text: validas.map(row => row ? `${(row['denominador'] as number) - (row['numerador'] as number)} de ${row['denominador']}` : ''),
|
||||
hovertemplate: '%{x}<br>%{y} %<br>%{text}<extra></extra>' },
|
||||
] : [];
|
||||
return {
|
||||
figure: { data: [
|
||||
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno),
|
||||
@@ -142,7 +130,6 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
return `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}${intervalo}`;
|
||||
}),
|
||||
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
|
||||
...normal,
|
||||
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
|
||||
comoLeer: PIE_PORCENTAJE[data.id] ?? 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
|
||||
...(resultadoEeg ? { notaMetodologica: 'Resultado experimental. La proporción usa el primer EEG de buena calidad de cada niño en el periodo. La clasificación de EEG normal está pendiente de validación.' } : {}),
|
||||
|
||||
@@ -49,7 +49,7 @@ describe('Pestaña Histórico', () => {
|
||||
it('TEA tiene Trazabilidad y Análisis de Riesgo', () => {
|
||||
abrir('cama', []);
|
||||
abrir('tea', [item('tea_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
});
|
||||
it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Indicadores se oculta', () => {
|
||||
|
||||
@@ -105,17 +105,17 @@ describe('Figuras de histórico', () => {
|
||||
describe('Pestaña Histórico', () => {
|
||||
let http: HttpTestingController;
|
||||
let fixture: ComponentFixture<IndicadoresHistorico>;
|
||||
const catalog: Indicador[] = [{ id: 'm1', titulo: 'Uno', contrato: 'C1', figuras: [], tipos_periodo: ['semestre', 'mes'] }];
|
||||
const periodos = { id: 'm1', version: '1', periodos: [
|
||||
const catalog: Indicador[] = [{ id: 'M24_confirmacion_diagnostico', titulo: 'Uno', contrato: 'C1', figuras: [], tipos_periodo: ['semestre', 'mes'] }];
|
||||
const periodos = { id: 'M24_confirmacion_diagnostico', version: '1', periodos: [
|
||||
{ periodo: '2024-01', tipo: 'mes', report_id: 1, periodo_inicio: '2024-01-01', periodo_fin: '2024-02-01', fecha_corte: '2024-03-01', generado_en: '2024-03-01T00:00:00+00:00' },
|
||||
{ periodo: '2024-02', tipo: 'mes', report_id: 2, periodo_inicio: '2024-02-01', periodo_fin: '2024-03-01', fecha_corte: '2024-03-01', generado_en: '2024-03-01T00:00:00+00:00' },
|
||||
{ periodo: '2024-S1', tipo: 'semestre', report_id: 3, periodo_inicio: '2024-01-01', periodo_fin: '2024-07-01', fecha_corte: '2024-08-01', generado_en: '2024-08-01T00:00:00+00:00' },
|
||||
] };
|
||||
const datos = (tipo: string, ps: string[]) => ({ id: 'm1', contrato: 'C1', tipo_periodo: tipo, periodos: ps, filas: ps.map(p => c1(p, 50)) });
|
||||
const datosUrl = '/tea/indicadores/m1/datos';
|
||||
const datos = (tipo: string, ps: string[]) => ({ id: 'M24_confirmacion_diagnostico', contrato: 'C1', tipo_periodo: tipo, periodos: ps, filas: ps.map(p => c1(p, 50)) });
|
||||
const datosUrl = '/tea/indicadores/M24_confirmacion_diagnostico/datos';
|
||||
const render = () => { TestBed.tick(); fixture.detectChanges(); };
|
||||
const datos_ = (tipo: string, ps: string[]) => datos(tipo, ps);
|
||||
const abrir_ = () => { fixture.componentRef.setInput('active', true); render(); http.expectOne('/tea/indicadores/m1/periodos').flush(periodos); http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render(); };
|
||||
const abrir_ = () => { fixture.componentRef.setInput('active', true); render(); http.expectOne('/tea/indicadores/M24_confirmacion_diagnostico/periodos').flush(periodos); http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render(); };
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
@@ -129,9 +129,25 @@ describe('Pestaña Histórico', () => {
|
||||
afterEach(() => http.verify());
|
||||
const abrir = () => {
|
||||
fixture.componentRef.setInput('active', true); render();
|
||||
http.expectOne('/tea/indicadores/m1/periodos').flush(periodos);
|
||||
http.expectOne('/tea/indicadores/M24_confirmacion_diagnostico/periodos').flush(periodos);
|
||||
};
|
||||
|
||||
it('ignora periodos y consultas de indicadores TEA ocultos', () => {
|
||||
fixture.componentRef.setInput('catalog', [
|
||||
{ ...catalog[0], tipos_periodo: ['semestre'] },
|
||||
{ id: 'oculto', titulo: 'Oculto', contrato: 'C1', figuras: [], tipos_periodo: ['mes'] },
|
||||
]);
|
||||
fixture.componentRef.setInput('active', true); render();
|
||||
expect(fixture.componentInstance.tipos()).toEqual(['semestre']);
|
||||
expect(fixture.componentInstance.tipo()).toBe('semestre');
|
||||
http.expectNone('/tea/indicadores/oculto/periodos');
|
||||
http.expectOne('/tea/indicadores/M24_confirmacion_diagnostico/periodos').flush(periodos);
|
||||
http.expectOne(r => r.url === datosUrl).flush(datos('semestre', ['2024-S1'])); render();
|
||||
expect(fixture.componentInstance.paneles().map(p => p.item.id)).toEqual(['M24_confirmacion_diagnostico']);
|
||||
expect(fixture.nativeElement.querySelector('.rango').textContent).toContain('2024 S1');
|
||||
http.expectNone(r => r.url.includes('/oculto/'));
|
||||
});
|
||||
|
||||
it('no consulta hasta abrir la pestaña y entonces pide todos los periodos de una vez', () => {
|
||||
http.expectNone(() => true);
|
||||
abrir();
|
||||
@@ -157,7 +173,7 @@ describe('Pestaña Histórico', () => {
|
||||
const meses = Array.from({ length: 12 }, (_, i) => '2024-' + String(i + 1).padStart(2, '0'));
|
||||
const semestres = ['2020-S1', '2020-S2', '2021-S1', '2021-S2', '2022-S1', '2022-S2'];
|
||||
fixture.componentRef.setInput('active', true); render();
|
||||
http.expectOne('/tea/indicadores/m1/periodos').flush({ id: 'm1', periodos: [...meses.map(periodo => ({ periodo, tipo: 'mes' })), ...semestres.map(periodo => ({ periodo, tipo: 'semestre' }))] });
|
||||
http.expectOne('/tea/indicadores/M24_confirmacion_diagnostico/periodos').flush({ id: 'M24_confirmacion_diagnostico', periodos: [...meses.map(periodo => ({ periodo, tipo: 'mes' })), ...semestres.map(periodo => ({ periodo, tipo: 'semestre' }))] });
|
||||
http.expectOne(r => r.url === datosUrl).flush(datos('mes', meses)); render();
|
||||
expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 meses', 'Últimos 10 meses', 'Todos (12 meses)', 'Personalizado…']);
|
||||
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ene 2024 a dic 2024 (12 meses)');
|
||||
@@ -206,19 +222,18 @@ describe('Pestaña Histórico', () => {
|
||||
const grupo = paneles[0] as Extract<(typeof paneles)[number], { estado: 'listo' }>;
|
||||
expect(grupo.pasos!.map(p => (p.figura.figure.layout['yaxis'] as { range: number[] }).range[1])).toEqual([105, 105, 105]);
|
||||
expect(Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('.pasos h3'), el => el.textContent?.trim())).toEqual(pasos);
|
||||
// The notes live in the round help, not as text under the chart.
|
||||
expect((fixture.nativeElement as HTMLElement).querySelector('.panel:last-child p.nota')).toBeNull();
|
||||
expect((fixture.nativeElement as HTMLElement).querySelector('.panel:last-child p.nota')?.textContent?.trim()).toBe('Línea de EEG anormal: se detecta alguna alteración.');
|
||||
const ayuda = (fixture.nativeElement as HTMLElement).querySelector('.panel:last-child app-indicador-ayuda') as HTMLElement;
|
||||
ayuda.querySelector('button')!.click(); fixture.detectChanges();
|
||||
expect(ayuda.querySelector('.ayuda-texto')!.textContent).toContain('Resultado experimental.');
|
||||
});
|
||||
it('TEA ordena sus paneles como se pidió y deja al final lo que la lista no nombra', () => {
|
||||
it('TEA muestra solamente los paneles solicitados en orden', () => {
|
||||
// Fails if the catalog's own order shows through, if M30 does not close the list or if an unnamed indicator is dropped.
|
||||
const ids = ['M30_resultado_eeg', 'M29_calidad_eeg', 'otro', 'M28_casos_por_estado', 'M22_diagnosticados_sin_eeg', 'M21_diagnosticados_con_eeg', 'M24_confirmacion_diagnostico', 'M23_pacientes_evaluados'];
|
||||
fixture.componentRef.setInput('catalog', ids.map(id => ({ id, titulo: id, contrato: 'C2', figuras: [], tipos_periodo: ['mes'] })));
|
||||
render();
|
||||
expect(fixture.componentInstance.paneles().map(p => p.item.id)).toEqual(['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg',
|
||||
'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado', 'M29_calidad_eeg', 'M30_resultado_eeg', 'otro']);
|
||||
'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado', 'M29_calidad_eeg', 'M30_resultado_eeg']);
|
||||
});
|
||||
it('Personalizado abre el diálogo con los periodos del intervalo y muestra solo los elegidos', async () => {
|
||||
const c = fixture.componentInstance;
|
||||
@@ -256,7 +271,7 @@ describe('Pestaña Histórico', () => {
|
||||
});
|
||||
it('un indicador sin reportes del intervalo lo dice sin consultar sus datos', () => {
|
||||
fixture.componentRef.setInput('active', true); render();
|
||||
http.expectOne('/tea/indicadores/m1/periodos').flush({ ...periodos, periodos: [periodos.periodos[2]] }); render();
|
||||
http.expectOne('/tea/indicadores/M24_confirmacion_diagnostico/periodos').flush({ ...periodos, periodos: [periodos.periodos[2]] }); render();
|
||||
http.expectNone(r => r.url === datosUrl);
|
||||
expect(fixture.nativeElement.textContent).toContain('Sin reportes publicados');
|
||||
});
|
||||
|
||||
@@ -86,7 +86,7 @@ export function resaltarSerie(figura: PlotlyFigure, elegida: string): PlotlyFigu
|
||||
return { ...figura, data };
|
||||
}
|
||||
|
||||
// TEA's panels in the order of the request; whatever it does not name keeps the catalog's order after them.
|
||||
// TEA's requested panels in display order.
|
||||
const ORDEN_TEA = [...TIEMPOS, ...TEA_FIGURAS_CLINICAS, M30_RESULTADO_EEG];
|
||||
function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
const lugar = (panel: Panel) => { const i = orden.indexOf(panel.item.id); return i < 0 ? orden.length : i; };
|
||||
@@ -161,7 +161,7 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="vistas()[panel.item.id] ?? panel.figura.figure"
|
||||
[label]="etiquetaVista() + ' de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
}
|
||||
@if (panel.figura.comoLeer && dominio() !== 'tea') { <p class="nota">{{ panel.figura.comoLeer }}</p> }
|
||||
@if (panel.figura.comoLeer && (dominio() !== 'tea' || panel.item.id === 'M30_resultado_eeg')) { <p class="nota">{{ panel.figura.comoLeer }}</p> }
|
||||
@if (panel.figura.suprimidos.length) {
|
||||
<details class="nota-pie">
|
||||
<summary>Datos suprimidos</summary>
|
||||
@@ -262,7 +262,7 @@ export class IndicadoresHistorico {
|
||||
const config = this.config();
|
||||
return config
|
||||
? config.paneles.filter(entrada => !entrada.enDesarrollo).flatMap(entrada => this.catalog().filter(item => item.id === entrada.id))
|
||||
: this.catalog();
|
||||
: this.dominio() === 'tea' ? this.catalog().filter(item => ORDEN_TEA.includes(item.id)) : this.catalog();
|
||||
});
|
||||
// Only the granularities some indicator publishes; monthly first when there is one.
|
||||
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.publicados().some(item => item.tipos_periodo.includes(tipo))));
|
||||
@@ -365,9 +365,9 @@ export class IndicadoresHistorico {
|
||||
return { ...panelDe(item), item: { ...visible, contrato: item.contrato } };
|
||||
});
|
||||
}
|
||||
const items = this.catalog().filter(item => item.tipos_periodo.includes(tipo));
|
||||
const items = this.publicados().filter(item => item.tipos_periodo.includes(tipo));
|
||||
if (this.dominio() !== 'tea') return items.map(panelDe);
|
||||
const paneles = items.map(item => panelDe({ ...item, titulo: TITULOS_TEA[item.id] ?? item.titulo }));
|
||||
const paneles = items.filter(item => ORDEN_TEA.includes(item.id)).map(item => panelDe({ ...item, titulo: TITULOS_TEA[item.id] ?? item.titulo }));
|
||||
return agruparTiempos(ordenar(paneles, ORDEN_TEA));
|
||||
});
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ describe('UX-04 navegación Angular', () => {
|
||||
return RouterTestingHarness.create();
|
||||
}
|
||||
function load(domain: 'tea' | 'cacu' | 'cama', harness: RouterTestingHarness) {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(syntheticCatalogs[domain]);
|
||||
http.expectOne('/' + domain + '/indicadores').flush(domain === 'tea' ? [{ ...syntheticCatalogs.tea[0], id: 'M23_pacientes_evaluados' }] : syntheticCatalogs[domain]);
|
||||
harness.detectChanges();
|
||||
const page = harness.routeDebugElement!.componentInstance as IndicadoresPage;
|
||||
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { periodAvailabilityProvider } from './indicadores-periodos.testing';
|
||||
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
@@ -20,15 +20,15 @@ import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { figure?: PlotlyFigure; }
|
||||
const item: Indicador = { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre', 'mes'] };
|
||||
const second: Indicador = { ...item, id: 'i2', titulo: 'Dos', figuras: ['g'] };
|
||||
const item: Indicador = { id: 'M23_pacientes_evaluados', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre', 'mes'] };
|
||||
const second: Indicador = { ...item, id: 'M24_confirmacion_diagnostico', titulo: 'Dos', figuras: ['g'] };
|
||||
describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let page: IndicadoresPage;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider] });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
@@ -46,7 +46,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
function control(index = 0) { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))[index].componentInstance as IndicadorPeriodFilters; }
|
||||
|
||||
it('no presenta destacados retirados del catálogo ni consulta sus datos', () => {
|
||||
load();
|
||||
load([{ ...item, id: 'retirado' }]);
|
||||
expect(fixture.nativeElement.querySelector('#kpi-section-title')).toBeNull();
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card h3')).map(h => (h as HTMLElement).textContent))
|
||||
.toEqual([]);
|
||||
@@ -90,7 +90,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
expect(grid.children).toHaveLength(2);
|
||||
expect(Array.from(grid.children).every(host => host.tagName === 'APP-INDICADOR-CATALOG-CARD')).toBe(true);
|
||||
const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf<HTMLElement>;
|
||||
expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'graphic-section-title']);
|
||||
expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'kpi-section-title', 'graphic-section-title']);
|
||||
// Cada figura trae su tabla de valores: no hay resumen de indicadores al final de la página.
|
||||
expect(fixture.nativeElement.querySelector('app-indicadores-numeric-summary')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('indicadores publicados');
|
||||
@@ -161,7 +161,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
});
|
||||
it.each([0, 1, 2, 18, 37])('catálogo de %i conserva orden y no consulta figuras inicialmente', count => {
|
||||
const items = Array.from({ length: count }, (_, i) => ({ ...item, id: 'id-' + i }));
|
||||
load(items);
|
||||
http.expectOne('/tea/indicadores'); page.changeDominio('cacu'); load(items, 'cacu');
|
||||
expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id));
|
||||
expect(cards().every(c => !c.visible)).toBe(true);
|
||||
expect(panels()).toHaveLength(0); http.expectNone(r => r.url.includes('/figuras/'));
|
||||
@@ -232,7 +232,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
for (let i = 0; i < 2; i++) {
|
||||
button.click(); fixture.detectChanges();
|
||||
if (i === 0) {
|
||||
http.expectOne(r => r.url === '/tea/indicadores/i1/metadatos').flush({});
|
||||
http.expectOne(r => r.url === '/tea/indicadores/M23_pacientes_evaluados/metadatos').flush({});
|
||||
fixture.detectChanges();
|
||||
}
|
||||
expect(button.getAttribute('aria-expanded')).toBe(i === 0 ? 'true' : 'false');
|
||||
@@ -278,13 +278,13 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
expect(cards()[0].visible).toBe(false); expect(page.tema).toBe('claro'); http.expectNone(() => true);
|
||||
});
|
||||
it('identidades estables conservan componentes al reordenar el catálogo', () => {
|
||||
load(); toggle(); flushAll(); const card = cards()[0], panel = panels()[0];
|
||||
http.expectOne('/tea/indicadores'); page.changeDominio('cacu'); load([item, second], 'cacu'); toggle(); flushAll(); const card = cards()[0], panel = panels()[0];
|
||||
page.catalog.set([second, item]); fixture.detectChanges();
|
||||
expect(cards()[1]).toBe(card); expect(panels()[0]).toBe(panel); http.expectNone(() => true);
|
||||
});
|
||||
it('identidad eliminada no se monta aunque exista preferencia anterior', () => {
|
||||
TestBed.inject(IndicadoresMemory).rememberFigure('tea', 'removed', 'f1');
|
||||
load([second]); expect(cards().map(c => c.indicador.id)).toEqual(['i2']); flushAll();
|
||||
load([second]); expect(cards().map(c => c.indicador.id)).toEqual(['M24_confirmacion_diagnostico']); flushAll();
|
||||
});
|
||||
it('controles permanentes conservan IDs únicos y foco al salir del viewport', () => {
|
||||
load(); toggle(); flushAll();
|
||||
@@ -316,8 +316,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
expect(page.catalogError()).toContain('error interno'); expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
page.retryCatalog(); load([]); expect(panels()).toHaveLength(0);
|
||||
});
|
||||
it.each(['M02_sexo', 'K01_evaluacion_3_meses'])('UX-04A: %s conserva selección vacía estable al reabrir sin escrituras ni HTTP redundantes', async id => {
|
||||
load(syntheticCatalogs.tea);
|
||||
it.each(['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico'])('UX-04A: %s conserva selección vacía estable al reabrir sin escrituras ni HTTP redundantes', async id => {
|
||||
load([item, second]);
|
||||
const index = cards().findIndex(c => c.indicador.id === id);
|
||||
toggle(index); flushAll();
|
||||
const c = control(); c.select([]); fixture.detectChanges(); await fixture.whenStable();
|
||||
@@ -344,8 +344,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
it('IDs distintos con el mismo título y figura conservan paneles y etiquetas independientes', () => {
|
||||
load([{ ...item, figuras: ['f1'] }, { ...second, titulo: item.titulo, figuras: ['f1'] }]);
|
||||
toggle(0); toggle(1);
|
||||
const a = http.expectOne(r => r.url.endsWith('/i1/figuras/f1'));
|
||||
const b = http.expectOne(r => r.url.endsWith('/i2/figuras/f1'));
|
||||
const a = http.expectOne(r => r.url.endsWith('/M23_pacientes_evaluados/figuras/f1'));
|
||||
const b = http.expectOne(r => r.url.endsWith('/M24_confirmacion_diagnostico/figuras/f1'));
|
||||
a.flush({ data: [{ y: [1] }], layout: {} }); b.flush({ data: [{ y: [2] }], layout: {} }); fixture.detectChanges();
|
||||
expect(panels()[0].titleId).not.toBe(panels()[1].titleId);
|
||||
expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2]]);
|
||||
|
||||
@@ -47,7 +47,7 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
];
|
||||
const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
|
||||
const SECTIONS_TEA: typeof SECTIONS = [
|
||||
{ id: 'resumen', label: 'Resumen' }, { id: 'historico', label: 'Trazabilidad' }, { id: 'seguimiento', label: 'Análisis de Riesgo' }, SECTIONS[2],
|
||||
SECTIONS[0], { id: 'historico', label: 'Trazabilidad' }, { id: 'seguimiento', label: 'Análisis de Riesgo' }, SECTIONS[2],
|
||||
];
|
||||
const SECTIONS_CACU: typeof SECTIONS = [SECTIONS[0], { id: 'historico', label: 'Trazabilidad' }, SECTIONS[1], SECTIONS[2]];
|
||||
// Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered.
|
||||
@@ -440,7 +440,7 @@ export class IndicadoresPage {
|
||||
&& !CACU_FIGURAS_OPORTUNIDAD.some(figura => figura.id === item.id));
|
||||
return [...CACU_FIGURAS_CLINICAS.flatMap(id => clinicos.filter(item => item.id === id)), ...clinicos.filter(item => !CACU_FIGURAS_CLINICAS.includes(item.id))];
|
||||
}
|
||||
return this.dominio === 'tea' ? items.filter(item => !TEA_FIGURAS_OPORTUNIDAD.includes(item.id)) : items;
|
||||
return this.dominio === 'tea' ? items.filter(item => TEA_FIGURAS_CLINICAS.includes(item.id)) : items;
|
||||
});
|
||||
// CaMa's confirmation rate closes its clinical section: a number card, pending while the catalog does not publish it.
|
||||
readonly confirmacionCama = CAMA_CONFIRMACION_KPI;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { periodAvailabilityProvider } from './indicadores-periodos.testing';
|
||||
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
@@ -13,7 +13,7 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
|
||||
const items: Indicador[] = ['Edad', 'Evaluación inicial', 'Sexo', 'Seguimiento', 'Evaluación final'].map((titulo, i) => ({
|
||||
id: 'i' + i, titulo, contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'],
|
||||
id: ["M23_pacientes_evaluados","M24_confirmacion_diagnostico","M21_diagnosticados_con_eeg","M22_diagnosticados_sin_eeg","M28_casos_por_estado"][i], titulo, contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'],
|
||||
}));
|
||||
|
||||
describe('UX-06E.D.3.B fijación temporal', () => {
|
||||
@@ -25,7 +25,7 @@ describe('UX-06E.D.3.B fijación temporal', () => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined);
|
||||
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider,
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider,
|
||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
||||
create(); load();
|
||||
});
|
||||
@@ -41,78 +41,78 @@ describe('UX-06E.D.3.B fijación temporal', () => {
|
||||
|
||||
it('no muestra el control de fijar y la memoria no reordena las tarjetas', async () => {
|
||||
expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
|
||||
await pin('i3');
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(true);
|
||||
await pin('M22_diagnosticados_sin_eeg');
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'M22_diagnosticados_sin_eeg')).toBe(true);
|
||||
expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('i3');
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(false);
|
||||
await pin('M22_diagnosticados_sin_eeg');
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'M22_diagnosticados_sin_eeg')).toBe(false);
|
||||
expect(ids()).toEqual(items.map(i => i.id));
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('varios fijados no alteran el orden del catálogo', async () => {
|
||||
const original = page.catalog(), snapshot = JSON.stringify(original);
|
||||
await pin('i4'); await pin('i2'); await pin('i0');
|
||||
await pin('M28_casos_por_estado'); await pin('M21_diagnosticados_con_eeg'); await pin('M23_pacientes_evaluados');
|
||||
expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('i2'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('M21_diagnosticados_con_eeg'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true);
|
||||
});
|
||||
it('la selección de indicadores conserva el orden del catálogo', async () => {
|
||||
await pin('i3'); await pin('i4');
|
||||
page.changeIndicatorSelection(['i1', 'i3', 'i4']); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['i1', 'i3', 'i4']);
|
||||
await pin('i1'); expect(ids()).toEqual(['i1', 'i3', 'i4']);
|
||||
await pin('M22_diagnosticados_sin_eeg'); await pin('M28_casos_por_estado');
|
||||
page.changeIndicatorSelection(['M24_confirmacion_diagnostico', 'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado']); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['M24_confirmacion_diagnostico', 'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado']);
|
||||
await pin('M24_confirmacion_diagnostico'); expect(ids()).toEqual(['M24_confirmacion_diagnostico', 'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado']);
|
||||
expect(cards()).toHaveLength(3); http.expectNone(() => true);
|
||||
});
|
||||
it('Mostrar todos restaura el catálogo en su orden', async () => {
|
||||
await pin('i3'); page.changeIndicatorSelection(['i0']); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['i0']);
|
||||
await pin('M22_diagnosticados_sin_eeg'); page.changeIndicatorSelection(['M23_pacientes_evaluados']); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['M23_pacientes_evaluados']);
|
||||
expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
|
||||
page.showAllIndicators(); fixture.detectChanges(); await settle();
|
||||
expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(items.map(i => i.id)); http.expectNone(() => true);
|
||||
});
|
||||
it('un fijado sin seleccionar no se muestra', async () => {
|
||||
await pin('i2'); page.changeIndicatorSelection(['i0', 'i1']); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['i0', 'i1']); http.expectNone(() => true);
|
||||
await pin('M21_diagnosticados_con_eeg'); page.changeIndicatorSelection(['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico']); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico']); http.expectNone(() => true);
|
||||
});
|
||||
it('memoria independiente por dominio y persistente al recrear la página', async () => {
|
||||
await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('M22_diagnosticados_sin_eeg'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('M24_confirmacion_diagnostico'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
const memory = TestBed.inject(IndicadoresMemory);
|
||||
expect(memory.isPinned('cacu', 'i1')).toBe(true);
|
||||
expect(memory.isPinned('tea', 'i3')).toBe(true);
|
||||
expect(memory.isPinned('cama', 'i1')).toBe(false);
|
||||
expect(memory.isPinned('cacu', 'M24_confirmacion_diagnostico')).toBe(true);
|
||||
expect(memory.isPinned('tea', 'M22_diagnosticados_sin_eeg')).toBe(true);
|
||||
expect(memory.isPinned('cama', 'M24_confirmacion_diagnostico')).toBe(false);
|
||||
page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
page.changeDominio('tea'); load(); expect(ids()).toEqual(items.map(i => i.id));
|
||||
fixture.destroy(); create(); load();
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(true);
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'M22_diagnosticados_sin_eeg')).toBe(true);
|
||||
expect(ids()).toEqual(items.map(i => i.id)); http.expectNone(() => true);
|
||||
});
|
||||
it('no usa Storage y una nueva memoria reinicia la fijación', async () => {
|
||||
const read = vi.spyOn(Storage.prototype, 'getItem'), write = vi.spyOn(Storage.prototype, 'setItem');
|
||||
await pin('i2'); expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i2')).toBe(true);
|
||||
expect(new IndicadoresMemory().isPinned('tea', 'i2')).toBe(false);
|
||||
await pin('M21_diagnosticados_con_eeg'); expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'M21_diagnosticados_con_eeg')).toBe(true);
|
||||
expect(new IndicadoresMemory().isPinned('tea', 'M21_diagnosticados_con_eeg')).toBe(false);
|
||||
expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); http.expectNone(() => true);
|
||||
});
|
||||
it('fijar no mueve la tarjeta ni pide figuras', async () => {
|
||||
const before = cards();
|
||||
await pin('i4');
|
||||
await pin('M28_casos_por_estado');
|
||||
expect(cards()).toEqual(before);
|
||||
await pin('i4');
|
||||
await pin('M28_casos_por_estado');
|
||||
expect(cards()).toEqual(before); http.expectNone(() => true);
|
||||
});
|
||||
it('preserva figura seleccionada, estado de visibilidad, panel y host Plotly', async () => {
|
||||
card('i3').setVisible(true); fixture.detectChanges(); respond(); await settle();
|
||||
card('i3').selectFigure('g'); fixture.detectChanges(); respond(); await settle();
|
||||
card('M22_diagnosticados_sin_eeg').setVisible(true); fixture.detectChanges(); respond(); await settle();
|
||||
card('M22_diagnosticados_sin_eeg').selectFigure('g'); fixture.detectChanges(); respond(); await settle();
|
||||
|
||||
const before = cards(), panel = fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance;
|
||||
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
|
||||
const host = chart.host.nativeElement, result = panel.result(), applied = page.filters!.applied;
|
||||
const reacts = runtime.react.mock.calls.length, purges = runtime.purge.mock.calls.length;
|
||||
for (const id of ['i3', 'i1', 'i3']) {
|
||||
for (const id of ['M22_diagnosticados_sin_eeg', 'M24_confirmacion_diagnostico', 'M22_diagnosticados_sin_eeg']) {
|
||||
await pin(id);
|
||||
for (const c of before) expect(card(c.indicador.id)).toBe(c);
|
||||
expect(card('i3').visible).toBe(true); expect(card('i3').selectedFigure).toBe('g'); expect(card('i3').visible).toBe(true);
|
||||
expect(card('i1').visible).toBe(false);
|
||||
expect(card('M22_diagnosticados_sin_eeg').visible).toBe(true); expect(card('M22_diagnosticados_sin_eeg').selectedFigure).toBe('g'); expect(card('M22_diagnosticados_sin_eeg').visible).toBe(true);
|
||||
expect(card('M24_confirmacion_diagnostico').visible).toBe(false);
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance).toBe(panel);
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance).toBe(chart);
|
||||
expect(chart.host.nativeElement).toBe(host); expect(panel.result()).toBe(result); expect(page.filters!.applied).toBe(applied);
|
||||
@@ -121,9 +121,9 @@ describe('UX-06E.D.3.B fijación temporal', () => {
|
||||
expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).toHaveBeenCalledTimes(purges);
|
||||
});
|
||||
it('mover un panel cargando conserva su petición sin cancelar ni duplicar', async () => {
|
||||
card('i4').setVisible(true); fixture.detectChanges(); const request = http.expectOne(r => r.url.endsWith('/i4/figuras/f'));
|
||||
card('M28_casos_por_estado').setVisible(true); fixture.detectChanges(); const request = http.expectOne(r => r.url.endsWith('/M28_casos_por_estado/figuras/f'));
|
||||
const panel = fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance;
|
||||
await pin('i4'); expect(request.cancelled).toBe(false);
|
||||
await pin('M28_casos_por_estado'); expect(request.cancelled).toBe(false);
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance).toBe(panel); http.expectNone(() => true);
|
||||
request.flush({ data: [{ y: [7] }], layout: {} }); await settle(); expect(panel.result().figure.data[0].y).toEqual([7]);
|
||||
});
|
||||
|
||||
@@ -27,7 +27,7 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () =>
|
||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
||||
fixture = TestBed.createComponent(IndicadoresPage);
|
||||
vi.spyOn(fixture.componentInstance as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'] }, { id: 'j', titulo: 'J', contrato: 'C1', figuras: ['g'], tipos_periodo: ['semestre'] }]);
|
||||
http.expectOne('/tea/indicadores').flush([{ id: 'M23_pacientes_evaluados', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'] }, { id: 'M24_confirmacion_diagnostico', titulo: 'J', contrato: 'C1', figuras: ['g'], tipos_periodo: ['semestre'] }]);
|
||||
fixture.detectChanges();
|
||||
for (const entry of fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard))) (entry.componentInstance as IndicadorCatalogCard).setVisible(true);
|
||||
fixture.detectChanges();
|
||||
@@ -42,8 +42,8 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () =>
|
||||
respond(); await settle(); const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
||||
expect(charts).toHaveLength(2); expect(runtime.react).toHaveBeenCalledTimes(2);
|
||||
const hosts = charts.map(c => c.componentInstance.host.nativeElement);
|
||||
expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea, i, f');
|
||||
expect(hosts[1].getAttribute('aria-label')).toBe('tea, j, g');
|
||||
expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea, M23_pacientes_evaluados, f');
|
||||
expect(hosts[1].getAttribute('aria-label')).toBe('tea, M24_confirmacion_diagnostico, g');
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
||||
fixture.componentInstance.catalog.set(fixture.componentInstance.catalog().slice(1)); fixture.detectChanges();
|
||||
expect(runtime.purge).toHaveBeenCalledWith(hosts[0]);
|
||||
@@ -59,7 +59,7 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () =>
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
||||
card.selectFigure('g'); fixture.detectChanges();
|
||||
expect(runtime.purge).toHaveBeenCalledWith(outgoing); expect(runtime.purge).not.toHaveBeenCalledWith(other);
|
||||
http.expectOne(r => r.url.endsWith('/i/figuras/g')).flush({ data: [{ y: [3] }], layout: {} }); await settle();
|
||||
http.expectOne(r => r.url.endsWith('/M23_pacientes_evaluados/figuras/g')).flush({ data: [{ y: [3] }], layout: {} }); await settle();
|
||||
const current = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
||||
expect(current[0].componentInstance.host.nativeElement).not.toBe(outgoing);
|
||||
expect(current[1].componentInstance.host.nativeElement).toBe(other);
|
||||
|
||||
@@ -163,7 +163,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
|
||||
http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar();
|
||||
expect(e.page.seleccionSeguimiento()).toBeUndefined();
|
||||
expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(
|
||||
dominio === 'tea' ? ['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
dominio === 'tea' ? ['Indicadores', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
: ['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(e.root.querySelector('#panel-analisis')).toBeNull();
|
||||
}
|
||||
|
||||
@@ -11,11 +11,11 @@ import { Indicador } from './indicadores.models';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
|
||||
const items: Indicador[] = [
|
||||
{ id: 'A01', titulo: 'Edad', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'B02', titulo: 'Evaluación inicial', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'M02_sexo', titulo: 'Distribución por sexo', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'D04', titulo: 'Seguimiento', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'E05', titulo: 'Evaluación final', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'M23_pacientes_evaluados', titulo: 'Edad', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'M24_confirmacion_diagnostico', titulo: 'Evaluación inicial', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'M21_diagnosticados_con_eeg', titulo: 'Distribución por sexo', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'M22_diagnosticados_sin_eeg', titulo: 'Seguimiento', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'M28_casos_por_estado', titulo: 'Evaluación final', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
];
|
||||
|
||||
describe('Selección de indicadores gráficos', () => {
|
||||
@@ -42,7 +42,7 @@ describe('Selección de indicadores gráficos', () => {
|
||||
function choose(selection: string[]) { page.changeIndicatorSelection(selection); fixture.detectChanges(); }
|
||||
|
||||
it.each([0, 1, 2, 5])('no ofrece buscador y muestra el catálogo completo: %i indicadores', count => {
|
||||
load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i })));
|
||||
load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: items[i].id })));
|
||||
expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
|
||||
expect(cards()).toHaveLength(count);
|
||||
http.expectNone(() => true);
|
||||
@@ -57,12 +57,12 @@ describe('Selección de indicadores gráficos', () => {
|
||||
});
|
||||
it('solo renderiza los seleccionados y conserva las tarjetas que siguen visibles', () => {
|
||||
load(); const before = cards(), original = page.catalog();
|
||||
choose(['B02', 'E05']);
|
||||
expect(ids()).toEqual(['B02', 'E05']);
|
||||
choose(['M24_confirmacion_diagnostico', 'M28_casos_por_estado']);
|
||||
expect(ids()).toEqual(['M24_confirmacion_diagnostico', 'M28_casos_por_estado']);
|
||||
expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]);
|
||||
expect(page.selectionSummary()).toBe('2 indicadores');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('indicadores publicados');
|
||||
choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo');
|
||||
choose(['M21_diagnosticados_con_eeg']); expect(ids()).toEqual(['M21_diagnosticados_con_eeg']); expect(page.selectionSummary()).toBe('Distribución por sexo');
|
||||
expect(page.catalog()).toBe(original);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
@@ -75,25 +75,25 @@ describe('Selección de indicadores gráficos', () => {
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('marcar todos equivale a no filtrar', () => {
|
||||
load(); choose(['A01']); choose(items.map(i => i.id));
|
||||
load(); choose(['M23_pacientes_evaluados']); choose(items.map(i => i.id));
|
||||
expect(page.indicatorSelection()).toBeNull(); expect(page.selectionSummary()).toBe('Todos los indicadores');
|
||||
});
|
||||
it('los indicadores destacados no dependen de la selección', () => {
|
||||
load(); const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'));
|
||||
choose(['A01']);
|
||||
choose(['M23_pacientes_evaluados']);
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'))).toEqual(kpis);
|
||||
});
|
||||
it('ir a un indicador oculto lo vuelve a mostrar y desplaza hasta su tarjeta', async () => {
|
||||
const scroll = vi.fn();
|
||||
Element.prototype.scrollIntoView = scroll;
|
||||
load(); choose(['A01']);
|
||||
load(); choose(['M23_pacientes_evaluados']);
|
||||
expect(document.querySelector('.indicator-select-panel')).toBeNull();
|
||||
page.goToIndicator('D04'); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
|
||||
page.goToIndicator('M22_diagnosticados_sin_eeg'); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(page.selectedIndicators()).toEqual(['M23_pacientes_evaluados', 'M22_diagnosticados_sin_eeg']);
|
||||
await vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(1); });
|
||||
expect((scroll.mock.contexts[0] as HTMLElement).querySelector('h2')?.textContent).toContain('Seguimiento');
|
||||
page.goToIndicator('A01'); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
|
||||
page.goToIndicator('M23_pacientes_evaluados'); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(page.selectedIndicators()).toEqual(['M23_pacientes_evaluados', 'M22_diagnosticados_sin_eeg']);
|
||||
await vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(2); });
|
||||
http.match(() => true).forEach(r => r.flush({ data: [], layout: {} }));
|
||||
});
|
||||
@@ -103,7 +103,7 @@ describe('Selección de indicadores gráficos', () => {
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('cambiar de dominio restablece la selección', () => {
|
||||
load(); choose(['A01']);
|
||||
load(); choose(['M23_pacientes_evaluados']);
|
||||
page.changeDominio('cacu'); fixture.detectChanges(); expect(page.indicatorSelection()).toBeNull();
|
||||
load(items, 'cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
});
|
||||
|
||||
@@ -39,7 +39,7 @@ describe('Secciones compartidas por dominio', () => {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
|
||||
const root = harness.routeNativeElement!;
|
||||
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||
const esperadas = domain === 'tea' ? ['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
const esperadas = domain === 'tea' ? ['Indicadores', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
: ['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones'];
|
||||
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
|
||||
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
|
||||
|
||||
@@ -73,12 +73,12 @@ describe('Indicadores de TEA: figuras de oportunidad y clínicas', () => {
|
||||
expect(root().querySelector('app-tea-resumen-periodo')).toBeNull();
|
||||
});
|
||||
|
||||
it('la primera pestaña se llama Resumen en TEA e Indicadores en CaCu y CaMa', () => {
|
||||
it('la primera pestaña se llama Indicadores en todos los dominios', () => {
|
||||
// Fails if TEA's first tab loses its name, if CaCu or CaMa take it, or if the section id changes.
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) {
|
||||
open(domain, [item(domain + '_x', 'Indicador', 'C2', ['fig_c2_barras'])]);
|
||||
const first = root().querySelector('[role="tab"]') as HTMLElement;
|
||||
expect(first.textContent?.trim()).toBe(domain === 'tea' ? 'Resumen' : 'Indicadores');
|
||||
expect(first.textContent?.trim()).toBe('Indicadores');
|
||||
expect(first.id).toBe('tab-resumen');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -18,7 +18,7 @@ import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
const items: Indicador[] = Array.from({ length: 5 }, (_, i) => ({
|
||||
id: 'i' + i, titulo: 'Indicador ' + i, contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'],
|
||||
id: ["M23_pacientes_evaluados","M24_confirmacion_diagnostico","M21_diagnosticados_con_eeg","M22_diagnosticados_sin_eeg","M28_casos_por_estado"][i], titulo: 'Indicador ' + i, contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'],
|
||||
}));
|
||||
|
||||
// jsdom geometry and browser notifications are explicit, independent inputs.
|
||||
@@ -104,9 +104,9 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
||||
expect(frames.size).toBe(0);
|
||||
}
|
||||
|
||||
it.each([{ domain: 'tea', count: 18 }, { domain: 'cacu', count: 8 }] as const)('%s no descarga todas las figuras al abrir', async ({ domain, count }) => {
|
||||
it.each([{ domain: 'tea', count: 5 }, { domain: 'cacu', count: 18 }] as const)('%s no descarga todas las figuras al abrir', async ({ domain, count }) => {
|
||||
if (domain !== 'tea') { http.expectOne('/tea/indicadores'); page.changeDominio(domain); }
|
||||
await load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'i' + i })), domain);
|
||||
await load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: domain === 'tea' ? items[i].id : 'i' + i })), domain);
|
||||
await idle(); expect(cards()).toHaveLength(count); expect(panels()).toHaveLength(count);
|
||||
expect(panels().every(p => p.result().status === 'deferred')).toBe(true); http.expectNone(() => true);
|
||||
expect(fixture.nativeElement.querySelectorAll('app-indicador-catalog-card header button')).toHaveLength(0);
|
||||
@@ -159,13 +159,13 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
||||
expect(panels()[0]).toBe(panel); expect(panel.result().status).toBe('deferred');
|
||||
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); http.expectNone(() => true);
|
||||
positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm();
|
||||
const request = http.expectOne(r => r.url.includes('/i0/figuras/'));
|
||||
const request = http.expectOne(r => r.url.includes('/M23_pacientes_evaluados/figuras/'));
|
||||
expect(request.request.params.get('periodos')).toBe('2025-S2'); expect(request.request.params.get('tema')).toBe('oscuro');
|
||||
request.flush({ data: [{ y: [2] }], layout: {} }); await render(); notify(); await idle(); http.expectNone(() => true);
|
||||
});
|
||||
it('aplicar antes del frame de scroll relee geometría y cancela petición obsoleta sin nueva descarga', async () => {
|
||||
await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm();
|
||||
const old = http.expectOne(r => r.url.includes('/i0/figuras/'));
|
||||
const old = http.expectOne(r => r.url.includes('/M23_pacientes_evaluados/figuras/'));
|
||||
positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll'));
|
||||
page.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S1'] }; page.applyFilters(); await render();
|
||||
expect(old.cancelled).toBe(true); expect(panels()[0].result().status).toBe('deferred'); http.expectNone(() => true);
|
||||
@@ -189,7 +189,7 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
||||
// Pins no longer reorder; the selected indicators keep catalog order and their components.
|
||||
expect(cards()).toEqual([before[3], before[4]]);
|
||||
positions(cards().map((_, i) => [i === 0 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
|
||||
http.expectOne(r => r.url.includes('/i3/figuras/')).flush({ data: [], layout: {} }); await render();
|
||||
http.expectOne(r => r.url.includes('/M22_diagnosticados_sin_eeg/figuras/')).flush({ data: [], layout: {} }); await render();
|
||||
expect(cards()[0].selectedFigure).toBe('f');
|
||||
});
|
||||
it.each([{ data: [], layout: {} }, { data: [{ y: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }])('resultado vacío o suprimido termina skeleton y conserva JSON: %j', async figure => {
|
||||
|
||||
@@ -34,13 +34,15 @@ describe('Resumen TEA por periodo', () => {
|
||||
// or if a median is cut (22.5 stays 22.5).
|
||||
const root: HTMLElement = render(completos()).nativeElement;
|
||||
const text = texto(root);
|
||||
expect(text).toContain('Al cierre del periodo 2025-S2, se evaluaron 100 niños entre 16 y 36 meses; 15 únicamente tienen M-CHAT, 15 hasta la evaluación psicológica y 70 presentan evaluación neuropediátrica.');
|
||||
expect(text).toContain('En este periodo el 86.5% de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0).');
|
||||
expect(text).toContain('Las ventanas de tiempo* de tamizaje son: 8 días de M-CHAT (psicología) a ADOS-2, 14 días de ADOS-2 a diagnóstico. El tiempo* de tamizaje completo de M-CHAT a diagnóstico fue de 22.5 días.');
|
||||
expect(text).toContain('De los 57 niños con diagnóstico confirmado en este periodo, 41 presentan estudio de EEG y faltan 16 por realizarlo. De los 41 estudios de EEG, 25.0% tienen buena calidad.');
|
||||
expect(text).toContain('Al cierre del periodo 2025-S2, se evaluaron 100 niños de la cohorte de tamizaje; 15 únicamente tienen M-CHAT, 15 hasta la evaluación psicológica y 70 presentan evaluación neuropediátrica.');
|
||||
expect(text).toContain('La cohorte incluye a niños de 16 a 36 meses al primer M-CHAT y a niños sin edad registrada.');
|
||||
expect(text).toContain('En este periodo el 86.5% de los pacientes en tamizaje con diagnóstico confirmado o en proceso tiene diagnóstico confirmado de TEA (CIE-10 F84.0).');
|
||||
expect(text).toContain('Las ventanas de tiempo* de tamizaje son: 8 días de M-CHAT (psicología) a ADOS-2, 14 días de ADOS-2 a diagnóstico. El tiempo* de tamizaje completo de M-CHAT a diagnóstico positivo fue de 22.5 días.');
|
||||
expect(text).toContain('De los 57 niños con diagnóstico confirmado al cierre del periodo, 41 tienen un EEG de buena calidad y 16 aún no cuentan con uno de esa calidad.');
|
||||
expect(text).toContain('De los 80 estudios de EEG realizados a niños de la cohorte en el periodo, 25.0% tienen buena calidad.');
|
||||
expect(text).toContain('*tomando la mediana de los tiempos');
|
||||
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim()))
|
||||
.toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '41', '25.0%']);
|
||||
.toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '80', '25.0%']);
|
||||
expect(root.querySelector('button')).toBeNull();
|
||||
expect(root.querySelector('h2')!.textContent).toBe('Resumen');
|
||||
});
|
||||
@@ -56,8 +58,10 @@ describe('Resumen TEA por periodo', () => {
|
||||
const periodo = '2026-03';
|
||||
for (const p of paneles) p.result.set({ ...p.result(), period: periodo });
|
||||
const text = texto(render(paneles, periodo).nativeElement);
|
||||
expect(text).toContain('se evaluaron 3 niños entre 16 y 36 meses; 1 únicamente tienen M-CHAT, 1 hasta la evaluación psicológica y 1 presentan');
|
||||
expect(text).toContain('De los 1 niños con diagnóstico confirmado en este periodo, 0 presentan estudio de EEG y faltan 1 por realizarlo. De los 0 estudios de EEG, 25.0% tienen buena calidad.');
|
||||
expect(text).toContain('Al cierre del periodo 2026-03, se evaluaron 3 niños de la cohorte de tamizaje; 1 únicamente tienen M-CHAT');
|
||||
expect(text).toContain('54.5 días de M-CHAT (psicología) a ADOS-2, 9 días de ADOS-2 a diagnóstico.');
|
||||
expect(text).toContain('De los 1 niños con diagnóstico confirmado al cierre del periodo, 0 tienen un EEG de buena calidad y 1 aún no cuentan con uno de esa calidad.');
|
||||
expect(text).toContain('De los 4 estudios de EEG realizados a niños de la cohorte en el periodo, 25.0% tienen buena calidad.');
|
||||
for (const ejemplo of ['47', '155.5', '18.6', '54 días', '97 días', '##']) expect(text).not.toContain(ejemplo);
|
||||
});
|
||||
|
||||
@@ -67,16 +71,15 @@ describe('Resumen TEA por periodo', () => {
|
||||
paneles[3].result.set(c1('0.0', 0, 57)); paneles[4].result.set(c1('100.0', 57, 57));
|
||||
paneles[7].result.set({ ...listo(0), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 0 } });
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(texto(root)).toContain('0 presentan estudio de EEG y faltan 57 por realizarlo. De los 0 estudios de EEG, sin dato (Sin estudios de EEG en el periodo) tienen buena calidad.');
|
||||
expect(texto(root)).toContain('0 tienen un EEG de buena calidad y 57 aún no cuentan con uno de esa calidad. No se registraron estudios de EEG en el periodo.');
|
||||
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())).toContain('0');
|
||||
});
|
||||
|
||||
it('incluye los estudios sin analizar en el total de EEG del periodo', () => {
|
||||
// Fails if the share of good quality leaves the unanalysed studies out of its denominator.
|
||||
const paneles = completos();
|
||||
paneles[7].result.set({ ...listo(6), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 6 } });
|
||||
expect(texto(render(paneles).nativeElement))
|
||||
.toContain('estudios de EEG, 0.0% tienen buena calidad.');
|
||||
.toContain('De los 6 estudios de EEG realizados a niños de la cohorte en el periodo, 0.0% tienen buena calidad.');
|
||||
});
|
||||
|
||||
it('muestra «sin dato» si falta, está oculto, es de otro periodo o no está publicado', () => {
|
||||
@@ -94,7 +97,7 @@ describe('Resumen TEA por periodo', () => {
|
||||
const paneles = completos();
|
||||
paneles[4].result.set({ ...c1('28.1', 16, 58), period: '2025-S1' });
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(texto(root)).toContain('De los 57 niños con diagnóstico confirmado en este periodo, 41 presentan estudio de EEG');
|
||||
expect(texto(root)).toContain('De los 57 niños con diagnóstico confirmado al cierre del periodo, 41 tienen un EEG de buena calidad');
|
||||
expect(root.querySelector('.dato.sin-dato')?.getAttribute('title')).toBe('Sin datos para el periodo seleccionado');
|
||||
});
|
||||
|
||||
@@ -104,7 +107,7 @@ describe('Resumen TEA por periodo', () => {
|
||||
paneles[4].result.set(c1('28.1', 16, 58));
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(Array.from(root.querySelectorAll('.dato.sin-dato')).map(e => e.getAttribute('title')))
|
||||
.toEqual(Array(4).fill('Las poblaciones de M21 y M22 no coinciden'));
|
||||
.toEqual(Array(3).fill('Las poblaciones de M21 y M22 no coinciden'));
|
||||
});
|
||||
|
||||
it('indica la carga y reintenta solo las consultas con error', () => {
|
||||
|
||||
@@ -19,23 +19,40 @@ const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M2
|
||||
<article class="resumen" [attr.aria-busy]="cargando" aria-labelledby="tea-resumen-titulo">
|
||||
<h2 id="tea-resumen-titulo">Resumen</h2>
|
||||
<p>
|
||||
Al cierre del periodo <span class="dato listo">{{ periodo }}</span>, se evaluaron <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M28_casos_por_estado', '') }" /> niños entre 16 y 36 meses;
|
||||
Al cierre del periodo <span class="dato listo">{{ periodo }}</span>, se evaluaron <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M28_casos_por_estado', '') }" /> niños de la cohorte de tamizaje;
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['SOLO_MCHAT']) }" /> únicamente tienen M-CHAT,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['PSICOLOGIA']) }" /> hasta la evaluación psicológica y
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(conNeuropediatria) }" /> presentan evaluación neuropediátrica.
|
||||
</p>
|
||||
<p class="nota">La cohorte incluye a niños de 16 a 36 meses al primer M-CHAT y a niños sin edad registrada.</p>
|
||||
<p>
|
||||
En este periodo el <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M24_confirmacion_diagnostico', '%') }" />
|
||||
de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0).
|
||||
de los pacientes en tamizaje con diagnóstico confirmado o en proceso tiene diagnóstico confirmado de TEA (CIE-10 F84.0).
|
||||
</p>
|
||||
<p>
|
||||
Las ventanas de tiempo<sup>*</sup> de tamizaje son: <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M26_dias_mchat_ados2', ' días') }" /> de M-CHAT (psicología) a ADOS-2,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M27_dias_ados2_diagnostico', ' días') }" /> de ADOS-2 a diagnóstico.
|
||||
El tiempo<sup>*</sup> de tamizaje completo de M-CHAT a diagnóstico fue de
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M25_dias_mchat_diagnostico', ' días') }" />.
|
||||
<br>
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: confirmados() }" /> niños con diagnóstico confirmado en este periodo,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: conEegBueno() }" /> presentan estudio de EEG y faltan
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: sinEegBueno() }" /> por realizarlo.
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: conEegBueno() }" /> estudios de EEG,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: buenaCalidad() }" /> tienen buena calidad.
|
||||
</p>
|
||||
<p>
|
||||
El tiempo<sup>*</sup> de tamizaje completo de M-CHAT a diagnóstico positivo fue de
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M25_dias_mchat_diagnostico', ' días') }" />.
|
||||
</p>
|
||||
<p>
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: confirmados() }" /> niños con diagnóstico confirmado al cierre del periodo,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: conEegBueno() }" /> tienen un EEG de buena calidad y
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: sinEegBueno() }" /> aún no cuentan con uno de esa calidad.
|
||||
</p>
|
||||
@let estudios = valor('M29_calidad_eeg', '');
|
||||
@if (estudios.estado !== 'listo') {
|
||||
<p>Estudios de EEG del periodo: <ng-container *ngTemplateOutlet="dato; context: { $implicit: estudios }" />.</p>
|
||||
} @else if (estudios.texto === '0') {
|
||||
<p>No se registraron estudios de EEG en el periodo.</p>
|
||||
} @else {
|
||||
<p>
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: estudios }" /> estudios de EEG realizados a niños de la cohorte en el periodo,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: buenaCalidad() }" /> tienen buena calidad.
|
||||
</p>
|
||||
}
|
||||
<p class="nota">*tomando la mediana de los tiempos</p>
|
||||
@if (conError.length) {
|
||||
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button>
|
||||
|
||||
Reference in New Issue
Block a user