Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 26fe1ccbb3 | |||
| 94c63c460c | |||
| 05a9967906 | |||
| 1c0bdf6184 |
@@ -47,7 +47,10 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
expect(root.querySelector('form select[name="meses"]')).not.toBeNull();
|
||||
expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull();
|
||||
expect(root.textContent).not.toMatch(/Ronda|Espera|Motivo de revisión/);
|
||||
expect(root.querySelector('tbody tr td:last-child')?.textContent).toBe('No disponible');
|
||||
expect(root.querySelector('tbody tr td:nth-child(8)')?.textContent).toBe('No disponible');
|
||||
expect(root.querySelector('thead')?.textContent).not.toContain('Acciones');
|
||||
expect(root.querySelectorAll('tbody button.patient-link')).toHaveLength(10);
|
||||
expect(root.querySelector('tbody button.patient-link')?.getAttribute('aria-label')).toContain(fixture.componentInstance.data?.items[0].id_seudonimo);
|
||||
expect(latestStudy(seguimientoResponse(fixtureData).items[5])).toBe('2026-08-15');
|
||||
expect(latestStudy({...seguimientoResponse(fixtureData).items[0],ultima_citologia:null,ultimo_vph:null})).toBeNull();
|
||||
});
|
||||
|
||||
@@ -30,7 +30,7 @@ import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
<mat-card>
|
||||
<header>
|
||||
<div class="card-identity">
|
||||
<h2 [id]="titleId">{{ indicador.titulo }}</h2>
|
||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
||||
</div>
|
||||
</header>
|
||||
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
|
||||
|
||||
@@ -48,14 +48,14 @@
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>Distribución de resultados, {{ m.periodo }}</h3>
|
||||
@if (m.total !== null && m.total > 0 && donutFigure) {
|
||||
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'EU7, dona de dos anillos, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="'EU7, dona de dos anillos, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
} @else { <p role="status">{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado disponible para la dona.' }}</p> }
|
||||
<p>{{ sinDatoNote }}</p>
|
||||
</section>
|
||||
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico, {{ m.periodo }}</h3>
|
||||
<p>Porcentaje del total válido de cada escenario; excluye «Sin dato».</p>
|
||||
@if (m.escenarios.length && barsFigure) {
|
||||
<app-plotly-chart [figure]="barsFigure" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7, barras por escenario clínico, ' + m.periodo + ', ' + selectionLabel" />
|
||||
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7, barras por escenario clínico, ' + m.periodo + ', ' + selectionLabel" />
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -14,7 +14,7 @@ import { Indicador } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub {
|
||||
figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>();
|
||||
figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = input<boolean>();
|
||||
plotClick = output<unknown>();
|
||||
}
|
||||
describe('EU7 integración Angular y caché compartida', () => {
|
||||
@@ -46,6 +46,7 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
const kpi = TestBed.inject(IndicadoresSnapshots).datos('cacu', indicador.id, 'semestre', ['2025-S2'], indicador.version).subscribe();
|
||||
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
|
||||
flush(); expect(f.componentInstance.model!.total).toBe(946);
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => (chart.componentInstance as ChartStub).animated())).toEqual([true, true]);
|
||||
const scenarioFigure = f.nativeElement.querySelectorAll('.figure')[1] as HTMLElement;
|
||||
expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1);
|
||||
expect((f.componentInstance.barsFigure!.layout['annotations'] as { text: string }[])[0].text).toBe('682');
|
||||
@@ -70,10 +71,13 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
}
|
||||
f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } }); f.detectChanges(); flush();
|
||||
expect(f.componentInstance.model!.total).toBe(1892); expect(f.componentInstance.model!.escenarios[0].den).toBe(1364);
|
||||
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance as ChartStub);
|
||||
f.componentInstance.select('grupos', 1); f.componentInstance.changePeriod(1); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({}); expect(f.componentInstance.model!.periodo).toBe('2025-S2');
|
||||
expect(f.componentInstance.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682);
|
||||
expect(f.componentInstance.barsFigure!.layout['annotations']).toBeDefined();
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance)).toEqual(charts);
|
||||
expect(charts.map(chart => chart.animated())).toEqual([true, true]);
|
||||
expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2');
|
||||
expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true);
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorDatos, Dominio } from './indicadores.models';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
@@ -30,8 +30,19 @@ describe('KPI integración con autoridad global', () => {
|
||||
for (const request of http.match(r => r.url.endsWith('/periodos'))) request.flush({ id: request.request.url.split('/').at(-2), periodos: periods.map(periodo => ({ tipo: 'semestre', periodo })) });
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel); }
|
||||
function requests() { return http.match(r => r.url.endsWith('/datos')); }
|
||||
// Regression assertions below target the original KPI contracts. The added lab
|
||||
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
||||
// Satisfy its independent request with an explicit empty response, never diagnosis data.
|
||||
function originalRequests() {
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
for (const r of requests.filter(r => r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'))) {
|
||||
const period = r.request.params.get('periodos')!;
|
||||
r.flush({ id: CACU_RESULTADO_KPI.id, contrato: 'C3r', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [], filas: [] });
|
||||
}
|
||||
return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'));
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
|
||||
function requests() { return originalRequests(); }
|
||||
function response(index: number, domain: Dominio = 'cacu', period = '2025-S1'): IndicadorDatos {
|
||||
const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [
|
||||
{ periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] };
|
||||
@@ -92,7 +103,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
});
|
||||
it('el catálogo vigente retira los KPI que dejaron de publicarse', () => {
|
||||
load('cacu', true); expect(panels().map(p => p.definition.id)).toEqual(KPI_BY_DOMAIN.cacu.slice(1).map(d => d.id));
|
||||
expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(2);
|
||||
expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(4);
|
||||
const req = requests(); expect(req).toHaveLength(1); req.forEach((r,i) => r.flush(response(i+1)));
|
||||
});
|
||||
it.each([0, 1, 2])('retirar definiciones deja %i tarjetas y conserva filtros y valores retenidos', count => {
|
||||
@@ -107,8 +118,8 @@ describe('KPI integración con autoridad global', () => {
|
||||
expect(page.filters).toBe(state); expect(state).toEqual(snapshot);
|
||||
const grid = fixture.nativeElement.querySelector('.kpi-grid') as HTMLElement | null;
|
||||
if (count) {
|
||||
expect(grid!.children).toHaveLength(count + 1);
|
||||
expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count + 1));
|
||||
expect(grid!.children).toHaveLength(count + 3);
|
||||
expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count + 3));
|
||||
} else expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
page.kpisByDomain.cacu = definitions; page.catalog.set([...page.catalog()]); fixture.detectChanges();
|
||||
@@ -145,7 +156,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
if (scenario === 'nulo') data.filas[0]['mediana'] = null;
|
||||
if (scenario === 'sin filas') { data.filas = []; data.periodos = []; }
|
||||
requests().forEach((r, i) => r.flush(i === 1 ? data : response(i))); fixture.detectChanges();
|
||||
expect(panels()).toEqual(before); expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(3);
|
||||
expect(panels()).toEqual(before); expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(5);
|
||||
expect(panels()[1].result().state).toBe(scenario === 'suprimido' ? 'Dato oculto por tamaño' : scenario === 'nulo' ? 'Sin valor disponible' : 'Sin filas utilizables');
|
||||
expect(panels()[1].result().value).toBeUndefined(); http.expectNone(() => true);
|
||||
});
|
||||
@@ -164,10 +175,10 @@ describe('KPI integración con autoridad global', () => {
|
||||
req.forEach((r, i) => r.flush({ ...response(i, domain), notas: ['Nota del pie de la figura.'] }));
|
||||
fixture.detectChanges();
|
||||
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
|
||||
expect(cards).toHaveLength(3);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', '7', undefined] : ['5', '40.0', '7']);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', 'días (mediana)', undefined] : ['pacientes', '%', 'días (mediana)']);
|
||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Disponible', 'Indicador no disponible'] : ['Disponible', 'Disponible', 'Disponible']);
|
||||
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 3);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '40.0', '7']);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', '%', 'días (mediana)']);
|
||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : ['Disponible', 'Disponible', 'Disponible']);
|
||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('2025-S1'),
|
||||
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
|
||||
|
||||
@@ -49,6 +49,9 @@ export class IndicadorKpiPanel implements OnChanges {
|
||||
const applied = this.applied, definition = this.definition, domain = this.dominio;
|
||||
this.usedPeriod.set(undefined);
|
||||
if (!applied) return of({ state: 'Esperando filtro aplicado' });
|
||||
if (definition.singleAppliedPeriod && (applied.selection.mode !== 'explicit' || applied.selection.periodos.length !== 1)) {
|
||||
return of({ state: 'Selección no consolidable', info: 'Elige un único periodo aplicado para consultar esta mediana.' });
|
||||
}
|
||||
if (this.indicador && this.indicador.contrato !== definition.contrato) return of({ state: 'Error de contrato' });
|
||||
const compatible = filterCompatibility(applied, this.indicador?.tipos_periodo ?? [applied.tipo]);
|
||||
if (!compatible.compatible || !applied) return of({ state: 'Filtro incompatible', info: !compatible.compatible ? compatible.reason : '' });
|
||||
|
||||
@@ -78,18 +78,20 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
|
||||
page.filters!.editors[tipo] = { added: [], draft: { mode: 'explicit', periodos: selected } };
|
||||
page.applyFilters(); fixture.detectChanges();
|
||||
}
|
||||
it('encabezados, tres tarjetas en orden y placeholder inerte sin periodo, unidad ni HTTP', () => {
|
||||
it('encabezados, cinco tarjetas en orden y placeholders inertes sin periodo, unidad ni HTTP', () => {
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector('#kpi-section-title')?.textContent).toBe('Indicadores de oportunidad');
|
||||
expect(root.querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
const kpis = Array.from(root.querySelectorAll('.kpi-section app-indicador-kpi-card'));
|
||||
expect(kpis.map(k => k.querySelector('h3')?.textContent)).toEqual([
|
||||
'Pacientes evaluadas', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de diagnóstico a tratamiento',
|
||||
'Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento',
|
||||
]);
|
||||
expect(kpis[2].querySelectorAll('p')).toHaveLength(1);
|
||||
expect(kpis[2].querySelector('p')?.textContent).toBe('Indicador no disponible');
|
||||
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 3');
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(2);
|
||||
for (const kpi of kpis.slice(3)) {
|
||||
expect(kpi.querySelectorAll('p')).toHaveLength(1);
|
||||
expect(kpi.querySelector('p')?.textContent).toBe('Indicador no disponible');
|
||||
}
|
||||
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 5');
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(3);
|
||||
expect(root.querySelector('.kpi-section')?.textContent).not.toContain('detección histopatológica');
|
||||
expect(card('cacu_eu13')).toBeDefined();
|
||||
http.expectNone(() => true);
|
||||
|
||||
@@ -42,8 +42,11 @@ describe('EU7 modelo de presentación del entregable', () => {
|
||||
expect(m.escenarios.map((s, i) => selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0).toFixed(1)))
|
||||
.toEqual(['5.0', '24.3', '21.7', '7.8']);
|
||||
const category = barras(m, { categoria: 'LIEAG' }, 'claro');
|
||||
expect(category.data).toHaveLength(1);
|
||||
expect(category.data[0]['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!));
|
||||
// Same traces in every selection (animation identity); unselected ones are zero-width.
|
||||
expect(category.data.map(t => t['uid'])).toEqual(f.data.map(t => t['uid']));
|
||||
const lieag = category.data.find(t => t['uid'] === 'LIEAG')!;
|
||||
expect(lieag['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!));
|
||||
expect(category.data.filter(t => t !== lieag).every(t => (t['x'] as number[]).every(v => v === 0) && t['hoverinfo'] === 'skip')).toBe(true);
|
||||
expect((category.layout['annotations'] as { text: string }[]).map(a => a.text))
|
||||
.toEqual(m.escenarios.map(s => `<b>${percentNumber(100 * s.celdas['LIEAG'].n! / s.den!)} %</b> (${s.celdas['LIEAG'].n}/${s.den})`));
|
||||
expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]);
|
||||
@@ -74,7 +77,10 @@ describe('EU7 modelo de presentación del entregable', () => {
|
||||
else if (kind === 'total suprimido') Object.assign((data.escenarios['totales_estrato'] as any[])[0], { n: 123456, suprimido: 1 });
|
||||
else Object.assign(row, { n: kind === 'nulo' ? null : 123456, suprimido: kind === 'nulo' ? 0 : 1 });
|
||||
const m = model(), f = barras(m, { categoria: 'LIEAG' }, 'claro');
|
||||
expect(m.escenarios[0].den).toBeNull(); expect(f.data[0]['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]);
|
||||
expect(m.escenarios[0].den).toBeNull(); expect(f.data.find(t => t['uid'] === 'LIEAG')!['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]);
|
||||
expect(f.data.every(t => (t['x'] as unknown[])[0] === null)).toBe(true);
|
||||
expect(f.data.filter(t => t['uid'] !== 'LIEAG').every(t =>
|
||||
t['hoverinfo'] === 'skip' && (t['customdata'] as unknown[]).length === 0)).toBe(true);
|
||||
expect(JSON.stringify(f)).not.toContain('123456');
|
||||
expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull();
|
||||
});
|
||||
@@ -95,6 +101,7 @@ describe('EU7 modelo de presentación del entregable', () => {
|
||||
(data.escenarios['totales_estrato'] as any[]).forEach(t => t.n = 0);
|
||||
const m = model(); expect(m.total).toBe(0); expect(dona(m, {}, 'claro').data).toEqual([]);
|
||||
expect(barras(m, {}, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
|
||||
expect(barras(m, { categoria: 'LIEAG' }, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
|
||||
expect(barras(m, {}, 'claro').layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: 'Sin pacientes con resultado' })]));
|
||||
});
|
||||
it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => {
|
||||
@@ -102,4 +109,20 @@ describe('EU7 modelo de presentación del entregable', () => {
|
||||
const m = model(); expect(m.vacio).toBe(true); expect(m.total).toBe(0); expect(m.escenarios).toEqual([]);
|
||||
expect(m.celdas['NORMAL'].n).toBeNull();
|
||||
});
|
||||
it('selección jerárquica y Volver conservan UID, orden, denominadores y datos fuente', () => {
|
||||
const original = structuredClone(data), m = model(), snapshot = structuredClone(m);
|
||||
const ids = m.categorias.map(c => c.id);
|
||||
for (const selection of [{}, { grupo: 'ANORMAL' }, { grupo: 'ANORMAL', categoria: 'LIEAG' }, { categoria: 'LIEAG' }, {}]) {
|
||||
const f = barras(m, selection, 'claro');
|
||||
expect(f.data.map(t => t['uid'])).toEqual(ids);
|
||||
expect(new Set(f.data.map(t => t['uid'])).size).toBe(ids.length);
|
||||
f.data.forEach((t, i) => {
|
||||
if (t['hoverinfo'] === 'skip') {
|
||||
expect(t['customdata']).toEqual([]); expect(t['text']).toEqual(m.escenarios.map(() => ''));
|
||||
} else expect(t['x']).toEqual(m.escenarios.map(s => porcentaje(s, ids[i])));
|
||||
});
|
||||
dona(m, selection, 'claro');
|
||||
}
|
||||
expect(m).toEqual(snapshot); expect(data).toEqual(original);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -217,13 +217,20 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
||||
const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id);
|
||||
const y = m.escenarios.map(s => escapar(s.etiqueta));
|
||||
const sumas = m.escenarios.map(s => s.den === null || s.den === 0 ? null : visibles.reduce((n, c) => n + porcentaje(s, c)!, 0));
|
||||
return { data: m.categorias.filter(c => visibles.includes(c.id)).map(c => {
|
||||
const x = m.escenarios.map(s => porcentaje(s, c.id));
|
||||
return { type: 'bar', orientation: 'h', name: escapar(c.etiqueta), y, x,
|
||||
marker: { color: c.color, line: { color: p.background, width: 1 } },
|
||||
text: x.map(v => v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle',
|
||||
customdata: m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]),
|
||||
hovertemplate: `%{y}<br>${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})<extra></extra>` };
|
||||
// Every category keeps its trace (same uid and count) so a selection animates;
|
||||
// an unselected category is a zero-width bar without text or hover, never data.
|
||||
return { data: m.categorias.map(c => {
|
||||
const visible = visibles.includes(c.id);
|
||||
const x = m.escenarios.map(s => {
|
||||
const value = porcentaje(s, c.id);
|
||||
return value === null ? null : visible ? value : 0;
|
||||
});
|
||||
return { type: 'bar', orientation: 'h', uid: c.id, name: escapar(c.etiqueta), y, x,
|
||||
marker: { color: c.color, line: { color: p.background, width: visible ? 1 : 0 } },
|
||||
text: x.map(v => visible && v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle',
|
||||
customdata: visible ? m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]) : [],
|
||||
...(visible ? { hovertemplate: `%{y}<br>${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})<extra></extra>` }
|
||||
: { hoverinfo: 'skip' }) };
|
||||
}), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65),
|
||||
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false,
|
||||
|
||||
@@ -10,7 +10,7 @@ import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { pending } from './indicadores-memory';
|
||||
import { Indicador } from './indicadores.models';
|
||||
|
||||
@@ -46,11 +46,22 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
valor: 50, numerador: 5, denominador: 10, mediana: 2, q1: 1, q3: 3, unidad: 'dias' }] };
|
||||
}
|
||||
function request(period: string) { return http.expectOne(r => r.url.endsWith(`/${definitions[0].id}/datos`) && r.params.get('periodos') === period); }
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel); }
|
||||
// Regression assertions below target the original KPI contracts. The added lab
|
||||
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
||||
// Satisfy its independent request with an explicit empty response, never diagnosis data.
|
||||
function originalRequests() {
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
for (const r of requests.filter(r => r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'))) {
|
||||
const period = r.request.params.get('periodos')!;
|
||||
r.flush({ id: CACU_RESULTADO_KPI.id, contrato: 'C3r', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [], filas: [] });
|
||||
}
|
||||
return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'));
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
|
||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
||||
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
|
||||
function flushPanels(period: string, expected = definitions.length - 1) {
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
const requests = originalRequests();
|
||||
expect(requests).toHaveLength(expected);
|
||||
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period);
|
||||
const index = definitions.findIndex(d => r.request.url.endsWith(`/${d.id}/datos`)); r.flush(data(index, period)); });
|
||||
@@ -114,13 +125,14 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
// ask /datos for the same shared period, including the partner hidden from the catalog.
|
||||
fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7 && !card.tiempos).length);
|
||||
const tiempos = http.match(r => r.url.endsWith('/datos'));
|
||||
expect(tiempos.some(r => r.request.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos')).toBe(domain === 'cacu');
|
||||
// P0-C.1 cached the same lab payload; the paired figure reuses it.
|
||||
expect(tiempos.some(r => r.request.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos')).toBe(false);
|
||||
for (const r of tiempos) { expect(r.request.params.get('periodos')).toBe(periods[1]); r.flush('', { status: 404, statusText: 'Missing' }); }
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('KPI secundarios sin datos no retroceden a otro periodo', () => {
|
||||
request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges();
|
||||
const requests = http.match(r => r.url.endsWith('/datos')); expect(requests).toHaveLength(definitions.length - 1);
|
||||
const requests = originalRequests(); expect(requests).toHaveLength(definitions.length - 1);
|
||||
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(periods[0]); r.flush('', { status: 404, statusText: 'Missing' }); });
|
||||
fixture.detectChanges(); expect(panels().slice(1).every(p => p.result().state === 'Sin datos del periodo')).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
@@ -191,7 +203,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
expect(page.kpiIndicator(definitions[0].id)).toBeUndefined();
|
||||
expect(panels()).toHaveLength(0); expect(cards()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos'));
|
||||
editor().select([periods[0]]); page.applyFilters(); fixture.detectChanges();
|
||||
http.match(r => r.url.endsWith('/datos')).forEach(r => {
|
||||
originalRequests().forEach(r => {
|
||||
const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos'));
|
||||
expect(index).toBeGreaterThan(0); r.flush(data(index, periods[0]));
|
||||
}); fixture.detectChanges();
|
||||
@@ -215,7 +227,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
value.filas[0].grupo = definitions[index].contrato === 'C1' && target !== 'tea' ? 'total' : 'TOTAL'; return value;
|
||||
};
|
||||
http.expectOne(r => r.url.endsWith('/' + definitions[0].id + '/datos')).flush(payload(0)); fixture.detectChanges();
|
||||
http.match(r => r.url.endsWith('/datos')).forEach(r => {
|
||||
originalRequests().forEach(r => {
|
||||
const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); r.flush(payload(index));
|
||||
}); fixture.detectChanges();
|
||||
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [period] });
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { Component, input } from '@angular/core';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter, ActivatedRoute } from '@angular/router';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { PARES_TIEMPOS } from './indicadores-tiempos-pareados';
|
||||
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); }
|
||||
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 1 };
|
||||
// Synthetic contract examples only; no value in these tests is a deployed clinical result.
|
||||
const payload = (period = '2025-S1', extra: Record<string, unknown> = {}): IndicadorDatos => ({
|
||||
id: CACU_RESULTADO_KPI.id, contrato: 'C3r', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period],
|
||||
filas: [{ periodo: period, grupo: 'TOTAL', estrato: null, n: 20, q1: 7, mediana: 12, q3: 20, unidad: 'dias', suprimido: 0, ...extra }],
|
||||
});
|
||||
|
||||
describe('P0-C.1: contrato de toma a resultado', () => {
|
||||
const read = (data: IndicadorDatos) => kpiResult(data, CACU_RESULTADO_KPI, 'cacu', applied);
|
||||
it('usa el ID del laboratorio del par, nunca la mediana de diagnóstico', () => {
|
||||
expect(CACU_RESULTADO_KPI.id).toBe(PARES_TIEMPOS.find(p => p.dominio === 'cacu')!.reporte);
|
||||
expect(read(payload())).toMatchObject({ state: 'Disponible', value: 12 });
|
||||
expect(CACU_RESULTADO_KPI.unit).toBe('días (mediana)');
|
||||
const diagnosis = { ...payload('2025-S1', { mediana: 52, q3: 90 }), id: KPI_BY_DOMAIN.cacu[1].id };
|
||||
expect(read(diagnosis).state).toBe('Error de contrato');
|
||||
expect(kpiResult(diagnosis, KPI_BY_DOMAIN.cacu[1], 'cacu', applied).value).toBe(52);
|
||||
});
|
||||
it.each([{ mediana: null }, { n: 0 }, { n: null }, { q1: null }, { unidad: 'meses' }, { q1: 15 }])('no inventa valor ante %j', extra => {
|
||||
expect(read(payload('2025-S1', extra))).toEqual({ state: 'Sin valor disponible' });
|
||||
});
|
||||
it('cero publicado es válido, supresión nunca expone cuantiles ni conteo', () => {
|
||||
expect(read(payload('2025-S1', { mediana: 0, q1: 0 })).value).toBe(0);
|
||||
expect(read(payload('2025-S1', { suprimido: 1 }))).toEqual({ state: 'Dato oculto por tamaño' });
|
||||
expect(read(payload('2025-S1', { suprimido: null })).value).toBeUndefined();
|
||||
});
|
||||
it('distingue vacío, periodo equivocado y selección no consolidable sin mezclar grupos o tipos', () => {
|
||||
expect(read({ ...payload(), filas: [], periodos: [] }).state).toBe('Sin filas utilizables');
|
||||
expect(read(payload('2025-S2')).state).toBe('Selección no consolidable');
|
||||
expect(read(payload('2025-01')).state).toBe('Error de contrato');
|
||||
expect(read({ ...payload(), filas: [...payload().filas, ...payload().filas] }).state).toBe('Selección no consolidable');
|
||||
expect(read(payload('2025-S1', { estrato: 'grupo_edad' })).state).toBe('Selección no consolidable');
|
||||
expect(kpiResult(payload(), CACU_RESULTADO_KPI, 'cacu', { ...applied, selection: { mode: 'todos' } }).state).toBe('Selección no consolidable');
|
||||
});
|
||||
});
|
||||
|
||||
describe('P0-C.1: transporte y periodo aplicado', () => {
|
||||
let f: ReturnType<typeof TestBed.createComponent<IndicadorKpiPanel>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorTiemposPareados, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
f = TestBed.createComponent(IndicadorKpiPanel);
|
||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('definition', CACU_RESULTADO_KPI);
|
||||
f.componentRef.setInput('applied', applied); f.detectChanges();
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.verify(); });
|
||||
const request = () => http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos');
|
||||
it('reutiliza la consulta idéntica en vuelo y completada de la gráfica mediante snapshots', () => {
|
||||
let received: IndicadorDatos | undefined;
|
||||
const snapshots = TestBed.inject(IndicadoresSnapshots);
|
||||
snapshots.datos('cacu', CACU_RESULTADO_KPI.id, 'semestre', ['2025-S1']).subscribe(data => received = data);
|
||||
const r = request(); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(payload());
|
||||
expect(received?.filas[0]['mediana']).toBe(12); expect(f.componentInstance.result().value).toBe(12);
|
||||
f.componentRef.setInput('applied', { ...applied, revision: 2 }); f.detectChanges();
|
||||
expect(f.componentInstance.result().value).toBe(12); http.expectNone(() => true);
|
||||
});
|
||||
it.each(['empty', '404', 'suppressed', 'error'] as const)('%s no dispara búsqueda de otro periodo', scenario => {
|
||||
const r = request();
|
||||
if (scenario === '404' || scenario === 'error') r.flush('private', { status: scenario === '404' ? 404 : 503, statusText: 'Unavailable' });
|
||||
else r.flush(scenario === 'empty' ? { ...payload(), filas: [], periodos: [] } : payload('2025-S1', { suprimido: 1 }));
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.result().state).toBe({ empty: 'Sin filas utilizables', '404': 'Sin datos del periodo', suppressed: 'Dato oculto por tamaño', error: 'Error de consulta' }[scenario]);
|
||||
expect(f.componentInstance.result().value).toBeUndefined(); expect(f.componentInstance.temporalReference).toBe('2025-S1');
|
||||
expect(f.nativeElement.textContent).not.toContain('private'); http.expectNone(() => true);
|
||||
});
|
||||
it('la gráfica pareada comparte la petición en vuelo y conserva ambas series originales', () => {
|
||||
const chart = TestBed.createComponent(IndicadorTiemposPareados);
|
||||
try {
|
||||
chart.componentRef.setInput('dominio', 'cacu'); chart.componentRef.setInput('tema', 'claro');
|
||||
chart.componentRef.setInput('par', PARES_TIEMPOS.find(p => p.dominio === 'cacu')!);
|
||||
chart.componentRef.setInput('indicador', { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', tipos_periodo: ['semestre'], figuras: ['fig_c3r_caja'] });
|
||||
chart.componentRef.setInput('applied', applied); chart.detectChanges();
|
||||
const lab = request(); expect(lab.request.params.get('periodos')).toBe('2025-S1');
|
||||
lab.flush(payload());
|
||||
http.expectOne(r => r.url.includes('/cacu_dias_toma_diagnostico/datos')).flush({ ...payload('2025-S1', { mediana: 52, q3: 90 }), id: 'cacu_dias_toma_diagnostico' });
|
||||
chart.detectChanges();
|
||||
expect(chart.componentInstance.figure!.data.map(series => series['name'])).toEqual(['Días de toma a resultado (laboratorio)', 'Días de toma a diagnóstico']);
|
||||
expect(chart.componentInstance.figure!.data.map(series => series['median'])).toEqual([[12], [52]]);
|
||||
expect(f.componentInstance.result().value).toBe(12); http.expectNone(() => true);
|
||||
} finally { chart.destroy(); }
|
||||
});
|
||||
it('Todos y varios periodos no consultan; un mes consulta únicamente ese mes', () => {
|
||||
const old = request();
|
||||
for (const selection of [{ mode: 'todos' as const }, { mode: 'explicit' as const, periodos: ['2025-S1', '2025-S2'] as [string, ...string[]] }]) {
|
||||
f.componentRef.setInput('applied', { ...applied, selection, revision: 2 }); f.detectChanges();
|
||||
expect(f.componentInstance.result().state).toBe('Selección no consolidable'); http.expectNone(() => true);
|
||||
}
|
||||
expect(old.cancelled).toBe(true);
|
||||
f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-02'] }, revision: 3 }); f.detectChanges();
|
||||
const r = request(); expect(r.request.params.get('periodos')).toBe('2025-02'); r.flush(payload('2025-02'));
|
||||
expect(f.componentInstance.result().value).toBe(12);
|
||||
});
|
||||
});
|
||||
|
||||
describe('P0-C.1: cinco tarjetas de oportunidad', () => {
|
||||
it('conserva los originales, agrega laboratorio y deja ambos tratamientos inertes', () => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([]),
|
||||
{ provide: ActivatedRoute, useValue: { snapshot: { data: { dominio: 'cacu' } } } }] });
|
||||
const f = TestBed.createComponent(IndicadoresPage), http = TestBed.inject(HttpTestingController);
|
||||
try {
|
||||
// The established lab partner is absent from this visible catalog, as in the paired figure.
|
||||
http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
|
||||
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ tipo: 'semestre', periodo: '2025-S1' }] }));
|
||||
http.expectOne(r => r.url.includes('/cacu_eu7/datos')).flush({ id: 'cacu_eu7', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: { A: {} }, filas: [{ periodo: '2025-S1', grupo: 'TOTAL', estrato: null, categoria: 'A', n: 20, suprimido: 0 }] });
|
||||
f.detectChanges();
|
||||
http.expectOne(r => r.url.includes('/cacu_eu_tiempo_reporte/datos')).flush(payload());
|
||||
http.expectOne(r => r.url.includes('/cacu_dias_toma_diagnostico/datos')).flush({ ...payload('2025-S1', { mediana: 52, q3: 90 }), id: 'cacu_dias_toma_diagnostico' });
|
||||
f.detectChanges();
|
||||
const cards = [...f.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||
expect(cards.map(c => c.querySelector('h3')!.textContent)).toEqual(['Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento']);
|
||||
expect(cards.map(c => c.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['20', '12', '52', undefined, undefined]);
|
||||
expect(cards.map(c => c.querySelector('.value span')?.textContent)).toEqual(['pacientes', 'días (mediana)', 'días (mediana)', undefined, undefined]);
|
||||
for (const card of cards.slice(3)) {
|
||||
expect(card.querySelectorAll('p')).toHaveLength(1); expect(card.querySelector('p')!.textContent).toBe('Indicador no disponible');
|
||||
}
|
||||
http.expectNone(() => true);
|
||||
} finally { f.destroy(); vi.unstubAllGlobals(); http.verify(); }
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,11 @@ import { Dominio, IndicadorDatos } from './indicadores.models';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { percentNumber } from './indicadores-format';
|
||||
|
||||
export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; }
|
||||
export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; singleAppliedPeriod?: boolean; }
|
||||
// Same laboratory-result source used by PARES_TIEMPOS; diagnosis has its own ID.
|
||||
export const CACU_RESULTADO_KPI: KpiDefinition = {
|
||||
id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
|
||||
};
|
||||
// Provisional (oct 2026): titles are copied by hand from the `title` of each indicator's TOML
|
||||
// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories
|
||||
// (patients), not the distribution. If a TOML title changes, change it here too, until the
|
||||
@@ -43,6 +47,7 @@ const unscoped = { state: 'Selección no consolidable', info: 'Elige un único p
|
||||
// C2 definitions count each patient once per period, in disjoint categories of TOTAL.
|
||||
// C1/C3r publish a single total row. Never combine totals, strata, or periods.
|
||||
export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domain: Dominio, applied: GlobalApplied): KpiResult {
|
||||
if (definition.singleAppliedPeriod && (applied.selection.mode !== 'explicit' || applied.selection.periodos.length !== 1)) return unscoped;
|
||||
if (data.id !== definition.id || data.contrato !== definition.contrato || data.tipo_periodo !== applied.tipo) {
|
||||
return { state: 'Error de contrato', info: 'Los datos recibidos no corresponden al indicador o periodo aplicado.' };
|
||||
}
|
||||
@@ -75,6 +80,6 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
|
||||
if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty;
|
||||
return { state: 'Disponible', value: percentNumber(row['valor']), info: C1_INFO[domain](row['numerador'], row['denominador']) };
|
||||
}
|
||||
if (!finite(row['mediana']) || !count(row['n']) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty;
|
||||
if (!finite(row['mediana']) || !count(row['n']) || (definition.id === CACU_RESULTADO_KPI.id && row['n'] === 0) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty;
|
||||
return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { Indicador } from './indicadores.models';
|
||||
import { identityElementId, indicatorIdentity } from './indicadores-identities';
|
||||
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
|
||||
import fixtureData from './fixtures/cacu_seguimiento.json';
|
||||
|
||||
const item = (id: string, titulo: string): Indicador => ({ id, titulo, contrato: 'C1', figuras: ['f-' + id], tipos_periodo: ['semestre'] });
|
||||
|
||||
describe('UX-10 navegación lateral del catálogo gráfico', () => {
|
||||
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, kpiQueriesProvider],
|
||||
});
|
||||
fixture = TestBed.createComponent(IndicadoresPage);
|
||||
page = fixture.componentInstance;
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
page.closeGraphicNavigation(false, false);
|
||||
fixture.detectChanges();
|
||||
http.match(request => request.url.endsWith('/seguimiento')).forEach(request => request.flush(fixtureData));
|
||||
http.match(request => request.url.endsWith('/metadatos')).forEach(request => request.flush({}));
|
||||
fixture.destroy();
|
||||
http.verify();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
async function load(items: Indicador[], domain: 'tea' | 'cacu' | 'cama' = 'tea') {
|
||||
if (domain !== page.dominio) {
|
||||
http.expectOne('/' + page.dominio + '/indicadores').flush([]);
|
||||
fixture.detectChanges();
|
||||
page.changeDominio(domain);
|
||||
}
|
||||
http.expectOne('/' + domain + '/indicadores').flush(items);
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
}
|
||||
|
||||
function trigger() { return fixture.nativeElement.querySelector('.graphic-navigation-trigger') as HTMLButtonElement | null; }
|
||||
function optionButtons() { return Array.from(document.querySelectorAll<HTMLButtonElement>('#indicator-navigation-panel .panel-list button')); }
|
||||
async function openPanel() {
|
||||
const button = trigger()!;
|
||||
button.focus();
|
||||
button.click();
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
return button;
|
||||
}
|
||||
function expectNoFigureRequests() { http.expectNone(request => request.url.includes('/figuras/') || request.url.endsWith('/datos')); }
|
||||
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('aparece solo en Resumen para el dominio %s', async domain => {
|
||||
await load([item('chart', 'Indicador gráfico')], domain);
|
||||
expect(trigger()).not.toBeNull();
|
||||
page.changeSection('seguimiento'); fixture.detectChanges();
|
||||
expect(trigger()).toBeNull();
|
||||
page.changeSection('datos'); fixture.detectChanges();
|
||||
expect(trigger()).toBeNull();
|
||||
page.changeSection('resumen'); fixture.detectChanges();
|
||||
page.fichaPacienteAbierta.set(true); fixture.detectChanges();
|
||||
expect(trigger()).toBeNull();
|
||||
page.fichaPacienteAbierta.set(false); fixture.detectChanges();
|
||||
expect(trigger()).not.toBeNull();
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('toma únicamente títulos y orden del catálogo visible, sin agregar KPI ni nombres alternos', async () => {
|
||||
const items = [item('a', 'Tasa visible exacta'), item('b', 'Distribución por edad')];
|
||||
await load(items, 'cacu');
|
||||
expect(page.showGraphicNavigation).toBe(true);
|
||||
await openPanel();
|
||||
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Tasa visible exacta', 'Distribución por edad']);
|
||||
expect(optionButtons().map(button => button.getAttribute('aria-label'))).toEqual(['Tasa visible exacta', 'Distribución por edad']);
|
||||
expect(optionButtons().some(button => button.textContent?.includes('Oportunidad') || button.textContent?.includes('destacado'))).toBe(false);
|
||||
expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-panel').length).toBe(0);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('presenta un popover compacto anclado al botón, sin backdrop ni bloqueo del scroll', async () => {
|
||||
await load([item('a', 'Uno'), item('b', 'Título largo del indicador')]);
|
||||
const button = trigger()!;
|
||||
vi.spyOn(button, 'getBoundingClientRect').mockReturnValue(new DOMRect(8, 180, 48, 48));
|
||||
const bodyOverflow = document.body.style.overflow;
|
||||
await openPanel();
|
||||
const panel = document.querySelector<HTMLElement>('.panel-shell')!;
|
||||
expect(page.navigationPositions[0]).toEqual({ originX: 'start', overlayX: 'start', originY: 'center', overlayY: 'center' });
|
||||
expect(panel.closest('.cdk-overlay-pane')).not.toBeNull();
|
||||
expect(document.querySelector('.cdk-overlay-backdrop')).toBeNull();
|
||||
expect(getComputedStyle(panel).maxHeight).toBe('min(58dvh, 32rem)');
|
||||
expect(bodyOverflow).toBe(document.body.style.overflow);
|
||||
expect(page.navigationScrollStrategy.constructor.name).toBe('RepositionScrollStrategy');
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('usa scroll interno en una lista extensa y se adapta al ancho disponible', async () => {
|
||||
await load(Array.from({ length: 30 }, (_, index) => item('indicator-' + index, 'Indicador clínico ' + index)));
|
||||
await openPanel();
|
||||
const panel = document.querySelector<HTMLElement>('.panel-shell')!;
|
||||
const list = panel.querySelector<HTMLElement>('.panel-list')!;
|
||||
expect(optionButtons()).toHaveLength(30);
|
||||
expect(getComputedStyle(panel).maxHeight).toBe('min(58dvh, 32rem)');
|
||||
expect(getComputedStyle(list).overflowY).toBe('auto');
|
||||
expect(getComputedStyle(panel.parentElement!).maxWidth).toBe('calc(100vw - 1rem)');
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('reubica el popover en viewports estrechos y conserva límites verticales', async () => {
|
||||
await load([item('one', 'Indicador')]);
|
||||
const previousWidth = window.innerWidth;
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, value: 320 });
|
||||
try {
|
||||
await openPanel();
|
||||
const panel = document.querySelector<HTMLElement>('.panel-shell')!;
|
||||
const host = panel.parentElement!;
|
||||
expect(getComputedStyle(host).maxWidth).toBe('calc(100vw - 1rem)');
|
||||
expect(page.navigationPositions).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ originX: 'end', overlayX: 'end' }),
|
||||
expect.objectContaining({ originY: 'bottom', overlayY: 'bottom' }),
|
||||
]));
|
||||
expect(panel.closest('.cdk-overlay-pane')).not.toBeNull();
|
||||
} finally {
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, value: previousWidth });
|
||||
}
|
||||
});
|
||||
|
||||
it('sigue el orden priorizado por búsqueda y fijación mientras el panel está abierto', async () => {
|
||||
await load([item('one', 'Alfa'), item('two', 'Beta'), item('three', 'Gamma')]);
|
||||
page.togglePinned(page.catalog()[2]);
|
||||
fixture.detectChanges();
|
||||
await openPanel();
|
||||
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Gamma', 'Alfa', 'Beta']);
|
||||
page.changeSearchQuery('beta');
|
||||
fixture.detectChanges();
|
||||
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Beta', 'Gamma', 'Alfa']);
|
||||
page.changeSearchQuery('sin coincidencias');
|
||||
fixture.detectChanges();
|
||||
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Gamma', 'Alfa', 'Beta']);
|
||||
page.searchQuery.set('');
|
||||
page.catalog.set([item('updated', 'Versión actualizada'), item('two', 'Beta')]);
|
||||
fixture.detectChanges();
|
||||
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Versión actualizada', 'Beta']);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('mantiene keys únicas para títulos duplicados y navega a la tarjeta elegida', async () => {
|
||||
const items = [item('duplicate-a', 'Resultado clínico'), item('duplicate-b', 'Resultado clínico')];
|
||||
await load(items, 'cama');
|
||||
const scroll = vi.fn();
|
||||
const focus = vi.spyOn(HTMLElement.prototype, 'focus');
|
||||
for (const card of fixture.nativeElement.querySelectorAll('app-indicador-catalog-card')) {
|
||||
card.scrollIntoView = scroll;
|
||||
}
|
||||
await openPanel();
|
||||
expect(optionButtons()).toHaveLength(2);
|
||||
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Resultado clínico', 'Resultado clínico']);
|
||||
optionButtons()[1].click();
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
const targetId = identityElementId(indicatorIdentity('cama', 'duplicate-b'));
|
||||
expect(scroll).toHaveBeenCalledOnce();
|
||||
expect(scroll.mock.instances[0]).toBe(fixture.nativeElement.querySelector('#' + targetId));
|
||||
expect(focus).toHaveBeenCalled();
|
||||
expect(document.activeElement).toBe(fixture.nativeElement.querySelector('#' + targetId + ' h2'));
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('abre con foco dentro, expone el estado expandido y cierra restaurando el foco con Escape', async () => {
|
||||
await load([item('one', 'Indicador')]);
|
||||
const button = await openPanel();
|
||||
expect(button.getAttribute('aria-expanded')).toBe('true');
|
||||
expect(document.querySelector('nav[aria-label="Navegar a indicadores clínicos"]')).not.toBeNull();
|
||||
expect(document.activeElement).toBe(optionButtons()[0]);
|
||||
expect(document.querySelector('.cdk-focus-trap-anchor')).toBeNull();
|
||||
document.querySelector('.panel-shell')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true, cancelable: true }));
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
expect(button.getAttribute('aria-expanded')).toBe('false');
|
||||
expect(document.activeElement).toBe(button);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('cierra al pulsar fuera y mantiene el click externo disponible', async () => {
|
||||
const bodyOverflow = document.body.style.overflow;
|
||||
await load([item('one', 'Indicador')]);
|
||||
await openPanel();
|
||||
document.body.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
|
||||
document.body.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
|
||||
fixture.detectChanges();
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
expect(page.navigationClosing()).toBe(true);
|
||||
expect(document.querySelector('app-indicadores-navegacion-panel')?.hasAttribute('inert')).toBe(true);
|
||||
expect(document.querySelector('.cdk-overlay-pane.indicator-navigation-overlay:has(.panel-closing)')).not.toBeNull();
|
||||
expect(document.body.style.overflow).toBe(bodyOverflow);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('no conserva elementos al cambiar de dominio y elimina el encabezado y el botón X', async () => {
|
||||
await load([item('one', 'TEA gráfico')]);
|
||||
await openPanel();
|
||||
expect(document.querySelector('#indicator-navigation-title')).toBeNull();
|
||||
expect(document.querySelector('.panel-header')).toBeNull();
|
||||
expect(document.querySelector('.panel-shell mat-icon')).toBeNull();
|
||||
expect(document.querySelector('.panel-shell')?.querySelectorAll('button')).toHaveLength(1);
|
||||
page.changeDominio('cacu');
|
||||
http.expectOne('/cacu/indicadores').flush([item('new', 'CaCu clínico')]);
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
expect(trigger()).not.toBeNull();
|
||||
await openPanel();
|
||||
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['CaCu clínico']);
|
||||
expect(optionButtons().some(button => button.textContent?.includes('TEA'))).toBe(false);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('respeta movimiento reducido, enfoca la tarjeta y no solicita sus figuras desde el panel', async () => {
|
||||
await load([item('lazy', 'Carga diferida')]);
|
||||
const card = fixture.nativeElement.querySelector('app-indicador-catalog-card') as HTMLElement;
|
||||
const scroll = vi.fn();
|
||||
card.scrollIntoView = scroll;
|
||||
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })));
|
||||
await openPanel();
|
||||
optionButtons()[0].click();
|
||||
await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(scroll).toHaveBeenCalledWith({ behavior: 'instant', block: 'start' });
|
||||
expect(fixture.debugElement.query(By.css('app-indicador-catalog-card'))?.componentInstance?.visible).toBe(false);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
function pointer(target: Element, type: 'pointerenter' | 'pointerleave' | 'pointermove', pointerType = 'mouse', moved = true) {
|
||||
const event = new Event(type);
|
||||
Object.defineProperty(event, 'pointerType', { value: pointerType });
|
||||
target.dispatchEvent(event);
|
||||
// A real entry caused by mouse movement also dispatches pointermove. Layout-only entries don't.
|
||||
if (type === 'pointerenter' && moved) {
|
||||
const move = new Event('pointermove');
|
||||
Object.defineProperty(move, 'pointerType', { value: pointerType });
|
||||
target.dispatchEvent(move);
|
||||
}
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function hoverDevice(enabled = true) {
|
||||
vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: enabled && query === '(hover: hover) and (pointer: fine)' })));
|
||||
}
|
||||
|
||||
it('abre por hover sin mover el foco y conserva el origen CDK oculto y su caja', async () => {
|
||||
await load([item('a', 'Indicador')]);
|
||||
hoverDevice();
|
||||
const button = trigger()!;
|
||||
const origin = fixture.debugElement.query(By.css('[cdkOverlayOrigin]')).nativeElement;
|
||||
const rect = new DOMRect(8, 180, 48, 48);
|
||||
vi.spyOn(button, 'getBoundingClientRect').mockReturnValue(rect);
|
||||
const initialFocus = document.activeElement;
|
||||
pointer(button, 'pointerenter');
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
expect(document.activeElement).toBe(initialFocus);
|
||||
expect(trigger()).toBe(origin);
|
||||
expect(getComputedStyle(button).opacity).toBe('0');
|
||||
expect(getComputedStyle(button).pointerEvents).toBe('none');
|
||||
expect(getComputedStyle(button).display).not.toBe('none');
|
||||
expect(button.getBoundingClientRect()).toBe(rect);
|
||||
expect(button.tabIndex).toBe(-1);
|
||||
expect(optionButtons()).toHaveLength(1);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('permite cruzar del disparador a cualquier opción y cancela el cierre al reingresar', async () => {
|
||||
await load([item('a', 'Uno'), item('b', 'Dos')]);
|
||||
hoverDevice(); vi.useFakeTimers();
|
||||
pointer(trigger()!, 'pointerenter');
|
||||
pointer(trigger()!, 'pointerleave');
|
||||
vi.advanceTimersByTime(200);
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
const panel = document.querySelector('app-indicadores-navegacion-panel')!;
|
||||
pointer(panel, 'pointerenter');
|
||||
vi.advanceTimersByTime(300);
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
pointer(panel, 'pointerleave');
|
||||
vi.advanceTimersByTime(200);
|
||||
pointer(panel, 'pointerenter');
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
pointer(panel, 'pointerleave');
|
||||
vi.advanceTimersByTime(229);
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
vi.advanceTimersByTime(1); fixture.detectChanges();
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
expect(page.navigationAttached()).toBe(true);
|
||||
expect(document.querySelector('.panel-closing')).not.toBeNull();
|
||||
vi.advanceTimersByTime(180); fixture.detectChanges();
|
||||
expect(page.navigationAttached()).toBe(false);
|
||||
expect(document.querySelector('.panel-shell')).toBeNull();
|
||||
});
|
||||
|
||||
it.each(['touch', 'pen', 'mouse'])('sin hover real ignora %s y conserva la apertura por toque/clic', async pointerType => {
|
||||
await load([item('a', 'Indicador')]);
|
||||
hoverDevice(false);
|
||||
pointer(trigger()!, 'pointerenter', pointerType);
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
trigger()!.dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 }));
|
||||
fixture.detectChanges();
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
page.toggleGraphicNavigation(new MouseEvent('click', { detail: 1 }));
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['Enter', ' '])('abre con %s, enfoca la primera opción y deja salir el foco con Tab', async key => {
|
||||
await load([item('a', 'Uno'), item('b', 'Dos')]);
|
||||
trigger()!.focus();
|
||||
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
|
||||
trigger()!.dispatchEvent(event);
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(document.activeElement).toBe(optionButtons()[0]);
|
||||
const tab = new KeyboardEvent('keydown', { key: 'Tab', bubbles: true, cancelable: true });
|
||||
optionButtons()[1].dispatchEvent(tab);
|
||||
expect(tab.defaultPrevented).toBe(false);
|
||||
expect(document.querySelector('.cdk-focus-trap-anchor')).toBeNull();
|
||||
const outside = fixture.nativeElement.querySelector('[role="tab"]') as HTMLButtonElement;
|
||||
outside.focus();
|
||||
expect(document.activeElement).toBe(outside);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('no cierra al salir el puntero si una opción conserva el foco de teclado', async () => {
|
||||
await load([item('a', 'Indicador')]);
|
||||
await openPanel();
|
||||
vi.useFakeTimers();
|
||||
pointer(document.querySelector('app-indicadores-navegacion-panel')!, 'pointerleave');
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
});
|
||||
|
||||
it('cierra con Escape aun cuando hover no haya trasladado el foco al panel', async () => {
|
||||
await load([item('a', 'Indicador')]); hoverDevice();
|
||||
pointer(trigger()!, 'pointerenter');
|
||||
document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true, cancelable: true }));
|
||||
fixture.detectChanges();
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
expect(document.activeElement).toBe(trigger());
|
||||
});
|
||||
|
||||
it('no espera animación al cerrar con movimiento reducido', async () => {
|
||||
await load([item('a', 'Indicador')]);
|
||||
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })));
|
||||
await openPanel();
|
||||
page.closeGraphicNavigation(); fixture.detectChanges();
|
||||
expect(page.navigationAttached()).toBe(false);
|
||||
expect(document.querySelector('.panel-shell')).toBeNull();
|
||||
});
|
||||
|
||||
it('no reabre por entradas del puntero generadas al desmontar el overlay y admite un nuevo movimiento', async () => {
|
||||
await load([item('a', 'Indicador')]); hoverDevice(); vi.useFakeTimers();
|
||||
pointer(trigger()!, 'pointerenter');
|
||||
page.closeGraphicNavigation(); fixture.detectChanges();
|
||||
page.closeGraphicNavigation(); fixture.detectChanges();
|
||||
pointer(trigger()!, 'pointerenter', 'mouse', false);
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
vi.advanceTimersByTime(180); fixture.detectChanges();
|
||||
expect(page.navigationAttached()).toBe(false);
|
||||
pointer(trigger()!, 'pointermove');
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
page.closeGraphicNavigation(false); fixture.detectChanges();
|
||||
pointer(trigger()!, 'pointerenter');
|
||||
vi.advanceTimersByTime(500); fixture.detectChanges();
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
expect(page.navigationClosing()).toBe(false);
|
||||
});
|
||||
|
||||
it('cancela el cierre pendiente al cambiar de sección o dominio y al destruir', async () => {
|
||||
await load([item('a', 'TEA')]); hoverDevice(); vi.useFakeTimers();
|
||||
pointer(trigger()!, 'pointerenter'); pointer(trigger()!, 'pointerleave');
|
||||
page.changeSection('datos'); fixture.detectChanges();
|
||||
expect(page.navigationAttached()).toBe(false);
|
||||
page.changeSection('resumen'); fixture.detectChanges();
|
||||
pointer(trigger()!, 'pointerenter');
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
pointer(trigger()!, 'pointerleave');
|
||||
page.changeDominio('cama');
|
||||
http.expectOne('/cama/indicadores').flush([item('b', 'CaMa')]); fixture.detectChanges();
|
||||
expect(page.navigationAttached()).toBe(false);
|
||||
pointer(trigger()!, 'pointerenter');
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
pointer(trigger()!, 'pointerleave');
|
||||
const clear = vi.spyOn(globalThis, 'clearTimeout');
|
||||
const close = vi.spyOn(page, 'closeGraphicNavigation');
|
||||
fixture.destroy();
|
||||
expect(page.navigationAttached()).toBe(false);
|
||||
expect(clear).toHaveBeenCalled();
|
||||
const callsAtDestroy = close.mock.calls.length;
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(close.mock.calls).toHaveLength(callsAtDestroy);
|
||||
});
|
||||
|
||||
it('mantiene botones estables, títulos completos multilínea y transforma solo la etiqueta visual', async () => {
|
||||
const title = 'Indicador clínico con un título extenso que puede ocupar varias líneas completas';
|
||||
await load([item('a', title), item('b', 'Otro indicador')]);
|
||||
await openPanel();
|
||||
const button = optionButtons()[0];
|
||||
expect(button.textContent?.trim()).toBe(title);
|
||||
expect(getComputedStyle(button).minHeight).toBe('44px');
|
||||
expect(getComputedStyle(button).whiteSpace).toBe('normal');
|
||||
expect(getComputedStyle(button).transform).not.toContain('scale');
|
||||
expect(button.querySelector('.option-label')).not.toBeNull();
|
||||
expect(getComputedStyle(document.querySelector('.panel-list')!).overflowX).toBe('hidden');
|
||||
const styles = Array.from(document.querySelectorAll('style')).map(style => style.textContent).join('\n');
|
||||
expect(styles).toContain('button:focus-visible');
|
||||
expect(styles).toContain('scale(1.02)');
|
||||
expect(styles).toContain('scale(0.99)');
|
||||
expect(styles).toContain('prefers-reduced-motion: reduce');
|
||||
expect(styles).toContain('@starting-style');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
<div class="panel-shell" id="indicator-navigation-panel" (keydown)="onKeydown($event)">
|
||||
<nav class="panel-list" aria-label="Navegar a indicadores clínicos">
|
||||
@if (items().length) {
|
||||
<ul>
|
||||
@for (item of items(); track item.key) {
|
||||
<li><button mat-button type="button" [attr.aria-label]="item.titulo" (click)="seleccionar(item.key)"><span class="option-label">{{ item.titulo }}</span></button></li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</nav>
|
||||
</div>
|
||||
@@ -0,0 +1,20 @@
|
||||
:host { display: block; width: min(20rem, calc(100vw - 1rem)); max-width: calc(100vw - 1rem); min-width: 0; color: var(--issste-text); }
|
||||
.panel-shell { display: flex; flex-direction: column; width: 100%; max-height: min(58dvh, 32rem); min-height: 0; overflow: hidden; color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: 0 8px 28px rgb(8 24 57 / 24%); opacity: 1; transform: scale(1); transform-origin: left center; transition: opacity 180ms ease, transform 180ms cubic-bezier(.2, .8, .2, 1); }
|
||||
@starting-style { .panel-shell { opacity: 0; transform: scale(.97); } }
|
||||
:host(.panel-closing) { pointer-events: none; }
|
||||
:host(.panel-closing) .panel-shell { opacity: 0; transform: scale(.97); }
|
||||
.panel-list { flex: 0 1 auto; min-height: 0; overflow-y: auto; overflow-x: hidden; overscroll-behavior: contain; padding: .35rem .5rem; }
|
||||
ul { list-style: none; margin: 0; padding: 0; }
|
||||
li + li { margin-top: .1rem; }
|
||||
li button { display: flex; width: 100%; min-height: 44px; height: auto; justify-content: flex-start; padding: .15rem .2rem; text-align: start; white-space: normal; line-height: 1.35; color: inherit; }
|
||||
.option-label { display: block; width: 100%; min-width: 0; padding: .4rem; box-sizing: border-box; border-radius: .35rem; overflow-wrap: anywhere; transition: transform 180ms ease, background-color 180ms ease; }
|
||||
button:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: -2px; }
|
||||
.panel-list:has(button:focus-visible) button:not(:focus-visible) .option-label { transform: scale(.99); }
|
||||
button:focus-visible .option-label { transform: scale(1.02); background: color-mix(in srgb, var(--issste-accent) 14%, transparent); }
|
||||
@media (hover: hover) and (pointer: fine) {
|
||||
.panel-list:has(button:hover) button:not(:hover):not(:focus-visible) .option-label { transform: scale(.99); }
|
||||
button:hover .option-label { transform: scale(1.02); background: color-mix(in srgb, var(--issste-accent) 14%, transparent); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.panel-shell, .option-label { transition: none; transform: none !important; }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Component, ElementRef, Input, Signal, inject, output } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
|
||||
export interface IndicadorNavegacionItem {
|
||||
key: string;
|
||||
titulo: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-navegacion-panel',
|
||||
imports: [MatButtonModule],
|
||||
host: { '[class.panel-closing]': 'closing', '[attr.inert]': "closing ? '' : null" },
|
||||
templateUrl: './indicadores-navegacion-panel.html',
|
||||
styleUrl: './indicadores-navegacion-panel.scss',
|
||||
})
|
||||
export class IndicadoresNavegacionPanel {
|
||||
@Input({ required: true }) items!: Signal<readonly IndicadorNavegacionItem[]>;
|
||||
@Input() closing = false;
|
||||
readonly selected = output<string>();
|
||||
readonly closed = output<void>();
|
||||
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
focusFirstOption() { this.element.nativeElement.querySelector<HTMLButtonElement>('.panel-list button')?.focus({ preventScroll: true }); }
|
||||
containsFocus() { return this.element.nativeElement.contains(this.element.nativeElement.ownerDocument.activeElement); }
|
||||
|
||||
onKeydown(event: KeyboardEvent) {
|
||||
if (event.key !== 'Escape') return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
this.closed.emit();
|
||||
}
|
||||
|
||||
seleccionar(key: string) {
|
||||
if (this.items().some(item => item.key === key)) this.selected.emit(key);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,44 @@
|
||||
<section class="dashboard" aria-labelledby="dashboard-title">
|
||||
<header>
|
||||
<span class="domain">{{ domainTitles[dominio] }}, investigación</span>
|
||||
<h1 id="dashboard-title">Indicadores</h1>
|
||||
<p>Explora los indicadores de {{ domainLabels[dominio] }}.</p>
|
||||
</header>
|
||||
<div class="section-tabs" [class.dark-theme]="tema === 'oscuro'" role="tablist" [attr.aria-label]="'Secciones de ' + domainLabels[dominio]" (keydown)="sectionKeydown($event)">
|
||||
@for (section of sections; track section.id) {
|
||||
<button type="button" role="tab" [id]="'tab-' + section.id" [attr.aria-controls]="'panel-' + section.id"
|
||||
[attr.aria-selected]="activeSection() === section.id" [tabIndex]="activeSection() === section.id ? 0 : -1"
|
||||
(click)="changeSection(section.id)">{{ section.label }}</button>
|
||||
@if (fichaPacienteAbierta()) {
|
||||
<h1 id="dashboard-title">Ficha del paciente</h1>
|
||||
<p>Consulta individual de seguimiento de cáncer cervicouterino</p>
|
||||
} @else {
|
||||
<span class="domain">{{ domainTitles[dominio] }}, investigación</span>
|
||||
<h1 id="dashboard-title">Indicadores</h1>
|
||||
<p>Explora los indicadores de {{ domainLabels[dominio] }}.</p>
|
||||
}
|
||||
</div>
|
||||
</header>
|
||||
@if (!fichaPacienteAbierta()) {
|
||||
<div class="section-tabs" [class.dark-theme]="tema === 'oscuro'" role="tablist" [attr.aria-label]="'Secciones de ' + domainLabels[dominio]" (keydown)="sectionKeydown($event)">
|
||||
@for (section of sections; track section.id) {
|
||||
<button type="button" role="tab" [id]="'tab-' + section.id" [attr.aria-controls]="'panel-' + section.id"
|
||||
[attr.aria-selected]="activeSection() === section.id" [tabIndex]="activeSection() === section.id ? 0 : -1"
|
||||
(click)="changeSection(section.id)">{{ section.label }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@if (showGraphicNavigation) {
|
||||
<button #navigationTrigger cdkOverlayOrigin #navigationOrigin="cdkOverlayOrigin" class="graphic-navigation-trigger" mat-mini-fab type="button"
|
||||
[class.graphic-navigation-trigger-expanded]="navigationOpen()" [tabIndex]="navigationOpen() ? -1 : 0"
|
||||
[attr.aria-label]="navigationOpen() ? 'Cerrar navegación por indicadores' : 'Abrir navegación por indicadores'"
|
||||
aria-controls="indicator-navigation-panel" [attr.aria-expanded]="navigationOpen()" (click)="toggleGraphicNavigation($event)"
|
||||
(keydown)="navigationTriggerKeydown($event)" (pointerenter)="navigationPointerEnter($event)" (pointerleave)="navigationPointerLeave($event)"
|
||||
(pointermove)="navigationPointerMove($event)">
|
||||
<mat-icon aria-hidden="true">format_list_bulleted</mat-icon>
|
||||
</button>
|
||||
<ng-template cdkConnectedOverlay [cdkConnectedOverlayOrigin]="navigationOrigin"
|
||||
[cdkConnectedOverlayOpen]="navigationAttached()" [cdkConnectedOverlayPositions]="navigationPositions"
|
||||
[cdkConnectedOverlayScrollStrategy]="navigationScrollStrategy" [cdkConnectedOverlayViewportMargin]="8"
|
||||
[cdkConnectedOverlayFlexibleDimensions]="true" [cdkConnectedOverlayPush]="true"
|
||||
cdkConnectedOverlayPanelClass="indicator-navigation-overlay"
|
||||
[cdkConnectedOverlayHasBackdrop]="false" (overlayOutsideClick)="closeGraphicNavigationFromOutside($event)"
|
||||
(overlayKeydown)="navigationOverlayKeydown($event)">
|
||||
<app-indicadores-navegacion-panel [items]="navigationItems" [closing]="navigationClosing()"
|
||||
(pointerenter)="navigationPointerEnter($event)" (pointerleave)="navigationPointerLeave($event)" (focusout)="navigationFocusOut()"
|
||||
(closed)="closeGraphicNavigation()" (selected)="selectGraphicNavigation($event)" />
|
||||
</ng-template>
|
||||
}
|
||||
|
||||
<div id="panel-resumen" class="section-panel" role="tabpanel" aria-labelledby="tab-resumen" tabindex="0" [hidden]="activeSection() !== 'resumen'">
|
||||
@if (!catalogLoading() && filters; as state) {
|
||||
@@ -37,16 +65,17 @@
|
||||
} @else if (initialPeriodState() === 'manual') {
|
||||
<p role="status">La búsqueda inicial se detuvo para conservar tu selección. Pulsa Aplicar para consultar.</p>
|
||||
}
|
||||
@let kpis = availableKpis;
|
||||
@let kpis = opportunityKpis;
|
||||
@if (kpis.length && !initialPeriodBlocked) {
|
||||
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
||||
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : 'Indicadores destacados' }}</h2>
|
||||
<div class="kpi-grid" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 1 : 0)">
|
||||
<div class="kpi-grid" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : 0)">
|
||||
@for (definition of kpis; track dominio + ':' + definition.id) {
|
||||
<app-indicador-kpi-panel [dominio]="dominio" [definition]="definition" [indicador]="kpiIndicator(definition.id)"
|
||||
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
|
||||
}
|
||||
@if (dominio === 'cacu') {
|
||||
<app-indicador-kpi-card title="Tiempo de tamizaje a tratamiento" state="Indicador no disponible" />
|
||||
<app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible" />
|
||||
}
|
||||
</div>
|
||||
@@ -93,7 +122,7 @@
|
||||
}
|
||||
<div class="catalog-grid">
|
||||
@for (item of searchResults().items; track cardIdentity(item)) {
|
||||
<app-indicador-catalog-card [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
|
||||
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
|
||||
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
|
||||
}
|
||||
</div>
|
||||
@@ -101,8 +130,9 @@
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section id="panel-seguimiento" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-seguimiento" tabindex="0" [hidden]="activeSection() !== 'seguimiento'">
|
||||
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'" />
|
||||
<section id="panel-seguimiento" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" [attr.aria-labelledby]="fichaPacienteAbierta() ? 'dashboard-title' : 'tab-seguimiento'" tabindex="0" [hidden]="activeSection() !== 'seguimiento'">
|
||||
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'"
|
||||
(fichaPacienteAbierta)="setFichaPacienteAbierta($event)" />
|
||||
</section>
|
||||
|
||||
<section id="panel-datos" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-datos" tabindex="0" [hidden]="activeSection() !== 'datos'">
|
||||
|
||||
@@ -32,6 +32,12 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
|
||||
@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||
|
||||
// Five opportunity cards: at least ~280px per card; retain existing TEA/CaMa grids.
|
||||
.kpi-section[data-domain='cacu'] .kpi-grid {
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.section-tabs { display: flex; justify-content: center; flex-wrap: wrap; gap: var(--issste-space-1);
|
||||
border-block-start: 2px solid var(--issste-accent); border-block-end: 1px solid var(--issste-border);
|
||||
background: var(--issste-surface); padding: var(--issste-space-2) var(--issste-space-2) 0;
|
||||
@@ -49,3 +55,8 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
.section-panel { padding-block: var(--issste-space-6); }
|
||||
.section-panel[hidden] { display: none; }
|
||||
@media (max-width: 550px) { .section-tabs button { flex: 1 1 auto; padding-inline: .65rem; } }
|
||||
.graphic-navigation-trigger { transition: opacity 180ms ease; }
|
||||
.graphic-navigation-trigger-expanded { opacity: 0; pointer-events: none; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.graphic-navigation-trigger { transition: none; }
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresTracking } from './indicadores-tracking';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
@@ -51,6 +52,22 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
.toEqual([]);
|
||||
http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('cambia al encabezado de ficha sin destruir el estado de las pestañas', () => {
|
||||
load();
|
||||
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
|
||||
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(3);
|
||||
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(true); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Ficha del paciente');
|
||||
expect(fixture.nativeElement.textContent).toContain('Consulta individual de seguimiento de cáncer cervicouterino');
|
||||
expect(fixture.nativeElement.querySelector('.section-tabs')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('dashboard-title');
|
||||
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(false); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
|
||||
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(3);
|
||||
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('tab-seguimiento');
|
||||
expect(page.activeSection()).toBe('resumen');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('KPI-DYNAMIC distingue carga, error y catálogo vacío confirmado', () => {
|
||||
fixture.detectChanges();
|
||||
expect(page.catalogLoading()).toBe(true);
|
||||
|
||||
@@ -10,28 +10,30 @@ import { MatInputModule } from '@angular/material/input';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { ConnectedPosition, Overlay, OverlayModule } from '@angular/cdk/overlay';
|
||||
import { catchError, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs';
|
||||
import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
|
||||
import { indicatorIdentity } from './indicadores-identities';
|
||||
import { identityElementId, indicatorIdentity } from './indicadores-identities';
|
||||
import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { IndicadoresInitialPeriod } from './indicadores-initial-period';
|
||||
import { IndicadoresDefinitions } from './indicadores-definitions';
|
||||
import { IndicadoresTracking } from './indicadores-tracking';
|
||||
import { IndicadorNavegacionItem, IndicadoresNavegacionPanel } from './indicadores-navegacion-panel';
|
||||
|
||||
type DashboardSection = 'resumen' | 'seguimiento' | 'datos';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking],
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
@@ -42,8 +44,14 @@ export class IndicadoresPage {
|
||||
{ id: 'datos', label: 'Datos y definiciones' },
|
||||
];
|
||||
readonly activeSection = signal<DashboardSection>('resumen');
|
||||
readonly fichaPacienteAbierta = signal(false);
|
||||
setFichaPacienteAbierta(open: boolean) {
|
||||
this.fichaPacienteAbierta.set(open);
|
||||
if (open) this.closeGraphicNavigation(false, false);
|
||||
}
|
||||
changeSection(section: DashboardSection) {
|
||||
if (!this.sections.some(item => item.id === section) || this.activeSection() === section) return;
|
||||
if (section !== 'resumen') this.closeGraphicNavigation(false, false);
|
||||
this.activeSection.set(section);
|
||||
// Retain views, filters and Plotly hosts; only visible regions authorize loading.
|
||||
if (section !== 'resumen') for (const card of this.graphicCards()) card.setVisible(false);
|
||||
@@ -64,6 +72,26 @@ export class IndicadoresPage {
|
||||
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly searchInput = viewChild<ElementRef<HTMLInputElement>>('searchInput');
|
||||
private readonly overlay = inject(Overlay);
|
||||
readonly navigationScrollStrategy = this.overlay.scrollStrategies.reposition();
|
||||
readonly navigationPositions: ConnectedPosition[] = [
|
||||
{ originX: 'start', originY: 'center', overlayX: 'start', overlayY: 'center' },
|
||||
{ originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'top' },
|
||||
{ originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'bottom' },
|
||||
{ originX: 'end', originY: 'center', overlayX: 'end', overlayY: 'center' },
|
||||
];
|
||||
readonly navigationOpen = signal(false);
|
||||
readonly navigationClosing = signal(false);
|
||||
readonly navigationAttached = computed(() => this.navigationOpen() || this.navigationClosing());
|
||||
readonly navigationKeyboard = signal(false);
|
||||
private readonly navigationPanel = viewChild(IndicadoresNavegacionPanel);
|
||||
private navigationHoverTimer?: ReturnType<typeof setTimeout>;
|
||||
private navigationAnimationTimer?: ReturnType<typeof setTimeout>;
|
||||
private navigationPointerInside = false;
|
||||
// Removing the overlay can generate pointerenter on the button under a stationary cursor.
|
||||
private navigationHoverDismissed = false;
|
||||
readonly navigationItems = computed<readonly IndicadorNavegacionItem[]>(() =>
|
||||
this.searchResults().items.map(item => ({ key: indicatorIdentity(this.dominio, item.id), titulo: item.titulo })));
|
||||
private readonly graphicCards = viewChildren(IndicadorCatalogCard);
|
||||
private readonly observedRegions = new Map<Element, IndicadorCatalogCard>();
|
||||
private renderedCards: readonly IndicadorCatalogCard[] = [];
|
||||
@@ -246,8 +274,27 @@ export class IndicadoresPage {
|
||||
readonly kpisByDomain = KPI_BY_DOMAIN;
|
||||
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
|
||||
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
|
||||
kpiIndicator(id: string) { return this.catalog().find(item => item.id === id); }
|
||||
kpiIndicator(id: string) {
|
||||
const published = this.catalog().find(item => item.id === id);
|
||||
if (published) return published;
|
||||
// The lab partner is deliberately hidden from some catalogs, as in the paired figure.
|
||||
// Reuse its established periodicity, without assigning the diagnosis version to lab data.
|
||||
if (this.dominio === 'cacu' && id === CACU_RESULTADO_KPI.id) {
|
||||
const diagnosis = this.catalog().find(item => item.id === 'cacu_dias_toma_diagnostico');
|
||||
if (diagnosis) return { id, titulo: CACU_RESULTADO_KPI.title, contrato: diagnosis.contrato,
|
||||
figuras: [], tipos_periodo: diagnosis.tipos_periodo };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
|
||||
get opportunityKpis() {
|
||||
const definitions = this.availableKpis;
|
||||
if (this.dominio !== 'cacu' || (!definitions.length && !this.catalog().some(item => item.id === CACU_RESULTADO_KPI.id))) return definitions;
|
||||
// Keep the established KPI definitions and initial-period anchor intact.
|
||||
const diagnosis = definitions.findIndex(item => item.id === 'cacu_dias_toma_diagnostico');
|
||||
return [...definitions.slice(0, diagnosis < 0 ? definitions.length : diagnosis), CACU_RESULTADO_KPI,
|
||||
...definitions.slice(diagnosis < 0 ? definitions.length : diagnosis)];
|
||||
}
|
||||
private readonly catalogRequests = new Subject<void>();
|
||||
readonly catalog = signal<Indicador[]>([]);
|
||||
readonly searchQuery = signal('');
|
||||
@@ -303,8 +350,117 @@ export class IndicadoresPage {
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); }
|
||||
cardElementId(item: Indicador) { return identityElementId(this.cardIdentity(item)); }
|
||||
get showGraphicNavigation() {
|
||||
return this.activeSection() === 'resumen' && !this.fichaPacienteAbierta() && !this.catalogLoading()
|
||||
&& !this.catalogError() && !this.initialPeriodBlocked && this.navigationItems().length > 0;
|
||||
}
|
||||
toggleGraphicNavigation(event?: MouseEvent) {
|
||||
if (!this.showGraphicNavigation) return;
|
||||
if (this.navigationOpen()) this.closeGraphicNavigation(false);
|
||||
else this.openGraphicNavigation(event?.detail === 0);
|
||||
}
|
||||
private openGraphicNavigation(keyboard = false) {
|
||||
if (!this.showGraphicNavigation) return;
|
||||
this.clearNavigationTimers();
|
||||
this.navigationHoverDismissed = false;
|
||||
this.navigationKeyboard.set(keyboard);
|
||||
this.navigationClosing.set(false);
|
||||
this.navigationOpen.set(true);
|
||||
if (keyboard) afterNextRender(() => {
|
||||
if (this.navigationOpen() && this.navigationKeyboard()) this.navigationPanel()?.focusFirstOption();
|
||||
}, { injector: this.injector });
|
||||
}
|
||||
navigationTriggerKeydown(event: KeyboardEvent) {
|
||||
if (event.key !== 'Enter' && event.key !== ' ') return;
|
||||
event.preventDefault();
|
||||
this.openGraphicNavigation(true);
|
||||
}
|
||||
navigationPointerEnter(event: PointerEvent) {
|
||||
if (this.navigationHoverDismissed || !this.navigationCanHover(event)) return;
|
||||
this.navigationPointerInside = true;
|
||||
if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer);
|
||||
this.navigationHoverTimer = undefined;
|
||||
if (!this.navigationOpen()) this.openGraphicNavigation();
|
||||
}
|
||||
navigationPointerMove(event: PointerEvent) {
|
||||
if (!this.navigationHoverDismissed || !this.navigationCanHover(event)) return;
|
||||
this.navigationHoverDismissed = false;
|
||||
this.navigationPointerEnter(event);
|
||||
}
|
||||
private navigationCanHover(event: PointerEvent) {
|
||||
return event.pointerType === 'mouse' && this.document.defaultView?.matchMedia?.('(hover: hover) and (pointer: fine)').matches;
|
||||
}
|
||||
navigationPointerLeave(event: PointerEvent) {
|
||||
if (!this.navigationCanHover(event)) return;
|
||||
this.navigationPointerInside = false;
|
||||
this.scheduleNavigationClose();
|
||||
}
|
||||
navigationFocusOut() { this.scheduleNavigationClose(); }
|
||||
private scheduleNavigationClose() {
|
||||
if (!this.navigationOpen()) return;
|
||||
if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer);
|
||||
this.navigationHoverTimer = setTimeout(() => {
|
||||
this.navigationHoverTimer = undefined;
|
||||
if (!this.navigationPointerInside && !this.navigationPanel()?.containsFocus()) this.closeGraphicNavigation(false);
|
||||
}, 230);
|
||||
}
|
||||
navigationOverlayKeydown(event: KeyboardEvent) {
|
||||
if (event.key !== 'Escape') return;
|
||||
event.preventDefault();
|
||||
this.closeGraphicNavigation();
|
||||
}
|
||||
private clearNavigationTimers() {
|
||||
if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer);
|
||||
if (this.navigationAnimationTimer !== undefined) clearTimeout(this.navigationAnimationTimer);
|
||||
this.navigationHoverTimer = this.navigationAnimationTimer = undefined;
|
||||
}
|
||||
closeGraphicNavigation(restoreFocus = true, animate = true) {
|
||||
const wasOpen = this.navigationOpen();
|
||||
this.clearNavigationTimers();
|
||||
this.navigationHoverDismissed ||= wasOpen;
|
||||
this.navigationPointerInside = false;
|
||||
this.navigationKeyboard.set(false);
|
||||
this.navigationOpen.set(false);
|
||||
const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
||||
this.navigationClosing.set(animate && wasOpen && !reducedMotion);
|
||||
if (this.navigationClosing()) this.navigationAnimationTimer = setTimeout(() => {
|
||||
this.navigationAnimationTimer = undefined;
|
||||
this.navigationClosing.set(false);
|
||||
}, 180);
|
||||
if (wasOpen && restoreFocus && this.showGraphicNavigation) {
|
||||
this.element.nativeElement.querySelector<HTMLButtonElement>('.graphic-navigation-trigger')?.focus({ preventScroll: true });
|
||||
}
|
||||
}
|
||||
closeGraphicNavigationFromOutside(event: MouseEvent) {
|
||||
const target = event.target;
|
||||
const trigger = this.element.nativeElement.querySelector<HTMLButtonElement>('.graphic-navigation-trigger');
|
||||
if (target instanceof Node && trigger?.contains(target)) return;
|
||||
this.closeGraphicNavigation(false);
|
||||
}
|
||||
selectGraphicNavigation(key: string) {
|
||||
if (!this.navigationItems().some(item => item.key === key)) {
|
||||
this.closeGraphicNavigation(false);
|
||||
return;
|
||||
}
|
||||
this.closeGraphicNavigation(false, false);
|
||||
afterNextRender(() => this.scrollToIndicator(key), { injector: this.injector });
|
||||
}
|
||||
private scrollToIndicator(key: string) {
|
||||
if (this.activeSection() !== 'resumen' || this.fichaPacienteAbierta()
|
||||
|| !this.navigationItems().some(item => item.key === key)) return;
|
||||
const target = this.document.getElementById(identityElementId(key));
|
||||
const grid = this.element.nativeElement.querySelector('.catalog-grid');
|
||||
if (!target || !grid?.contains(target)) return;
|
||||
const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
||||
target.scrollIntoView({ behavior: reducedMotion ? 'instant' : 'smooth', block: 'start' });
|
||||
target.querySelector('h2')?.focus({ preventScroll: true });
|
||||
}
|
||||
constructor() {
|
||||
afterEveryRender(() => this.syncVisibility());
|
||||
afterEveryRender(() => {
|
||||
this.syncVisibility();
|
||||
if (!this.showGraphicNavigation && (this.navigationAttached() || this.navigationHoverTimer !== undefined)) this.closeGraphicNavigation(false, false);
|
||||
});
|
||||
const browser = this.document.defaultView;
|
||||
if (typeof IntersectionObserver !== 'undefined') {
|
||||
browser?.addEventListener('scroll', this.viewportChanged, { passive: true });
|
||||
@@ -313,6 +469,7 @@ export class IndicadoresPage {
|
||||
this.destroyRef.onDestroy(() => {
|
||||
this.filtersEdited();
|
||||
this.visibilityDestroyed = true;
|
||||
this.closeGraphicNavigation(false, false);
|
||||
this.clearVisibility();
|
||||
this.sizeObserver?.disconnect();
|
||||
this.sizeTargets.clear();
|
||||
@@ -327,6 +484,7 @@ export class IndicadoresPage {
|
||||
return this.periodService.dominio(this.dominio, this.catalog());
|
||||
}), takeUntilDestroyed(this.destroyRef)).subscribe(state => this.availability.set(state));
|
||||
this.catalogRequests.pipe(startWith(undefined), switchMap(() => {
|
||||
this.closeGraphicNavigation(false, false);
|
||||
this.cancelInitialPeriod.next();
|
||||
this.initialPeriodState.set('ready');
|
||||
this.clearVisibility();
|
||||
@@ -348,6 +506,7 @@ export class IndicadoresPage {
|
||||
}
|
||||
changeDominio(dominio: Dominio) {
|
||||
if (!isDominio(dominio) || dominio === this.dominio) return;
|
||||
this.closeGraphicNavigation(false, false);
|
||||
this.activeSection.set('resumen');
|
||||
this.searchQuery.set('');
|
||||
this.filtersEdited();
|
||||
|
||||
@@ -6,7 +6,7 @@ import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { Dominio, IndicadorDatos } from './indicadores.models';
|
||||
|
||||
describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
@@ -29,7 +29,18 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
catalog(domain).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN[domain][i].id, periods[i])));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel); }
|
||||
// Regression assertions below target the original KPI contracts. The added lab
|
||||
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
||||
// Satisfy its independent request with an explicit empty response, never diagnosis data.
|
||||
function originalRequests() {
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
for (const r of requests.filter(r => r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'))) {
|
||||
const period = r.request.params.get('periodos')!;
|
||||
r.flush({ id: CACU_RESULTADO_KPI.id, contrato: 'C3r', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [], filas: [] });
|
||||
}
|
||||
return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'));
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
|
||||
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
|
||||
function data(index: number, domain: Dominio, period: string, suppressed = false): IndicadorDatos {
|
||||
const d = KPI_BY_DOMAIN[domain][index];
|
||||
@@ -41,7 +52,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
function flushDatos(domain: Dominio, suppressed = false) {
|
||||
const resolved = [];
|
||||
for (;;) {
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
const requests = originalRequests();
|
||||
if (!requests.length) return resolved;
|
||||
resolved.push(...requests);
|
||||
requests.forEach(r => {
|
||||
@@ -65,7 +76,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
});
|
||||
it('tras Aplicar Todos, supresión del último no busca periodos anteriores ni sustituye cifras', () => {
|
||||
load('cacu', Array(3).fill(['2024-S1', '2026-S2', '2025-S2']));
|
||||
const initial = http.match(r => r.url.endsWith('/datos'));
|
||||
const initial = originalRequests();
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
expect(initial.every(r => r.cancelled)).toBe(true);
|
||||
const requests = flushDatos('cacu', true);
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
@if (pacienteDetalle.estado().tipo !== 'cerrado') {
|
||||
<app-paciente-detalle [estado]="pacienteDetalle.estado()" [categorias]="categories"
|
||||
[registrosTemporales]="pacienteDetalle.registrosTemporales()"
|
||||
(registroAgregado)="pacienteDetalle.agregarRegistro($event)" (volver)="volverASeguimiento()" />
|
||||
}
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
|
||||
<h2>Seguimiento de {{ domainLabel }}</h2>
|
||||
@if (dominio !== 'cacu') {
|
||||
<p>El seguimiento aún no está disponible.</p>
|
||||
@@ -32,11 +38,11 @@
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados disponibles por paciente</caption>
|
||||
<thead><tr><th>Identificador seudónimo</th><th>Grupo de edad</th><th>Estatus de seguimiento</th><th>Última citología</th><th>Último resultado de VPH</th><th>Estudio más reciente</th><th>Días de toma a diagnóstico</th><th>Prioridad</th></tr></thead>
|
||||
<thead><tr><th scope="col">Identificador seudónimo</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
|
||||
<tbody>
|
||||
@for (item of response.items; track item.id_seudonimo) {
|
||||
<tr>
|
||||
<td>{{ item.id_seudonimo }}</td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
|
||||
<tr tabindex="-1" (click)="abrirPaciente(item, $event)" [attr.data-paciente]="item.id_seudonimo">
|
||||
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + item.id_seudonimo" (click)="abrirPaciente(item, $event)">{{ item.id_seudonimo }}</button></td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
|
||||
<td>@if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}<small>Fecha: {{ c.fecha }}</small><small>Calidad: {{ c.calidad ?? '—' }}</small> } @else { No disponible }</td>
|
||||
<td>@if (item.ultimo_vph; as v) { {{ v.resultado }}<small>Fecha: {{ v.fecha }}</small><small>Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }}</small> } @else { No disponible }</td>
|
||||
<td>{{ latestStudy(item) ?? 'No disponible' }}</td><td>{{ item.dias_toma_diagnostico ?? 'No disponible' }}</td><td>{{ item.prioridad?.etiqueta ?? 'No disponible' }}</td>
|
||||
@@ -52,3 +58,4 @@
|
||||
</nav>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -16,3 +16,8 @@ th, td { text-align: start; vertical-align: top; padding: 1rem; border-top: 1px
|
||||
th { background: var(--issste-background); font-weight: 600; }
|
||||
small { display: block; margin-top: .35rem; }
|
||||
nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top: 1rem; }
|
||||
tbody tr[data-paciente] { cursor: pointer; transition: background-color 120ms ease; }
|
||||
tbody tr[data-paciente]:hover { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); }
|
||||
tbody tr[data-paciente]:focus-within { outline: 2px solid var(--issste-accent); outline-offset: -2px; }
|
||||
.patient-link { min-height: 44px; padding: .35rem .5rem; border: 0; border-radius: var(--issste-radius); background: transparent; color: var(--issste-accent); font: inherit; font-weight: 600; text-align: left; text-decoration: underline; text-underline-offset: .15em; cursor: pointer; }
|
||||
.patient-link:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
import { ChangeDetectorRef, Component, DestroyRef, inject, Input, OnChanges } from '@angular/core';
|
||||
import { afterNextRender, ChangeDetectorRef, Component, DestroyRef, inject, Injector, Input, OnChanges, output } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of, Subject, switchMap } from 'rxjs';
|
||||
import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
import { latestStudy, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
|
||||
import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state';
|
||||
import { Dominio } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-tracking',
|
||||
imports: [FormsModule],
|
||||
imports: [FormsModule, MatButtonModule, PacienteDetalleComponent],
|
||||
providers: [PacienteDetalleState],
|
||||
templateUrl: './indicadores-tracking.html',
|
||||
styleUrl: './indicadores-tracking.scss',
|
||||
})
|
||||
@@ -22,6 +26,10 @@ export class IndicadoresTracking implements OnChanges {
|
||||
private readonly indicators = inject(IndicadoresService);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private readonly injector = inject(Injector);
|
||||
readonly pacienteDetalle = inject(PacienteDetalleState);
|
||||
readonly fichaPacienteAbierta = output<boolean>();
|
||||
private controlPaciente?: HTMLElement;
|
||||
private readonly requests = new Subject<SeguimientoQuery | null>();
|
||||
private initialized = false;
|
||||
private previousDomain?: Dominio;
|
||||
@@ -61,6 +69,8 @@ export class IndicadoresTracking implements OnChanges {
|
||||
}
|
||||
ngOnChanges() {
|
||||
if (this.previousDomain !== this.dominio) {
|
||||
if (this.pacienteDetalle.estado().tipo !== 'cerrado') this.fichaPacienteAbierta.emit(false);
|
||||
this.pacienteDetalle.cerrar(); this.controlPaciente = undefined;
|
||||
this.previousDomain = this.dominio; this.requests.next(null); this.data = undefined;
|
||||
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft };
|
||||
}
|
||||
@@ -77,6 +87,27 @@ export class IndicadoresTracking implements OnChanges {
|
||||
if (!this.data || page < 1 || page > this.data.paginacion.total_pages) return;
|
||||
this.load({ ...this.applied, page });
|
||||
}
|
||||
abrirPaciente(paciente: SeguimientoPaciente, evento: Event) {
|
||||
if (this.dominio !== 'cacu' || this.status !== 'ready' || !this.data?.items.includes(paciente)) return;
|
||||
evento.stopPropagation();
|
||||
if (evento.type === 'click' && evento.currentTarget instanceof HTMLButtonElement) {
|
||||
if (evento.currentTarget.classList.contains('patient-link')) evento.preventDefault();
|
||||
this.controlPaciente = evento.currentTarget;
|
||||
} else if (evento.type === 'click' && evento.currentTarget instanceof HTMLTableRowElement
|
||||
&& evento.target instanceof HTMLElement && !evento.target.closest('button, a, input, select, textarea')) this.controlPaciente = evento.currentTarget;
|
||||
else if (evento.type === 'click' && evento.target instanceof HTMLElement && evento.target.closest('button, a, input, select, textarea')) return;
|
||||
else if (evento.type !== 'click') return;
|
||||
this.pacienteDetalle.abrir(paciente, this.data.corte);
|
||||
this.fichaPacienteAbierta.emit(true);
|
||||
}
|
||||
volverASeguimiento() {
|
||||
this.pacienteDetalle.cerrar();
|
||||
this.fichaPacienteAbierta.emit(false);
|
||||
const control = this.controlPaciente;
|
||||
afterNextRender(() => {
|
||||
if (control?.isConnected) control.focus({ preventScroll: true });
|
||||
}, { injector: this.injector });
|
||||
}
|
||||
// The shown cytology is the patient's latest in the window. Without a Bethesda result it is either
|
||||
// unsatisfactory (`cacu.calidad_insatisfactoria` in the kit) or not yet reported at the cut-off.
|
||||
cytologyLabel(c: { bethesda: string | null; calidad: string | null }) {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<div role="group" [attr.aria-labelledby]="id + '-titulo'" (focusout)="salir($event)">
|
||||
<p class="etiqueta" [id]="id + '-titulo'">{{ etiqueta }}</p>
|
||||
<div class="partes">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Día</mat-label>
|
||||
<input matInput type="text" inputmode="numeric" autocomplete="off" required
|
||||
data-fecha="dia" [formControl]="partes.controls.dia" [matAutocomplete]="dias"
|
||||
[errorStateMatcher]="estadoError" [aria-describedby]="mostrarError ? id + '-error' : ''">
|
||||
<mat-autocomplete #dias="matAutocomplete">
|
||||
@for (dia of diasSugeridos; track dia) { <mat-option [value]="dia">{{ dia }}</mat-option> }
|
||||
</mat-autocomplete>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Mes</mat-label>
|
||||
<input matInput type="text" autocomplete="off" required
|
||||
data-fecha="mes" [formControl]="partes.controls.mes" [matAutocomplete]="meses"
|
||||
[errorStateMatcher]="estadoError" [aria-describedby]="mostrarError ? id + '-error' : ''">
|
||||
<mat-autocomplete #meses="matAutocomplete">
|
||||
@for (mes of mesesSugeridos; track mes) { <mat-option [value]="mes">{{ mes }}</mat-option> }
|
||||
</mat-autocomplete>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Año</mat-label>
|
||||
<input matInput type="text" inputmode="numeric" autocomplete="off" required
|
||||
data-fecha="anio" [formControl]="partes.controls.anio" [matAutocomplete]="anios"
|
||||
[errorStateMatcher]="estadoError" [aria-describedby]="mostrarError ? id + '-error' : ''">
|
||||
<mat-autocomplete #anios="matAutocomplete">
|
||||
@for (anio of aniosSugeridos; track anio) { <mat-option [value]="anio">{{ anio }}</mat-option> }
|
||||
</mat-autocomplete>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
@if (mostrarError) { <p class="error" [id]="id + '-error'" aria-live="polite">{{ mensajeError }}</p> }
|
||||
</div>
|
||||
@@ -0,0 +1,8 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.etiqueta { margin: 0 0 .5rem; font-size: .875rem; font-weight: 500; }
|
||||
.partes { display: grid; grid-template-columns: minmax(0, .8fr) minmax(0, 1.6fr) minmax(0, 1fr); gap: .5rem; }
|
||||
mat-form-field { width: 100%; min-width: 0; }
|
||||
.error { margin: .25rem 0 0; color: var(--mat-sys-error, #ba1a1a); font-size: .75rem; }
|
||||
@media (max-width: 400px) {
|
||||
.partes { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
|
||||
import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing';
|
||||
import { MatInputHarness } from '@angular/material/input/testing';
|
||||
import { FechaCompuesta } from './fecha-compuesta';
|
||||
|
||||
@Component({
|
||||
imports: [ReactiveFormsModule, FechaCompuesta],
|
||||
template: '<app-fecha-compuesta [formControl]="fecha" etiqueta="Fecha del estudio" /><button>Después</button>',
|
||||
})
|
||||
class FormularioFecha {
|
||||
readonly fecha = new FormControl('', { nonNullable: true, validators: [Validators.required] });
|
||||
}
|
||||
|
||||
describe('Fecha compuesta reutilizable', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<FormularioFecha>>;
|
||||
let fecha: FormControl<string>;
|
||||
let control: FechaCompuesta;
|
||||
let root: HTMLElement;
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(FormularioFecha);
|
||||
fecha = fixture.componentInstance.fecha;
|
||||
root = fixture.nativeElement;
|
||||
fixture.detectChanges();
|
||||
control = fixture.debugElement.query(By.directive(FechaCompuesta)).componentInstance;
|
||||
});
|
||||
|
||||
async function escribir(parte: string, valor: string) {
|
||||
const input = await TestbedHarnessEnvironment.loader(fixture).getHarness(
|
||||
MatInputHarness.with({ selector: `[data-fecha="${parte}"]` }));
|
||||
await input.setValue(valor);
|
||||
}
|
||||
async function capturar(dia: string, mes: string, anio: string) {
|
||||
await escribir('dia', dia); await escribir('mes', mes); await escribir('anio', anio);
|
||||
}
|
||||
function entrada(parte: string) { return root.querySelector<HTMLInputElement>(`[data-fecha="${parte}"]`)!; }
|
||||
function tecla(input: HTMLInputElement, key: string, keyCode: number) {
|
||||
input.dispatchEvent(new KeyboardEvent('keydown', { key, keyCode, bubbles: true, cancelable: true }));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
|
||||
it('empieza vacío e inválido sin errores prematuros, con etiquetas y orden día-mes-año', () => {
|
||||
expect(fecha.invalid).toBe(true);
|
||||
expect(root.querySelector('.error')).toBeNull();
|
||||
expect(root.querySelector('[role="group"]')?.getAttribute('aria-labelledby')).toBe(control.id + '-titulo');
|
||||
expect(root.querySelector('#' + control.id + '-titulo')?.textContent).toContain('Fecha del estudio');
|
||||
expect(Array.from(root.querySelectorAll('input')).map(input => input.dataset['fecha'])).toEqual(['dia', 'mes', 'anio']);
|
||||
for (const parte of ['dia', 'mes', 'anio']) {
|
||||
const input = entrada(parte);
|
||||
expect(input.required).toBe(true);
|
||||
expect(input.tabIndex).toBe(0);
|
||||
expect(root.querySelector(`label[for="${input.id}"]`)?.textContent).toMatch(/Día|Mes|Año/);
|
||||
}
|
||||
});
|
||||
|
||||
it('captura manualmente sin seleccionar sugerencias y conserva ISO sin conversión horaria', async () => {
|
||||
await capturar('26', 'octubre', '2026');
|
||||
expect(fecha.valid).toBe(true);
|
||||
expect(fecha.value).toBe('2026-10-26');
|
||||
await capturar('1', '01', '0001');
|
||||
expect(fecha.value).toBe('0001-01-01');
|
||||
await capturar('31', '12', '9999');
|
||||
expect(fecha.value).toBe('9999-12-31');
|
||||
});
|
||||
|
||||
it('ofrece doce meses y filtra nombres y números sin aceptar fragmentos ambiguos', async () => {
|
||||
const mes = await TestbedHarnessEnvironment.loader(fixture).getHarness(
|
||||
MatAutocompleteHarness.with({ selector: '[data-fecha="mes"]' }));
|
||||
await mes.focus();
|
||||
expect(await mes.getOptions()).toHaveLength(12);
|
||||
await mes.enterText('ma');
|
||||
expect(await Promise.all((await mes.getOptions()).map(opcion => opcion.getText()))).toEqual(['Marzo', 'Mayo']);
|
||||
await escribir('dia', '15'); await escribir('anio', '2026');
|
||||
expect(fecha.value).toBe('');
|
||||
expect(fecha.invalid).toBe(true);
|
||||
await mes.clear(); await mes.enterText('10');
|
||||
expect(await Promise.all((await mes.getOptions()).map(opcion => opcion.getText()))).toEqual(['Octubre']);
|
||||
expect(fecha.value).toBe('2026-10-15');
|
||||
for (const valor of ['13', '0', 'mes desconocido', 'mar']) {
|
||||
await mes.clear(); await mes.enterText(valor);
|
||||
expect(fecha.value, valor).toBe('');
|
||||
expect(fecha.invalid).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('selecciona los tres componentes mediante autocompletado', async () => {
|
||||
const loader = TestbedHarnessEnvironment.loader(fixture);
|
||||
for (const [parte, valor] of [['anio', '2024'], ['mes', 'Febrero'], ['dia', '29']]) {
|
||||
const input = await loader.getHarness(MatAutocompleteHarness.with({ selector: `[data-fecha="${parte}"]` }));
|
||||
if (parte === 'anio') await input.enterText(valor); else await input.focus();
|
||||
await input.selectOption({ text: valor });
|
||||
}
|
||||
expect(fecha.value).toBe('2024-02-29');
|
||||
expect(fecha.valid).toBe(true);
|
||||
});
|
||||
|
||||
it('navega las sugerencias con flechas y Enter y cierra con Escape manteniendo el foco', async () => {
|
||||
const mes = await TestbedHarnessEnvironment.loader(fixture).getHarness(
|
||||
MatAutocompleteHarness.with({ selector: '[data-fecha="mes"]' }));
|
||||
await mes.enterText('ma');
|
||||
tecla(entrada('mes'), 'ArrowDown', 40);
|
||||
tecla(entrada('mes'), 'ArrowDown', 40);
|
||||
tecla(entrada('mes'), 'ArrowUp', 38);
|
||||
expect(entrada('mes').getAttribute('aria-activedescendant')).toBeTruthy();
|
||||
tecla(entrada('mes'), 'Enter', 13);
|
||||
await fixture.whenStable();
|
||||
expect(await mes.getValue()).toBe('Marzo');
|
||||
expect(await mes.isOpen()).toBe(false);
|
||||
await mes.clear(); await mes.enterText('ab');
|
||||
tecla(entrada('mes'), 'Escape', 27);
|
||||
await fixture.whenStable();
|
||||
expect(await mes.isOpen()).toBe(false);
|
||||
expect(await mes.isFocused()).toBe(true);
|
||||
expect(await mes.getValue()).toBe('ab');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['31', 'Abril', '2026'], ['30', 'Febrero', '2024'], ['29', 'Febrero', '2026'],
|
||||
['29', 'Febrero', '1900'], ['0', 'Enero', '2026'], ['32', 'Enero', '2026'],
|
||||
['1.5', 'Enero', '2026'], ['1', 'Enero', '0'], ['1', 'Enero', '10000'],
|
||||
['1', 'Enero', '-1'], ['1', 'Enero', '20e2'],
|
||||
])('rechaza fecha imposible o entrada inválida %s / %s / %s', async (dia, mes, anio) => {
|
||||
await capturar(dia, mes, anio);
|
||||
expect(fecha.value).toBe('');
|
||||
expect(fecha.invalid).toBe(true);
|
||||
});
|
||||
|
||||
it.each(['2000', '2024'])('admite 29 de febrero en el año bisiesto %s', async anio => {
|
||||
await capturar('29', 'Febrero', anio);
|
||||
expect(fecha.value).toBe(`${anio}-02-29`);
|
||||
expect(fecha.valid).toBe(true);
|
||||
});
|
||||
|
||||
it('invalida el día al cambiar mes o año sin corregirlo silenciosamente ni conservar el ISO anterior', async () => {
|
||||
await capturar('31', 'Marzo', '2024');
|
||||
expect(fecha.value).toBe('2024-03-31');
|
||||
await escribir('mes', 'Abril');
|
||||
expect(fecha.value).toBe('');
|
||||
expect(entrada('dia').value).toBe('31');
|
||||
expect(control.diasSugeridos).toHaveLength(30);
|
||||
await capturar('29', 'Febrero', '2024');
|
||||
expect(control.diasSugeridos).toHaveLength(29);
|
||||
await escribir('anio', '2025');
|
||||
expect(fecha.value).toBe('');
|
||||
expect(fecha.invalid).toBe(true);
|
||||
expect(entrada('dia').value).toBe('29');
|
||||
expect(control.diasSugeridos).toHaveLength(28);
|
||||
await escribir('anio', '2024');
|
||||
expect(fecha.value).toBe('2024-02-29');
|
||||
});
|
||||
|
||||
it.each(['dia', 'mes', 'anio'])('vaciar %s invalida inmediatamente una fecha previamente válida', async parte => {
|
||||
await capturar('26', 'Octubre', '2026');
|
||||
await escribir(parte, '');
|
||||
expect(fecha.value).toBe('');
|
||||
expect(fecha.invalid).toBe(true);
|
||||
});
|
||||
|
||||
it('muestra un único error asociado al salir del grupo o al solicitar validación', async () => {
|
||||
const dia = entrada('dia');
|
||||
dia.focus();
|
||||
entrada('mes').focus();
|
||||
fixture.detectChanges();
|
||||
expect(fecha.touched).toBe(false);
|
||||
expect(root.querySelector('.error')).toBeNull();
|
||||
root.querySelector('button')!.focus();
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(fecha.touched).toBe(true);
|
||||
expect(root.querySelectorAll('.error')).toHaveLength(1);
|
||||
for (const input of root.querySelectorAll('input')) {
|
||||
expect(input.getAttribute('aria-describedby')).toContain(control.id + '-error');
|
||||
expect(input.getAttribute('aria-required')).toBe('true');
|
||||
}
|
||||
fecha.reset(''); fixture.detectChanges();
|
||||
expect(root.querySelector('.error')).toBeNull();
|
||||
fecha.markAllAsTouched(); fixture.detectChanges();
|
||||
expect(root.querySelector('.error')?.textContent).toContain('completa día, mes y año');
|
||||
await capturar('31', 'Abril', '2026');
|
||||
expect(root.querySelector('.error')?.textContent).toContain('ese día no existe');
|
||||
expect(dia.getAttribute('aria-invalid')).toBe('true');
|
||||
await escribir('dia', '30');
|
||||
expect(root.querySelector('.error')).toBeNull();
|
||||
});
|
||||
|
||||
it('acepta valores externos sin emitir cambios adicionales y no normaliza fechas inválidas', async () => {
|
||||
const cambios = vi.fn();
|
||||
fecha.valueChanges.subscribe(cambios);
|
||||
fecha.setValue('2024-02-29'); fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
expect(cambios).toHaveBeenCalledExactlyOnceWith('2024-02-29');
|
||||
expect(entrada('dia').value).toBe('29');
|
||||
expect(entrada('mes').value).toBe('Febrero');
|
||||
expect(entrada('anio').value).toBe('2024');
|
||||
expect(fecha.valid).toBe(true);
|
||||
for (const valor of ['2026-02-30', '2026-13-01', 'ayer', '2026-1-1', '2026-10-26T00:00:00Z']) {
|
||||
fecha.setValue(valor); fixture.detectChanges();
|
||||
expect(fecha.value).toBe(valor);
|
||||
expect(fecha.invalid).toBe(true);
|
||||
}
|
||||
fecha.reset(''); fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
expect(Array.from(root.querySelectorAll('input')).every(input => input.value === '')).toBe(true);
|
||||
});
|
||||
|
||||
it('propaga disabled y permite años históricos y futuros sin listas enormes', async () => {
|
||||
fecha.disable(); fixture.detectChanges();
|
||||
expect(Array.from(root.querySelectorAll('input')).every(input => input.disabled)).toBe(true);
|
||||
fecha.enable(); fixture.detectChanges();
|
||||
for (const anio of ['0001', '1500', '2100', '9999']) {
|
||||
await capturar('1', 'Enero', anio);
|
||||
expect(fecha.value).toBe(`${anio}-01-01`);
|
||||
expect(fecha.valid).toBe(true);
|
||||
expect(control.aniosSugeridos.length).toBeLessThanOrEqual(7);
|
||||
expect(control.aniosSugeridos).toContain(anio);
|
||||
expect(control.aniosSugeridos.every(opcion => Number(opcion) >= 1 && Number(opcion) <= 9999)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import { AfterViewInit, ChangeDetectorRef, Component, DestroyRef, ElementRef, Injector, Input, OnInit, forwardRef, inject } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { AbstractControl, ControlValueAccessor, FormControl, FormGroup, NG_VALIDATORS, NG_VALUE_ACCESSOR, NgControl, ReactiveFormsModule, ValidationErrors, Validator } from '@angular/forms';
|
||||
import { MatAutocompleteModule } from '@angular/material/autocomplete';
|
||||
import { ErrorStateMatcher } from '@angular/material/core';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { esFechaReal } from './paciente-registro.validation';
|
||||
|
||||
const MESES = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
|
||||
'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
|
||||
let siguienteId = 0;
|
||||
|
||||
/** Tres entradas editables; el formulario recibe exclusivamente ISO de calendario o vacío. */
|
||||
@Component({
|
||||
selector: 'app-fecha-compuesta',
|
||||
imports: [ReactiveFormsModule, MatAutocompleteModule, MatFormFieldModule, MatInputModule],
|
||||
templateUrl: './fecha-compuesta.html',
|
||||
styleUrl: './fecha-compuesta.scss',
|
||||
providers: [
|
||||
{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => FechaCompuesta), multi: true },
|
||||
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => FechaCompuesta), multi: true },
|
||||
],
|
||||
})
|
||||
export class FechaCompuesta implements ControlValueAccessor, Validator, OnInit, AfterViewInit {
|
||||
@Input() etiqueta = 'Fecha';
|
||||
readonly id = `fecha-compuesta-${siguienteId++}`;
|
||||
readonly partes = new FormGroup({
|
||||
dia: new FormControl('', { nonNullable: true }),
|
||||
mes: new FormControl('', { nonNullable: true }),
|
||||
anio: new FormControl('', { nonNullable: true }),
|
||||
});
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
private readonly cdr = inject(ChangeDetectorRef);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private ngControl: NgControl | null = null;
|
||||
private visitado = false;
|
||||
private entradaExternaInvalida = false;
|
||||
private onChange: (valor: string) => void = () => {};
|
||||
private onTouched: () => void = () => {};
|
||||
readonly estadoError: ErrorStateMatcher = { isErrorState: () => this.mostrarError };
|
||||
|
||||
constructor() {
|
||||
this.partes.valueChanges.pipe(takeUntilDestroyed(this.destroy)).subscribe(() => {
|
||||
this.entradaExternaInvalida = false;
|
||||
// Emitir también al invalidarse: nunca conservar la última fecha válida.
|
||||
this.onChange(this.fechaIso);
|
||||
this.cdr.markForCheck();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
// Resolver después de crear los providers CVA/Validator evita una dependencia circular.
|
||||
this.ngControl = this.injector.get(NgControl, null, { self: true });
|
||||
}
|
||||
|
||||
ngAfterViewInit() {
|
||||
// FormControlName ya está conectado al FormGroup al terminar de crear la vista.
|
||||
// markAllAsTouched/reset del formulario también deben refrescar el grupo con OnPush.
|
||||
this.ngControl?.control?.events.pipe(takeUntilDestroyed(this.destroy))
|
||||
.subscribe(() => this.cdr.markForCheck());
|
||||
}
|
||||
|
||||
private numero(valor: string, digitos: number): number | null {
|
||||
const texto = valor.trim();
|
||||
return new RegExp(`^\\d{1,${digitos}}$`).test(texto) ? Number(texto) : null;
|
||||
}
|
||||
|
||||
private get mesNumero(): number | null {
|
||||
const texto = this.partes.controls.mes.value.trim().toLocaleLowerCase('es');
|
||||
const numero = this.numero(texto, 2);
|
||||
if (numero !== null) return numero >= 1 && numero <= 12 ? numero : null;
|
||||
const indice = MESES.findIndex(mes => mes.toLocaleLowerCase('es') === texto);
|
||||
return indice >= 0 ? indice + 1 : null;
|
||||
}
|
||||
|
||||
get mesesSugeridos(): string[] {
|
||||
const texto = this.partes.controls.mes.value.trim().toLocaleLowerCase('es');
|
||||
const numero = this.numero(texto, 2);
|
||||
if (numero !== null) return numero >= 1 && numero <= 12 ? [MESES[numero - 1]] : [];
|
||||
return MESES.filter(mes => mes.toLocaleLowerCase('es').includes(texto));
|
||||
}
|
||||
|
||||
get diasSugeridos(): string[] {
|
||||
const mes = String(this.mesNumero ?? 1).padStart(2, '0');
|
||||
const numeroAnio = this.numero(this.partes.controls.anio.value, 4);
|
||||
// Sin año válido se ofrece el máximo de febrero; completar el año vuelve a validar.
|
||||
const anio = String(numeroAnio || 2000).padStart(4, '0');
|
||||
return Array.from({ length: 31 }, (_, i) => String(i + 1))
|
||||
.filter(dia => esFechaReal(`${anio}-${mes}-${dia.padStart(2, '0')}`));
|
||||
}
|
||||
|
||||
get aniosSugeridos(): string[] {
|
||||
const escrito = this.numero(this.partes.controls.anio.value, 4);
|
||||
const centro = escrito && escrito <= 9999 ? escrito : new Date().getFullYear();
|
||||
return Array.from({ length: 7 }, (_, i) => centro - 3 + i)
|
||||
.filter(anio => anio >= 1 && anio <= 9999).map(anio => String(anio).padStart(4, '0'));
|
||||
}
|
||||
|
||||
private get fechaIso(): string {
|
||||
const { dia, anio } = this.partes.getRawValue();
|
||||
const d = this.numero(dia, 2);
|
||||
const m = this.mesNumero;
|
||||
const a = this.numero(anio, 4);
|
||||
if (d === null || m === null || a === null) return '';
|
||||
const fecha = `${String(a).padStart(4, '0')}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
|
||||
return esFechaReal(fecha) ? fecha : '';
|
||||
}
|
||||
|
||||
get mensajeError(): string {
|
||||
if (this.entradaExternaInvalida) return 'Ingresa una fecha real de calendario.';
|
||||
const { dia, mes, anio } = this.partes.getRawValue();
|
||||
if (![dia, mes, anio].every(valor => valor.trim())) return 'Ingresa una fecha válida: completa día, mes y año.';
|
||||
if (this.mesNumero === null) return 'Escribe el nombre completo del mes o un número del 1 al 12.';
|
||||
const a = this.numero(anio, 4);
|
||||
if (a === null || a < 1) return 'Ingresa un año entre 0001 y 9999.';
|
||||
if (!this.fechaIso) return 'Ingresa una fecha real: ese día no existe en el mes y año indicados.';
|
||||
return '';
|
||||
}
|
||||
|
||||
get mostrarError(): boolean {
|
||||
return !this.partes.disabled && !!this.mensajeError && (this.ngControl?.touched ?? this.visitado);
|
||||
}
|
||||
|
||||
salir(event: FocusEvent) {
|
||||
if (!this.host.nativeElement.contains(event.relatedTarget as Node | null)) {
|
||||
this.visitado = true;
|
||||
this.onTouched();
|
||||
}
|
||||
}
|
||||
|
||||
writeValue(valor: unknown): void {
|
||||
const coincidencia = typeof valor === 'string' ? /^(\d{4})-(\d{2})-(\d{2})$/.exec(valor) : null;
|
||||
this.entradaExternaInvalida = !!valor && !esFechaReal(valor);
|
||||
this.visitado = false;
|
||||
this.partes.reset(coincidencia ? {
|
||||
dia: coincidencia[3], mes: MESES[Number(coincidencia[2]) - 1] ?? coincidencia[2], anio: coincidencia[1],
|
||||
} : { dia: '', mes: '', anio: '' }, { emitEvent: false });
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
registerOnChange(fn: (valor: string) => void): void { this.onChange = fn; }
|
||||
registerOnTouched(fn: () => void): void { this.onTouched = fn; }
|
||||
setDisabledState(deshabilitado: boolean): void {
|
||||
if (deshabilitado) this.partes.disable({ emitEvent: false });
|
||||
else this.partes.enable({ emitEvent: false });
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
validate(control: AbstractControl): ValidationErrors | null {
|
||||
return esFechaReal(control.value) && this.fechaIso === control.value ? null : { fechaCompuesta: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { PacienteDetalle } from './paciente-detalle.models';
|
||||
|
||||
// Explicit demonstration identities only. Never derive a history from age, status or a hash.
|
||||
export const PACIENTES_DETALLE_SINTETICOS: readonly PacienteDetalle[] = [
|
||||
{
|
||||
id_seudonimo: 'P-4BC9B9E8F4',
|
||||
origen: 'sintetico',
|
||||
historial: [{ descripcion: 'Antecedente de tamizaje cervical (demostración)', fecha: '2025-06-12', notas: null }],
|
||||
procedimientos: [],
|
||||
pruebas: [{ nombre: 'Citología previa (demostración)', fecha: '2025-06-12', resultado: 'Negativa para lesión intraepitelial' }],
|
||||
},
|
||||
{
|
||||
id_seudonimo: 'P-2C9E494F5D',
|
||||
origen: 'sintetico',
|
||||
historial: null,
|
||||
procedimientos: [{ nombre: 'Colposcopia (demostración)', fecha: '2026-06-10', resultado: null }],
|
||||
pruebas: [{ nombre: 'Histopatología (demostración)', fecha: null, resultado: null }],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,85 @@
|
||||
@if (estado.tipo !== 'cerrado') {
|
||||
<button class="back-button" mat-stroked-button type="button" (click)="volver.emit()"><mat-icon aria-hidden="true">arrow_back</mat-icon><span>Regresar</span></button>
|
||||
<header>
|
||||
<h2 #titulo tabindex="-1">Paciente {{ estado.resumen.id_seudonimo }}</h2>
|
||||
<p>Fecha de corte: {{ estado.resumen.corte }}.</p>
|
||||
<dl class="summary">
|
||||
<div><dt>Identificador seudónimo</dt><dd>{{ estado.resumen.id_seudonimo }}</dd></div>
|
||||
<div><dt>Grupo de edad</dt><dd>{{ estado.resumen.grupoEdad ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>Estatus de seguimiento</dt><dd>{{ estado.resumen.estatus ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>Días de toma a diagnóstico</dt><dd>{{ estado.resumen.diasTomaDiagnostico ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>Prioridad</dt><dd>{{ estado.resumen.prioridad ?? 'No disponible' }}</dd></div>
|
||||
</dl>
|
||||
</header>
|
||||
@if (estado.tipo === 'cargando') { <p role="status">Cargando información…</p> }
|
||||
@if (estado.tipo === 'no-disponible') { <p class="availability" role="status">Información no disponible.</p> }
|
||||
@if (estado.tipo === 'error') { <p class="availability" role="alert">No se pudo cargar la información de este paciente. Regresa a Seguimiento para intentar de nuevo.</p> }
|
||||
@if (registrosTemporales.length) { <p class="pending-changes" role="status">Cambios sin guardar</p> }
|
||||
<div class="detail-grid">
|
||||
<mat-card class="history-card" appearance="outlined" aria-labelledby="historial-title">
|
||||
<mat-card-header><h3 id="historial-title">Historial médico relevante</h3></mat-card-header>
|
||||
<mat-card-content>
|
||||
<div class="history-actions">
|
||||
<button mat-stroked-button type="button" (click)="abrirRegistro('condicion')">Agregar condición</button>
|
||||
<button mat-stroked-button type="button" (click)="abrirRegistro('procedimiento')">Agregar procedimiento</button>
|
||||
</div>
|
||||
<div class="history-table-scroll" role="region" aria-label="Historial médico relevante" tabindex="0">
|
||||
<table class="history-table">
|
||||
<thead><tr><th scope="col">Registro</th><th scope="col">Fecha</th></tr></thead>
|
||||
<tbody>
|
||||
<tr class="section-row"><th scope="rowgroup" colspan="2">Condiciones</th></tr>
|
||||
@if (estado.tipo === 'disponible') {
|
||||
@if (estado.detalle.historial; as historial) {
|
||||
@for (item of historial; track $index) {
|
||||
<tr><td><strong>{{ item.descripcion }}</strong>@if (item.notas) { <span class="record-detail">{{ item.notas }}</span> }</td><td>{{ item.fecha ?? 'No disponible' }}</td></tr>
|
||||
}
|
||||
@if (!historial.length && !temporales('condicion').length) { <tr><td colspan="2" class="empty-row">Sin registros.</td></tr> }
|
||||
} @else if (!temporales('condicion').length) { <tr><td colspan="2" class="empty-row">Información no disponible.</td></tr> }
|
||||
} @else if (!temporales('condicion').length) { <tr><td colspan="2" class="empty-row">Información no disponible.</td></tr> }
|
||||
@for (item of temporales('condicion'); track item.id) {
|
||||
<tr data-registro-temporal="condicion"><td><strong>{{ etiquetaRegistro(item) }}</strong><span class="record-detail">Agregado en esta sesión</span></td><td>{{ item.fecha }}</td></tr>
|
||||
}
|
||||
<tr class="section-row"><th scope="rowgroup" colspan="2">Procedimientos</th></tr>
|
||||
@if (estado.tipo === 'disponible') {
|
||||
@if (estado.detalle.procedimientos; as procedimientos) {
|
||||
@for (item of procedimientos; track $index) {
|
||||
<tr><td><strong>{{ item.nombre }}</strong>@if (item.resultado) { <span class="record-detail">Resultado: {{ item.resultado }}</span> }</td><td>{{ item.fecha ?? 'No disponible' }}</td></tr>
|
||||
}
|
||||
@if (!procedimientos.length && !temporales('procedimiento').length) { <tr><td colspan="2" class="empty-row">Sin registros.</td></tr> }
|
||||
} @else if (!temporales('procedimiento').length) { <tr><td colspan="2" class="empty-row">Información no disponible.</td></tr> }
|
||||
} @else if (!temporales('procedimiento').length) { <tr><td colspan="2" class="empty-row">Información no disponible.</td></tr> }
|
||||
@for (item of temporales('procedimiento'); track item.id) {
|
||||
<tr data-registro-temporal="procedimiento"><td><strong>{{ etiquetaRegistro(item) }}</strong><span class="record-detail">Agregado en esta sesión</span></td><td>{{ item.fecha }}</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
<mat-card class="tests-card" appearance="outlined" aria-labelledby="pruebas-title">
|
||||
<mat-card-header><h3 id="pruebas-title">Pruebas y resultados</h3></mat-card-header>
|
||||
<mat-card-content>
|
||||
<button mat-stroked-button type="button" (click)="abrirRegistro('resultado')">Agregar resultado</button>
|
||||
<h4>Últimos resultados</h4>
|
||||
<ul>
|
||||
<li><strong>Última citología</strong>@if (estado.resumen.citologia; as c) { <span>Fecha: {{ c.fecha }}</span><span>Resultado: {{ etiquetaCitologia(c.resultado, c.calidad) }}</span><span>Calidad: {{ c.calidad ?? 'No disponible' }}</span> } @else { <span>No disponible</span> }</li>
|
||||
<li><strong>Último resultado de VPH</strong>@if (estado.resumen.vph; as v) { <span>Fecha: {{ v.fecha }}</span><span>Resultado: {{ v.resultado }}</span><span>Genotipo 16/18: {{ v.genotipo16y18 === null ? 'No disponible' : v.genotipo16y18 ? 'Presente' : 'No detectado' }}</span> } @else { <span>No disponible</span> }</li>
|
||||
</ul>
|
||||
@if (estado.tipo === 'disponible') {
|
||||
<h4>Pruebas adicionales</h4>
|
||||
@if (estado.detalle.pruebas; as pruebas) {
|
||||
<ul>@for (item of pruebas; track $index) { <li><strong>{{ item.nombre }}</strong><span>Fecha: {{ item.fecha ?? 'No disponible' }}</span><span>Resultado: {{ item.resultado ?? 'No disponible' }}</span></li> } @empty { <li>Sin registros.</li> }</ul>
|
||||
} @else { <p>Información no disponible.</p> }
|
||||
}
|
||||
@if (estado.tipo === 'disponible' || temporales('resultado').length) {
|
||||
<h4>Resultados agregados</h4>
|
||||
<ul>@for (item of temporales('resultado'); track item.id) { <li data-registro-temporal="resultado"><strong>{{ etiquetaRegistro(item) }}</strong><span>Fecha: {{ item.fecha }}</span><span>Resultado: {{ etiquetaResultado(item) }}</span></li> } @empty { <li>Sin registros.</li> }</ul>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
<mat-card class="risks-card" appearance="outlined" aria-labelledby="riesgos-title">
|
||||
<mat-card-header><h3 id="riesgos-title">Riesgos y recomendaciones</h3></mat-card-header>
|
||||
<mat-card-content><app-paciente-riesgo-tabla /></mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
/** Snapshot of the received row, independent of the Seguimiento transport contract. */
|
||||
export interface PacienteResumen {
|
||||
id_seudonimo: string;
|
||||
grupoEdad: string | null;
|
||||
estatus: string | null;
|
||||
corte: string;
|
||||
origen: 'seguimiento-demostracion';
|
||||
citologia: { fecha: string; resultado: string | null; calidad: string | null } | null;
|
||||
vph: { fecha: string; resultado: string; genotipo16y18: boolean | null } | null;
|
||||
diasTomaDiagnostico: number | null;
|
||||
prioridad: string | null;
|
||||
}
|
||||
|
||||
export interface AntecedenteDetalle { descripcion: string; fecha: string | null; notas?: string | null; }
|
||||
export interface ProcedimientoDetalle { nombre: string; fecha: string | null; resultado?: string | null; }
|
||||
export interface PruebaDetalle { nombre: string; fecha: string | null; resultado: string | null; }
|
||||
|
||||
/** null = unavailable collection; [] = no entries supplied, never proof of clinical absence. */
|
||||
export interface PacienteDetalle {
|
||||
id_seudonimo: string;
|
||||
origen: 'sintetico';
|
||||
historial: AntecedenteDetalle[] | null;
|
||||
procedimientos: ProcedimientoDetalle[] | null;
|
||||
pruebas: PruebaDetalle[] | null;
|
||||
}
|
||||
|
||||
export interface PacienteDetalleProvider {
|
||||
obtener(idSeudonimo: string): Observable<PacienteDetalle | null>;
|
||||
}
|
||||
|
||||
export type PacienteDetalleEstado =
|
||||
| { tipo: 'cerrado' }
|
||||
| { tipo: 'cargando' | 'no-disponible' | 'error'; resumen: PacienteResumen }
|
||||
| { tipo: 'disponible'; resumen: PacienteResumen; detalle: PacienteDetalle };
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Injectable, InjectionToken, inject } from '@angular/core';
|
||||
import { defer, of } from 'rxjs';
|
||||
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
|
||||
import { PacienteDetalleProvider } from './paciente-detalle.models';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class PacienteDetalleMockProvider implements PacienteDetalleProvider {
|
||||
obtener(idSeudonimo: string) {
|
||||
return defer(() => {
|
||||
const detalle = PACIENTES_DETALLE_SINTETICOS.find(item => item.id_seudonimo === idSeudonimo);
|
||||
// Each read owns its data; consumers cannot mutate another selection or the fixtures.
|
||||
return of(detalle ? structuredClone(detalle) : null);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const PACIENTE_DETALLE_PROVIDER = new InjectionToken<PacienteDetalleProvider>('PacienteDetalleProvider', {
|
||||
providedIn: 'root',
|
||||
factory: () => inject(PacienteDetalleMockProvider),
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
:host { display: block; min-width: 0; color: var(--issste-text); overflow-wrap: anywhere; }
|
||||
header { margin-block: 1.5rem; }
|
||||
h2 { margin-block: .5rem 1rem; font-size: 1.65rem; }
|
||||
h3 { margin-block: 0 1rem; font-size: 1.2rem; }
|
||||
h4 { font: inherit; font-weight: 600; }
|
||||
.back-button { display: inline-flex; align-items: center; gap: .35rem; min-height: 40px; padding-inline: .65rem; }
|
||||
.back-button mat-icon { width: 1.15rem; height: 1.15rem; font-size: 1.15rem; }
|
||||
.availability { margin-block: .75rem; color: var(--issste-text-secondary); }
|
||||
.pending-changes { margin-block: .75rem; color: var(--issste-text-secondary); font-size: .9rem; }
|
||||
.summary { display: flex; flex-wrap: wrap; gap: 1.25rem 2rem; }
|
||||
dt { color: var(--issste-text-secondary); font-size: .9rem; }
|
||||
dd { margin: .4rem 0 0; font-weight: 600; }
|
||||
.detail-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-areas: "history tests" "risks risks"; gap: 1rem; align-items: start; }
|
||||
mat-card { min-width: 0; background: var(--issste-surface); color: inherit; border-color: var(--issste-border); }
|
||||
.history-card { grid-area: history; }
|
||||
.tests-card { grid-area: tests; }
|
||||
.risks-card { grid-area: risks; }
|
||||
.history-actions { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.history-table-scroll { width: 100%; min-width: 0; max-width: 100%; overflow-x: auto; margin-top: .75rem; border: 1px solid var(--issste-border); border-radius: .5rem; }
|
||||
.history-table-scroll:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
|
||||
.history-table { width: 100%; min-width: 26rem; border-collapse: separate; border-spacing: 0; text-align: start; }
|
||||
.history-table th, .history-table td { padding: .7rem .75rem; vertical-align: top; border-bottom: 1px solid var(--issste-border); }
|
||||
.history-table thead th { color: var(--issste-text-secondary); font-size: .9rem; font-weight: 600; }
|
||||
.history-table thead th:last-child, .history-table td:last-child { width: 9rem; white-space: nowrap; }
|
||||
.history-table .section-row th { text-align: start; background: color-mix(in srgb, var(--issste-surface), var(--issste-border) 24%); font-weight: 600; }
|
||||
.history-table .empty-row { color: var(--issste-text-secondary); font-size: .9rem; }
|
||||
.record-detail { display: block; margin-top: .35rem; color: var(--issste-text-secondary); font-size: .9rem; }
|
||||
.risks-card mat-card-content { min-width: 0; }
|
||||
ul { list-style: none; padding: 0; }
|
||||
li { padding-block: .75rem; border-top: 1px solid var(--issste-border); }
|
||||
li span { display: block; margin-top: .4rem; }
|
||||
button { min-height: 44px; color: var(--issste-text); border-color: var(--issste-border); }
|
||||
@media (max-width: 48rem) {
|
||||
.detail-grid { grid-template-columns: minmax(0, 1fr); grid-template-areas: "history" "tests" "risks"; }
|
||||
.history-table { min-width: 22rem; }
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { Subject, of, throwError } from 'rxjs';
|
||||
import fixtureData from '../fixtures/cacu_seguimiento.json';
|
||||
import { seguimientoResponse } from '../cacu-seguimiento.service';
|
||||
import { IndicadoresTracking } from '../indicadores-tracking';
|
||||
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
|
||||
import { PacienteDetalle, PacienteDetalleProvider } from './paciente-detalle.models';
|
||||
import { PACIENTE_DETALLE_PROVIDER, PacienteDetalleMockProvider } from './paciente-detalle.provider';
|
||||
import { PacienteDetalleState } from './paciente-detalle.state';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
|
||||
const pacientes = seguimientoResponse(fixtureData).items;
|
||||
|
||||
describe('Proveedor de detalle sintético', () => {
|
||||
it('funciona sin HttpClient y busca únicamente el seudónimo exacto', () => {
|
||||
const provider = TestBed.inject(PacienteDetalleMockProvider);
|
||||
const id = pacientes[0].id_seudonimo;
|
||||
provider.obtener(id).subscribe(detalle => expect(detalle?.id_seudonimo).toBe(id));
|
||||
for (const desconocido of ['001', '1', id.toLowerCase(), ` ${id}`, 'sin-ficha', 'toString']) {
|
||||
provider.obtener(desconocido).subscribe(detalle => expect(detalle).toBeNull());
|
||||
}
|
||||
});
|
||||
|
||||
it('aísla lecturas y conserva nulos, colecciones vacías y propiedades ausentes', () => {
|
||||
const provider = TestBed.inject(PacienteDetalleMockProvider);
|
||||
provider.obtener(pacientes[0].id_seudonimo).subscribe(detalle => {
|
||||
expect(detalle?.procedimientos).toEqual([]);
|
||||
expect(detalle?.historial?.[0].notas).toBeNull();
|
||||
detalle!.historial![0].descripcion = 'mutación local';
|
||||
});
|
||||
provider.obtener(pacientes[0].id_seudonimo).subscribe(detalle => {
|
||||
expect(detalle?.historial?.[0].descripcion).not.toBe('mutación local');
|
||||
});
|
||||
provider.obtener(pacientes[1].id_seudonimo).subscribe(detalle => {
|
||||
expect(detalle?.historial).toBeNull();
|
||||
expect(detalle?.procedimientos?.[0].resultado).toBeNull();
|
||||
expect(Object.hasOwn(detalle!.procedimientos![0], 'notas')).toBe(false);
|
||||
expect(detalle?.pruebas?.[0].fecha).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Estado de selección del paciente', () => {
|
||||
function setup(provider: PacienteDetalleProvider) {
|
||||
TestBed.configureTestingModule({ providers: [PacienteDetalleState, { provide: PACIENTE_DETALLE_PROVIDER, useValue: provider }] });
|
||||
return TestBed.inject(PacienteDetalleState);
|
||||
}
|
||||
|
||||
it('entrega el seudónimo sin conversión y toma una instantánea independiente de la fila', () => {
|
||||
const obtener = vi.fn(() => of(null));
|
||||
const state = setup({ obtener });
|
||||
const paciente = { ...pacientes[0], id_seudonimo: '001', ultimo_vph: { ...pacientes[0].ultimo_vph! }, dias_toma_diagnostico: 0 };
|
||||
state.abrir(paciente, fixtureData.corte);
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith('001');
|
||||
paciente.ultimo_vph.resultado = 'cambio posterior';
|
||||
const estado = state.estado();
|
||||
expect(estado.tipo).toBe('no-disponible');
|
||||
if (estado.tipo !== 'cerrado') {
|
||||
expect(estado.resumen.id_seudonimo).toBe('001');
|
||||
expect(estado.resumen.vph?.resultado).toBe('NEGATIVO');
|
||||
expect(estado.resumen.vph?.genotipo16y18).toBeNull();
|
||||
expect(estado.resumen.diasTomaDiagnostico).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
it('descarta respuestas tardías de otro paciente y al regresar a la lista', () => {
|
||||
const a = new Subject<PacienteDetalle | null>();
|
||||
const b = new Subject<PacienteDetalle | null>();
|
||||
const state = setup({ obtener: id => id === pacientes[0].id_seudonimo ? a : b });
|
||||
state.abrir(pacientes[0], fixtureData.corte);
|
||||
expect(state.estado().tipo).toBe('cargando');
|
||||
state.abrir(pacientes[1], fixtureData.corte);
|
||||
a.next(PACIENTES_DETALLE_SINTETICOS[0]);
|
||||
expect(state.estado().tipo).toBe('cargando');
|
||||
b.next(PACIENTES_DETALLE_SINTETICOS[1]);
|
||||
let estado = state.estado();
|
||||
expect(estado.tipo).toBe('disponible');
|
||||
if (estado.tipo === 'disponible') expect(estado.detalle.id_seudonimo).toBe(pacientes[1].id_seudonimo);
|
||||
state.abrir(pacientes[0], fixtureData.corte);
|
||||
state.cerrar();
|
||||
a.next(PACIENTES_DETALLE_SINTETICOS[0]);
|
||||
expect(state.estado()).toEqual({ tipo: 'cerrado' });
|
||||
});
|
||||
|
||||
it('no presenta detalles devueltos para un seudónimo distinto', () => {
|
||||
const state = setup({ obtener: () => of(PACIENTES_DETALLE_SINTETICOS[1]) });
|
||||
state.abrir(pacientes[0], fixtureData.corte);
|
||||
expect(state.estado().tipo).toBe('error');
|
||||
expect(state.estado()).not.toHaveProperty('detalle');
|
||||
});
|
||||
|
||||
it('mantiene el resumen ante un error del proveedor, sin exponer datos internos', () => {
|
||||
const state = setup({ obtener: () => throwError(() => new Error('private')) });
|
||||
state.abrir(pacientes[0], fixtureData.corte);
|
||||
expect(state.estado().tipo).toBe('error');
|
||||
expect(JSON.stringify(state.estado())).not.toContain('private');
|
||||
state.cerrar();
|
||||
expect(state.estado().tipo).toBe('cerrado');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Ficha individual desde Seguimiento CaCu', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresTracking>>;
|
||||
let http: HttpTestingController;
|
||||
let root: HTMLElement;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
fixture = TestBed.createComponent(IndicadoresTracking);
|
||||
root = fixture.nativeElement;
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cacu');
|
||||
fixture.componentRef.setInput('domainLabel', 'CaCu');
|
||||
fixture.componentRef.setInput('active', true);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(r => r.url === '/cacu/seguimiento').flush(fixtureData);
|
||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: { NORMAL: { etiqueta: 'Normal' } } });
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
|
||||
function accion(index = 0) { return root.querySelectorAll<HTMLButtonElement>('tbody button.patient-link')[index]; }
|
||||
function abrir(index = 0) { accion(index).click(); fixture.detectChanges(); return root.querySelector<HTMLElement>('app-paciente-detalle')!; }
|
||||
function volver() { root.querySelector<HTMLButtonElement>('app-paciente-detalle button')!.click(); fixture.detectChanges(); }
|
||||
|
||||
it('abre por acción nativa accesible, enfoca la ficha y restaura el foco sin HTTP adicional', () => {
|
||||
const button = accion();
|
||||
expect(button.type).toBe('button');
|
||||
expect(button.getAttribute('aria-label')).toBe(`Ver ficha del paciente ${pacientes[0].id_seudonimo}`);
|
||||
const focus = vi.spyOn(button, 'focus');
|
||||
const detail = abrir();
|
||||
expect(detail.querySelector('h2')?.textContent).toContain(pacientes[0].id_seudonimo);
|
||||
expect(detail.querySelector('h2')).toBe(document.activeElement);
|
||||
expect(root.querySelector('form')!.closest('[hidden]')).not.toBeNull();
|
||||
expect(detail.textContent).not.toMatch(/Datos de demostración|información adicional sintética|solo existen en memoria|no representan un expediente clínico real/i);
|
||||
expect(Array.from(detail.querySelectorAll('h3')).map(h => h.textContent)).toEqual([
|
||||
'Historial médico relevante', 'Pruebas y resultados', 'Riesgos y recomendaciones',
|
||||
]);
|
||||
expect(detail.querySelectorAll('.history-card')).toHaveLength(1);
|
||||
expect(detail.querySelectorAll('.history-card table thead th')).toHaveLength(2);
|
||||
expect(Array.from(detail.querySelectorAll('.history-card table thead th'), th => th.textContent?.trim())).toEqual(['Registro', 'Fecha']);
|
||||
expect(Array.from(detail.querySelectorAll('.history-card .section-row th'), th => th.textContent?.trim())).toEqual(['Condiciones', 'Procedimientos']);
|
||||
expect(detail.querySelector('.history-card button')?.textContent).toContain('Agregar condición');
|
||||
expect(Array.from(detail.querySelectorAll('.history-card button'), button => button.textContent?.trim())).toEqual(['Agregar condición', 'Agregar procedimiento']);
|
||||
expect(detail.querySelector('.history-card')!.compareDocumentPosition(detail.querySelector('.tests-card')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(detail.querySelector('.tests-card')!.compareDocumentPosition(detail.querySelector('.risks-card')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(detail.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(detail.querySelectorAll('app-paciente-riesgo-tabla table')).toHaveLength(0);
|
||||
expect(detail.textContent).not.toContain('Valores ilustrativos');
|
||||
volver();
|
||||
expect(root.querySelector('app-paciente-detalle')).toBeNull();
|
||||
expect(root.querySelector('form')!.closest('[hidden]')).toBeNull();
|
||||
expect(focus).toHaveBeenCalledWith({ preventScroll: true });
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('abre desde otras celdas y devuelve el foco a la fila; mantiene el seudónimo enfocable', () => {
|
||||
const row = root.querySelectorAll<HTMLTableRowElement>('tbody tr[data-paciente]')[1];
|
||||
const control = accion(1);
|
||||
expect(control.tabIndex).toBe(0);
|
||||
expect(control.getAttribute('aria-label')).toContain(pacientes[1].id_seudonimo);
|
||||
row.cells[1].click();
|
||||
fixture.detectChanges();
|
||||
const estado = fixture.componentInstance.pacienteDetalle.estado();
|
||||
expect(estado.tipo).toBe('disponible');
|
||||
if (estado.tipo === 'disponible') expect(estado.resumen.id_seudonimo).toBe(pacientes[1].id_seudonimo);
|
||||
volver();
|
||||
expect(row).toBe(document.activeElement);
|
||||
http.expectNone(() => true);
|
||||
expect(row.isConnected).toBe(true);
|
||||
});
|
||||
|
||||
it('conserva filtros aplicados, borrador, página, filas y desplazamiento de tabla al volver', () => {
|
||||
const component = fixture.componentInstance;
|
||||
component.draft = { corte: '2026-09-30', meses: 6, estatus: 'VIGILANCIA', page: 1, page_size: 10 };
|
||||
component.apply();
|
||||
const response = { ...fixtureData, ventana: { ...fixtureData.ventana, meses: 6 }, filtros: { estatus: 'VIGILANCIA' } };
|
||||
http.expectOne(r => r.url === '/cacu/seguimiento').flush(response);
|
||||
component.navigate(2);
|
||||
http.expectOne(r => r.url === '/cacu/seguimiento').flush({ ...response, paginacion: { ...fixtureData.paginacion, page: 2 } });
|
||||
fixture.detectChanges();
|
||||
component.draft.meses = 12;
|
||||
const table = root.querySelector<HTMLElement>('.tracking-table')!;
|
||||
table.scrollLeft = 200;
|
||||
const row = root.querySelector('tbody tr');
|
||||
abrir(); volver();
|
||||
expect(component.draft.meses).toBe(12);
|
||||
expect(component.draft.estatus).toBe('VIGILANCIA');
|
||||
expect(component.data?.paginacion.page).toBe(2);
|
||||
expect(root.querySelector('tbody tr')).toBe(row);
|
||||
expect(root.querySelector('.tracking-table')).toBe(table);
|
||||
expect(table.scrollLeft).toBe(200);
|
||||
http.expectNone(() => true);
|
||||
component.navigate(3);
|
||||
const request = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(request.request.params.get('meses')).toBe('6');
|
||||
expect(request.request.params.get('estatus')).toBe('VIGILANCIA');
|
||||
expect(request.request.params.get('page')).toBe('3');
|
||||
request.flush({ ...response, paginacion: { ...fixtureData.paginacion, page: 3 } });
|
||||
});
|
||||
|
||||
it('muestra ausencia de ficha sin asignar a otro paciente los antecedentes anteriores', () => {
|
||||
expect(abrir().textContent).toContain('Antecedente de tamizaje cervical');
|
||||
const riesgoNoDisponible = root.querySelector('app-paciente-riesgo-tabla')!.textContent;
|
||||
volver();
|
||||
const detail = abrir(2);
|
||||
expect(detail.textContent).toContain(pacientes[2].id_seudonimo);
|
||||
expect(detail.textContent).toContain('Información no disponible');
|
||||
expect((detail.textContent.match(/Información no disponible/g) ?? [])).toHaveLength(3);
|
||||
expect(detail.textContent).not.toContain('Antecedente de tamizaje cervical');
|
||||
expect(detail.textContent).not.toContain('Colposcopia (demostración)');
|
||||
expect(detail.textContent).toContain('Normal'); // Received study is still available.
|
||||
expect(detail.textContent).not.toContain('ficha sintética');
|
||||
expect(detail.querySelector('app-paciente-riesgo-tabla')!.textContent).toBe(riesgoNoDisponible);
|
||||
expect(detail.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
|
||||
expect(detail.querySelectorAll('app-paciente-riesgo-tabla [aria-selected]')).toHaveLength(0);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('organiza condiciones y procedimientos en una sola tabla y conserva los datos iniciales', () => {
|
||||
let detail = abrir();
|
||||
const historial = detail.querySelector('.history-card table')!;
|
||||
expect(historial.querySelectorAll('.section-row')).toHaveLength(2);
|
||||
expect(Array.from(historial.querySelectorAll('tbody tr'), row => row.textContent?.trim()).join(' ')).toContain('Antecedente de tamizaje cervical (demostración)');
|
||||
expect(Array.from(historial.querySelectorAll('tbody tr'), row => row.textContent?.trim()).join(' ')).toContain('2025-06-12');
|
||||
expect(historial.querySelectorAll('[data-registro-temporal]')).toHaveLength(0);
|
||||
volver();
|
||||
|
||||
detail = abrir(1);
|
||||
const rows = Array.from(detail.querySelectorAll('.history-card table tbody tr'));
|
||||
const procedure = rows.find(row => row.textContent?.includes('Colposcopia (demostración)'))!;
|
||||
expect(procedure.textContent).toContain('2026-06-10');
|
||||
expect(procedure.previousElementSibling?.querySelector('th')?.textContent).toBe('Procedimientos');
|
||||
expect(detail.querySelectorAll('.history-card')).toHaveLength(1);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('monta el contrato solo por inyección de prueba y no lo conserva en la siguiente ficha', () => {
|
||||
const provider = TestBed.inject(PACIENTE_RIESGO_PROVIDER);
|
||||
const obtener = vi.spyOn(provider, 'obtener').mockReturnValueOnce(of(riesgoCacuEjemplo()));
|
||||
try {
|
||||
const detail = abrir();
|
||||
const tarjeta = detail.querySelector('app-paciente-riesgo-tabla')!;
|
||||
expect(tarjeta.textContent).toContain('Información simulada');
|
||||
expect(tarjeta.querySelectorAll('tbody tr')).toHaveLength(3);
|
||||
expect(tarjeta.textContent).not.toContain(pacientes[0].id_seudonimo);
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith();
|
||||
volver();
|
||||
const otra = abrir(1);
|
||||
expect(otra.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(otra.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
} finally { obtener.mockRestore(); }
|
||||
});
|
||||
|
||||
it('distingue fuentes, nulos, falsos, ceros y listas sin registros sin inferir condiciones', () => {
|
||||
let detail = abrir();
|
||||
expect(detail.textContent).toContain('Últimos resultados');
|
||||
expect(detail.textContent).toContain('Pruebas adicionales');
|
||||
expect(detail.textContent).toContain('Genotipo 16/18: No disponible');
|
||||
expect(detail.textContent).toContain('Sin registros');
|
||||
volver();
|
||||
detail = abrir(1);
|
||||
expect(detail.textContent).toContain('Información no disponible');
|
||||
expect(detail.textContent).toContain('Resultado: No disponible');
|
||||
expect(detail.textContent).not.toContain('Antecedente de tamizaje cervical');
|
||||
volver();
|
||||
detail = abrir(5);
|
||||
expect(detail.textContent).toContain('Genotipo 16/18: No detectado');
|
||||
expect(detail.textContent).toContain('Insatisfactoria');
|
||||
expect(detail.textContent).not.toMatch(/undefined|null/);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('conserva la selección al cambiar de pestaña y la limpia al cambiar de dominio', () => {
|
||||
abrir();
|
||||
fixture.componentRef.setInput('active', false); fixture.detectChanges();
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
expect(root.querySelector('app-paciente-detalle h2')?.textContent).toContain(pacientes[0].id_seudonimo);
|
||||
fixture.componentRef.setInput('dominio', 'tea'); fixture.detectChanges();
|
||||
expect(root.querySelector('app-paciente-detalle')).toBeNull();
|
||||
expect(fixture.componentInstance.pacienteDetalle.estado().tipo).toBe('cerrado');
|
||||
expect(root.querySelector('tbody button')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('no selecciona filas ajenas a la respuesta vigente', () => {
|
||||
fixture.componentInstance.abrirPaciente({ ...pacientes[0] }, { currentTarget: accion() } as unknown as Event);
|
||||
expect(fixture.componentInstance.pacienteDetalle.estado().tipo).toBe('cerrado');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { computed, DestroyRef, Injectable, inject, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { Subject, catchError, defer, map, of, switchMap } from 'rxjs';
|
||||
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
|
||||
import { PacienteDetalleEstado, PacienteResumen } from './paciente-detalle.models';
|
||||
import { PACIENTE_DETALLE_PROVIDER } from './paciente-detalle.provider';
|
||||
import { AltaRegistroTemporal } from './paciente-registro.models';
|
||||
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
|
||||
|
||||
/** Selección por instancia de Seguimiento; las altas temporales viven aparte en la sesión Angular. */
|
||||
@Injectable()
|
||||
export class PacienteDetalleState {
|
||||
private readonly provider = inject(PACIENTE_DETALLE_PROVIDER);
|
||||
private readonly sesion = inject(PacienteRegistrosSesion);
|
||||
private readonly seleccion = new Subject<PacienteResumen | null>();
|
||||
private readonly actual = signal<PacienteDetalleEstado>({ tipo: 'cerrado' });
|
||||
readonly estado = this.actual.asReadonly();
|
||||
readonly registrosTemporales = computed(() => {
|
||||
const estado = this.actual();
|
||||
return estado.tipo === 'cerrado' ? [] : this.sesion.paraPaciente(estado.resumen.id_seudonimo);
|
||||
});
|
||||
|
||||
constructor() {
|
||||
this.seleccion.pipe(
|
||||
switchMap(resumen => resumen ? defer(() => this.provider.obtener(resumen.id_seudonimo)).pipe(
|
||||
map(detalle => {
|
||||
if (detalle && (detalle.id_seudonimo !== resumen.id_seudonimo || detalle.origen !== 'sintetico')) {
|
||||
throw new Error('Detalle incompatible con la selección');
|
||||
}
|
||||
return detalle
|
||||
? { tipo: 'disponible', resumen, detalle } as const
|
||||
: { tipo: 'no-disponible', resumen } as const;
|
||||
}),
|
||||
catchError(() => of({ tipo: 'error', resumen } as const)),
|
||||
) : of({ tipo: 'cerrado' } as const)),
|
||||
takeUntilDestroyed(inject(DestroyRef)),
|
||||
).subscribe(estado => this.actual.set(estado));
|
||||
}
|
||||
|
||||
abrir(paciente: SeguimientoPaciente, corte: string) {
|
||||
const resumen: PacienteResumen = {
|
||||
id_seudonimo: paciente.id_seudonimo,
|
||||
grupoEdad: paciente.grupo_edad === 'sin_dato' ? null : paciente.grupo_edad,
|
||||
estatus: paciente.estatus.etiqueta,
|
||||
corte,
|
||||
origen: 'seguimiento-demostracion',
|
||||
citologia: paciente.ultima_citologia ? {
|
||||
fecha: paciente.ultima_citologia.fecha,
|
||||
resultado: paciente.ultima_citologia.bethesda,
|
||||
calidad: paciente.ultima_citologia.calidad,
|
||||
} : null,
|
||||
vph: paciente.ultimo_vph ? {
|
||||
fecha: paciente.ultimo_vph.fecha,
|
||||
resultado: paciente.ultimo_vph.resultado,
|
||||
genotipo16y18: paciente.ultimo_vph.genotipo_16_18,
|
||||
} : null,
|
||||
diasTomaDiagnostico: paciente.dias_toma_diagnostico,
|
||||
prioridad: paciente.prioridad?.etiqueta ?? null,
|
||||
};
|
||||
this.actual.set({ tipo: 'cargando', resumen });
|
||||
this.seleccion.next(resumen);
|
||||
}
|
||||
|
||||
cerrar() { this.seleccion.next(null); }
|
||||
|
||||
agregarRegistro(alta: AltaRegistroTemporal) {
|
||||
const estado = this.actual();
|
||||
if (estado.tipo === 'cerrado' || estado.resumen.id_seudonimo !== alta.id_seudonimo) return false;
|
||||
return this.sesion.agregar(alta.id_seudonimo, alta.registro);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { AfterViewInit, Component, DestroyRef, ElementRef, inject, Input, OnDestroy, ViewChild, output } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { PacienteDetalleEstado } from './paciente-detalle.models';
|
||||
import { PacienteRegistroDialog } from './paciente-registro-dialog';
|
||||
import { AltaRegistroTemporal, NuevoRegistroTemporal, RegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
|
||||
import { etiquetaRegistro, etiquetaResultado } from './paciente-registros-sesion';
|
||||
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
|
||||
@Component({
|
||||
selector: 'app-paciente-detalle',
|
||||
imports: [MatButtonModule, MatCardModule, MatDialogModule, MatIconModule, PacienteRiesgoTabla],
|
||||
templateUrl: './paciente-detalle.html',
|
||||
styleUrl: './paciente-detalle.scss',
|
||||
})
|
||||
export class PacienteDetalleComponent implements AfterViewInit, OnDestroy {
|
||||
@Input({ required: true }) estado: PacienteDetalleEstado = { tipo: 'cerrado' };
|
||||
@Input() categorias: Record<string, { etiqueta: string }> = {};
|
||||
@Input() registrosTemporales: readonly RegistroTemporal[] = [];
|
||||
readonly volver = output<void>();
|
||||
readonly registroAgregado = output<AltaRegistroTemporal>();
|
||||
readonly etiquetaRegistro = etiquetaRegistro;
|
||||
readonly etiquetaResultado = etiquetaResultado;
|
||||
private readonly dialog = inject(MatDialog);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private dialogoActivo?: MatDialogRef<PacienteRegistroDialog, NuevoRegistroTemporal>;
|
||||
@ViewChild('titulo') private titulo?: ElementRef<HTMLElement>;
|
||||
ngAfterViewInit() { this.titulo?.nativeElement.focus(); }
|
||||
ngOnDestroy() { this.dialogoActivo?.close(); }
|
||||
|
||||
temporales(tipo: TipoRegistroTemporal) { return this.registrosTemporales.filter(item => item.tipo === tipo); }
|
||||
|
||||
abrirRegistro(tipo: TipoRegistroTemporal) {
|
||||
if (this.estado.tipo === 'cerrado' || this.dialogoActivo) return;
|
||||
const id_seudonimo = this.estado.resumen.id_seudonimo;
|
||||
const ref = this.dialog.open<PacienteRegistroDialog, { tipo: TipoRegistroTemporal; id_seudonimo: string }, NuevoRegistroTemporal>(PacienteRegistroDialog, {
|
||||
data: { tipo, id_seudonimo }, width: '34rem', maxWidth: 'calc(100vw - 2rem)', maxHeight: '90dvh',
|
||||
autoFocus: 'first-tabbable', restoreFocus: true, disableClose: false,
|
||||
});
|
||||
this.dialogoActivo = ref;
|
||||
ref.afterClosed().pipe(takeUntilDestroyed(this.destroy)).subscribe(registro => {
|
||||
this.dialogoActivo = undefined;
|
||||
if (registro) this.registroAgregado.emit({ id_seudonimo, registro });
|
||||
});
|
||||
}
|
||||
etiquetaCitologia(resultado: string | null, calidad: string | null) {
|
||||
if (resultado !== null) return this.categorias[resultado]?.etiqueta ?? resultado;
|
||||
return calidad?.trim().toUpperCase() === 'INSATISFACTORIO' ? 'Insatisfactoria' : 'Sin resultado al corte';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<h2 mat-dialog-title>{{ titulo }}</h2>
|
||||
<form [formGroup]="form" (ngSubmit)="agregar()">
|
||||
<mat-dialog-content>
|
||||
<p>Paciente {{ data.id_seudonimo }}</p>
|
||||
<div class="fields">
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>{{ etiquetaTipo }}</mat-label>
|
||||
<mat-select formControlName="seleccion" required>
|
||||
@for (opcion of tipos; track opcion.valor) {
|
||||
<mat-option [value]="opcion.valor">{{ opcion.etiqueta }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
@if (form.controls.seleccion.hasError('required')) { <mat-error>Selecciona una opción.</mat-error> }
|
||||
@else { <mat-error>Selecciona una opción válida.</mat-error> }
|
||||
</mat-form-field>
|
||||
@if (data.tipo === 'resultado') {
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Resultado</mat-label>
|
||||
<mat-select formControlName="resultado" required>
|
||||
@for (opcion of resultados; track opcion.valor) {
|
||||
<mat-option [value]="opcion.valor">{{ opcion.etiqueta }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
<mat-hint>Selecciona primero el tipo de estudio.</mat-hint>
|
||||
@if (form.controls.resultado.hasError('required')) { <mat-error>Selecciona un resultado para este estudio.</mat-error> }
|
||||
@else { <mat-error>El resultado no corresponde al estudio seleccionado.</mat-error> }
|
||||
</mat-form-field>
|
||||
}
|
||||
<app-fecha-compuesta formControlName="fecha" [etiqueta]="etiquetaFecha" />
|
||||
</div>
|
||||
</mat-dialog-content>
|
||||
<mat-dialog-actions align="end">
|
||||
<button mat-button type="button" [mat-dialog-close]="undefined">Cancelar</button>
|
||||
<button mat-flat-button type="submit" [disabled]="form.invalid">Agregar</button>
|
||||
</mat-dialog-actions>
|
||||
</form>
|
||||
@@ -0,0 +1,5 @@
|
||||
:host { display: block; color: var(--issste-text); }
|
||||
.fields { display: grid; gap: 1.25rem; margin-block: 1.5rem .75rem; }
|
||||
mat-form-field { width: 100%; min-width: 0; }
|
||||
button { min-height: 44px; }
|
||||
mat-dialog-actions { gap: .5rem; flex-wrap: wrap; }
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Component, DestroyRef, inject } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormControl, FormGroup, ReactiveFormsModule, ValidatorFn, Validators } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { FechaCompuesta } from './fecha-compuesta';
|
||||
import { CONDICIONES_DEMO, PROCEDIMIENTOS_DEMO, ESTUDIOS_DEMO, RESULTADOS_DEMO, esOpcion, opciones } from './paciente-registro.catalogos';
|
||||
import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
|
||||
import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation';
|
||||
|
||||
export interface RegistroDialogData { tipo: TipoRegistroTemporal; id_seudonimo: string; }
|
||||
|
||||
const opcionValida = (catalogo: Readonly<Record<string, string>>): ValidatorFn =>
|
||||
control => !control.value || esOpcion(catalogo, control.value) ? null : { opcion: true };
|
||||
const fechaValida: ValidatorFn = control => !control.value || esFechaReal(control.value) ? null : { fecha: true };
|
||||
|
||||
@Component({
|
||||
selector: 'app-paciente-registro-dialog',
|
||||
imports: [ReactiveFormsModule, MatDialogModule, MatButtonModule, MatFormFieldModule, MatSelectModule, FechaCompuesta],
|
||||
templateUrl: './paciente-registro-dialog.html',
|
||||
styleUrl: './paciente-registro-dialog.scss',
|
||||
})
|
||||
export class PacienteRegistroDialog {
|
||||
readonly data = inject<RegistroDialogData>(MAT_DIALOG_DATA);
|
||||
private readonly dialogRef = inject<MatDialogRef<PacienteRegistroDialog, NuevoRegistroTemporal>>(MatDialogRef);
|
||||
readonly titulo = this.data.tipo === 'condicion' ? 'Agregar condición'
|
||||
: this.data.tipo === 'procedimiento' ? 'Agregar procedimiento' : 'Agregar resultado';
|
||||
readonly etiquetaTipo = this.data.tipo === 'condicion' ? 'Tipo de condición'
|
||||
: this.data.tipo === 'procedimiento' ? 'Tipo de procedimiento' : 'Tipo de estudio';
|
||||
readonly etiquetaFecha = this.data.tipo === 'condicion' ? 'Fecha de inicio'
|
||||
: this.data.tipo === 'procedimiento' ? 'Fecha del procedimiento' : 'Fecha del estudio';
|
||||
private readonly catalogo = this.data.tipo === 'condicion' ? CONDICIONES_DEMO
|
||||
: this.data.tipo === 'procedimiento' ? PROCEDIMIENTOS_DEMO : ESTUDIOS_DEMO;
|
||||
readonly tipos = opciones(this.catalogo);
|
||||
resultados: ReturnType<typeof opciones> = [];
|
||||
readonly form = new FormGroup({
|
||||
seleccion: new FormControl('', { nonNullable: true, validators: [Validators.required, opcionValida(this.catalogo)] }),
|
||||
fecha: new FormControl('', { nonNullable: true, validators: [Validators.required, fechaValida] }),
|
||||
resultado: new FormControl({ value: '', disabled: true }, { nonNullable: true }),
|
||||
});
|
||||
private enviado = false;
|
||||
|
||||
constructor() {
|
||||
if (this.data.tipo === 'resultado') {
|
||||
this.form.controls.seleccion.valueChanges.pipe(takeUntilDestroyed(inject(DestroyRef))).subscribe(estudio => {
|
||||
const catalogo = esOpcion(ESTUDIOS_DEMO, estudio) ? RESULTADOS_DEMO[estudio] : null;
|
||||
this.resultados = catalogo ? opciones(catalogo) : [];
|
||||
const resultado = this.form.controls.resultado;
|
||||
resultado.reset('');
|
||||
resultado.setValidators([Validators.required, opcionValida(catalogo ?? {})]);
|
||||
if (catalogo) resultado.enable(); else resultado.disable();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
agregar() {
|
||||
this.form.markAllAsTouched();
|
||||
if (this.enviado || this.form.invalid) return;
|
||||
const { seleccion, fecha, resultado } = this.form.getRawValue();
|
||||
const registro = crearRegistroTemporal(this.data.tipo, seleccion, fecha, resultado);
|
||||
if (!registro) return;
|
||||
this.enviado = true;
|
||||
this.dialogRef.close(registro);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
import { EnvironmentInjector, createEnvironmentInjector } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
|
||||
import { MatSelectHarness } from '@angular/material/select/testing';
|
||||
import { MatInputHarness } from '@angular/material/input/testing';
|
||||
import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import fixtureData from '../fixtures/cacu_seguimiento.json';
|
||||
import { seguimientoResponse } from '../cacu-seguimiento.service';
|
||||
import { IndicadoresTracking } from '../indicadores-tracking';
|
||||
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
|
||||
import { PacienteDetalleState } from './paciente-detalle.state';
|
||||
import { PacienteRegistroDialog } from './paciente-registro-dialog';
|
||||
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
|
||||
import { TipoRegistroTemporal } from './paciente-registro.models';
|
||||
|
||||
const pacientes = seguimientoResponse(fixtureData).items;
|
||||
const acciones: { tipo: TipoRegistroTemporal; texto: string; opcion: string; resultado?: string }[] = [
|
||||
{ tipo: 'condicion', texto: 'Agregar condición', opcion: 'Embarazo' },
|
||||
{ tipo: 'procedimiento', texto: 'Agregar procedimiento', opcion: 'Colposcopia' },
|
||||
{ tipo: 'resultado', texto: 'Agregar resultado', opcion: 'VPH', resultado: 'VPH no detectado' },
|
||||
];
|
||||
|
||||
describe('Altas de demostración desde la ficha de Seguimiento', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresTracking>>;
|
||||
let root: HTMLElement;
|
||||
let http: HttpTestingController;
|
||||
let dialog: MatDialog;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
dialog = TestBed.inject(MatDialog);
|
||||
montarTracking();
|
||||
});
|
||||
|
||||
function montarTracking() {
|
||||
fixture = TestBed.createComponent(IndicadoresTracking);
|
||||
root = fixture.nativeElement;
|
||||
fixture.componentRef.setInput('dominio', 'cacu');
|
||||
fixture.componentRef.setInput('active', true);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(r => r.url === '/cacu/seguimiento' && r.method === 'GET').flush(fixtureData);
|
||||
http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/metadatos' && r.method === 'GET').flush({});
|
||||
fixture.detectChanges();
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
dialog.closeAll();
|
||||
fixture.destroy();
|
||||
http.verify();
|
||||
});
|
||||
|
||||
function abrir(index = 0) {
|
||||
root.querySelectorAll<HTMLButtonElement>('tbody button')[index].click();
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function volver() {
|
||||
root.querySelector<HTMLButtonElement>('app-paciente-detalle > button')!.click();
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function boton(texto: string) {
|
||||
return Array.from(root.querySelectorAll<HTMLButtonElement>('app-paciente-detalle button')).find(b => b.textContent?.trim() === texto)!;
|
||||
}
|
||||
async function abrirDialogo(texto: string) {
|
||||
const origen = boton(texto);
|
||||
origen.focus(); origen.click();
|
||||
expect(dialog.openDialogs).toHaveLength(1);
|
||||
const ref = dialog.openDialogs[0];
|
||||
const abierto = firstValueFrom(ref.afterOpened());
|
||||
fixture.detectChanges();
|
||||
await abierto;
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
expect(document.querySelector('[role="dialog"]')).not.toBeNull();
|
||||
expect(document.querySelector('[role="dialog"]')?.getAttribute('aria-labelledby')).toBeTruthy();
|
||||
expect(document.querySelector('[role="dialog"]')?.getAttribute('aria-describedby')).toBeNull();
|
||||
expect(document.querySelector('[role="dialog"]')?.contains(document.activeElement)).toBe(true);
|
||||
return { ref, origen };
|
||||
}
|
||||
async function confirmar() {
|
||||
const ref = dialog.openDialogs[0];
|
||||
const cerrado = firstValueFrom(ref.afterClosed());
|
||||
document.querySelector<HTMLButtonElement>('app-paciente-registro-dialog [type="submit"]')!.click();
|
||||
await cerrado;
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
}
|
||||
|
||||
async function capturarFecha(dia: string, mes: string, anio: string) {
|
||||
const loader = TestbedHarnessEnvironment.documentRootLoader(fixture);
|
||||
for (const [parte, valor] of [['dia', dia], ['mes', mes], ['anio', anio]]) {
|
||||
const input = await loader.getHarness(MatInputHarness.with({ selector: `[data-fecha="${parte}"]` }));
|
||||
await input.setValue(valor);
|
||||
}
|
||||
}
|
||||
|
||||
for (const accion of acciones) {
|
||||
it(`abre, valida y confirma «${accion.texto}» sin HTTP y restaura el foco`, async () => {
|
||||
const inicial = JSON.stringify(PACIENTES_DETALLE_SINTETICOS);
|
||||
const resumen = JSON.stringify(fixture.componentInstance.data);
|
||||
abrir();
|
||||
const { origen } = await abrirDialogo(accion.texto);
|
||||
const loader = TestbedHarnessEnvironment.documentRootLoader(fixture);
|
||||
const tipo = await loader.getHarness(MatSelectHarness.with({ selector: '[formControlName="seleccion"]' }));
|
||||
await tipo.clickOptions({ text: accion.opcion });
|
||||
if (accion.resultado) {
|
||||
const resultado = await loader.getHarness(MatSelectHarness.with({ selector: '[formControlName="resultado"]' }));
|
||||
await resultado.clickOptions({ text: accion.resultado });
|
||||
}
|
||||
await capturarFecha('26', 'Octubre', '2026');
|
||||
expect(document.querySelector<HTMLButtonElement>('app-paciente-registro-dialog [type="submit"]')!.disabled).toBe(false);
|
||||
await confirmar();
|
||||
const registro = root.querySelector(`[data-registro-temporal="${accion.tipo}"]`)!;
|
||||
expect(registro.textContent).toContain(accion.opcion);
|
||||
expect(registro.textContent).toContain('2026-10-26');
|
||||
expect(root.querySelectorAll(`[data-registro-temporal="${accion.tipo}"]`)).toHaveLength(1);
|
||||
if (accion.tipo !== 'resultado') {
|
||||
expect(registro.closest('.history-card table')).not.toBeNull();
|
||||
let encabezado = registro.previousElementSibling;
|
||||
while (encabezado && !encabezado.classList.contains('section-row')) encabezado = encabezado.previousElementSibling;
|
||||
expect(encabezado?.textContent?.trim()).toBe(accion.tipo === 'condicion' ? 'Condiciones' : 'Procedimientos');
|
||||
} else {
|
||||
expect(registro.closest('.tests-card')).not.toBeNull();
|
||||
}
|
||||
expect(root.textContent).toContain('Cambios sin guardar');
|
||||
expect(document.activeElement).toBe(origen);
|
||||
expect(JSON.stringify(PACIENTES_DETALLE_SINTETICOS)).toBe(inicial);
|
||||
expect(JSON.stringify(fixture.componentInstance.data)).toBe(resumen);
|
||||
const almacenado = fixture.componentInstance.pacienteDetalle.registrosTemporales()[0];
|
||||
expect(almacenado.id_seudonimo).toBe(pacientes[0].id_seudonimo);
|
||||
expect(almacenado.origen).toBe('sesion-demostracion');
|
||||
expect(almacenado.fecha).toBe('2026-10-26');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it(`cancela «${accion.texto}» sin guardar el borrador`, async () => {
|
||||
abrir();
|
||||
const { ref, origen } = await abrirDialogo(accion.texto);
|
||||
(ref.componentInstance as PacienteRegistroDialog).form.controls.seleccion.setValue(accion.tipo === 'resultado' ? 'vph' : accion.tipo === 'condicion' ? 'embarazo' : 'colposcopia');
|
||||
await capturarFecha('26', 'Octubre', '2026');
|
||||
const cerrado = firstValueFrom(ref.afterClosed());
|
||||
document.querySelector<HTMLButtonElement>('app-paciente-registro-dialog button[type="button"]')!.click();
|
||||
expect(await cerrado).toBeUndefined();
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()).toEqual([]);
|
||||
expect(root.querySelector('[data-registro-temporal]')).toBeNull();
|
||||
expect(document.activeElement).toBe(origen);
|
||||
await abrirDialogo(accion.texto);
|
||||
expect((dialog.openDialogs[0].componentInstance as PacienteRegistroDialog).form.controls.seleccion.value).toBe('');
|
||||
expect(Array.from(document.querySelectorAll<HTMLInputElement>('app-fecha-compuesta input')).every(input => input.value === '')).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it(`bloquea fechas incompletas e imposibles en «${accion.texto}» y admite corregirlas`, async () => {
|
||||
abrir();
|
||||
const { ref } = await abrirDialogo(accion.texto);
|
||||
const component = ref.componentInstance as PacienteRegistroDialog;
|
||||
component.form.controls.seleccion.setValue(accion.tipo === 'resultado' ? 'vph' : accion.tipo === 'condicion' ? 'embarazo' : 'colposcopia');
|
||||
if (accion.tipo === 'resultado') component.form.controls.resultado.setValue('negativo');
|
||||
for (const partes of [['29', 'Febrero', ''], ['31', 'Abril', '2024'], ['30', 'Febrero', '2024'], ['29', 'Febrero', '2025']]) {
|
||||
await capturarFecha(partes[0], partes[1], partes[2]);
|
||||
expect(component.form.controls.fecha.value).toBe('');
|
||||
expect(document.querySelector<HTMLButtonElement>('app-paciente-registro-dialog [type="submit"]')!.disabled).toBe(true);
|
||||
component.agregar();
|
||||
expect(dialog.openDialogs).toHaveLength(1);
|
||||
expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()).toEqual([]);
|
||||
}
|
||||
await capturarFecha('29', '2', '2024');
|
||||
expect(component.form.controls.fecha.value).toBe('2024-02-29');
|
||||
await confirmar();
|
||||
expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()[0].fecha).toBe('2024-02-29');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it(`Escape cierra las sugerencias de «${accion.texto}» antes de permitir cancelar el diálogo`, async () => {
|
||||
abrir();
|
||||
const { ref, origen } = await abrirDialogo(accion.texto);
|
||||
const mes = await TestbedHarnessEnvironment.documentRootLoader(fixture).getHarness(
|
||||
MatAutocompleteHarness.with({ selector: '[data-fecha="mes"]' }));
|
||||
await mes.enterText('ma');
|
||||
expect(await mes.isOpen()).toBe(true);
|
||||
const input = document.querySelector<HTMLInputElement>('[data-fecha="mes"]')!;
|
||||
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true, cancelable: true }));
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(await mes.isOpen()).toBe(false);
|
||||
expect(dialog.openDialogs).toHaveLength(1);
|
||||
expect(document.activeElement).toBe(input);
|
||||
expect(input.value).toBe('ma');
|
||||
const cerrado = firstValueFrom(ref.afterClosed());
|
||||
// Con las sugerencias cerradas, Escape conserva la cancelación habitual del modal.
|
||||
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true, cancelable: true }));
|
||||
expect(await cerrado).toBeUndefined();
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(document.activeElement).toBe(origen);
|
||||
expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()).toEqual([]);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
}
|
||||
|
||||
it('permite Escape y cierra el diálogo si se abandona la ficha sin confirmar', async () => {
|
||||
abrir();
|
||||
const { ref } = await abrirDialogo('Agregar condición');
|
||||
const cerrado = firstValueFrom(ref.afterClosed());
|
||||
document.querySelector('[role="dialog"]')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true }));
|
||||
expect(await cerrado).toBeUndefined();
|
||||
fixture.detectChanges();
|
||||
const otro = await abrirDialogo('Agregar resultado');
|
||||
const destruido = firstValueFrom(otro.ref.afterClosed());
|
||||
volver();
|
||||
expect(await destruido).toBeUndefined();
|
||||
expect(TestBed.inject(PacienteRegistrosSesion).paraPaciente(pacientes[0].id_seudonimo)).toEqual([]);
|
||||
expect(root.querySelector('app-paciente-detalle')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('agrega sin fixture, conserva las tres secciones al navegar y aísla pacientes', async () => {
|
||||
abrir(2);
|
||||
const riesgoNoDisponible = root.querySelector('app-paciente-riesgo-tabla')!.textContent;
|
||||
expect(root.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
|
||||
expect(riesgoNoDisponible).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(root.textContent).toContain('Información no disponible');
|
||||
for (const tipo of acciones) {
|
||||
const { ref } = await abrirDialogo(tipo.texto);
|
||||
const form = (ref.componentInstance as PacienteRegistroDialog).form;
|
||||
form.patchValue({ seleccion: tipo.tipo === 'condicion' ? 'lesion_cervical' : tipo.tipo === 'procedimiento' ? 'escision_cervical' : 'histologia', fecha: '2026-10-26' });
|
||||
if (tipo.tipo === 'resultado') form.controls.resultado.setValue('nic1');
|
||||
fixture.detectChanges();
|
||||
await confirmar();
|
||||
}
|
||||
expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3);
|
||||
expect(root.querySelector('app-paciente-riesgo-tabla')!.textContent).toBe(riesgoNoDisponible);
|
||||
expect(root.textContent).toContain('Recomendaciones no disponibles');
|
||||
volver(); abrir(0);
|
||||
expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(0);
|
||||
volver(); abrir(2);
|
||||
expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3);
|
||||
volver();
|
||||
fixture.destroy(); // La navegación puede desmontar Seguimiento; la aplicación sigue viva.
|
||||
montarTracking(); abrir(2);
|
||||
expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('no sustituye la última citología o VPH ni modifica el resumen, prioridades o datos recibidos', async () => {
|
||||
const inicial = structuredClone(fixture.componentInstance.data);
|
||||
abrir();
|
||||
const resumen = structuredClone(fixture.componentInstance.pacienteDetalle.estado());
|
||||
const { ref } = await abrirDialogo('Agregar resultado');
|
||||
const form = (ref.componentInstance as PacienteRegistroDialog).form;
|
||||
form.patchValue({ seleccion: 'vph', fecha: '2026-10-26' });
|
||||
form.controls.resultado.setValue('positivo_16_18');
|
||||
fixture.detectChanges(); await confirmar();
|
||||
expect(fixture.componentInstance.pacienteDetalle.estado()).toEqual(resumen);
|
||||
expect(fixture.componentInstance.data).toEqual(inicial);
|
||||
expect(root.textContent).toContain('Último resultado de VPH');
|
||||
expect(root.textContent).toContain('NEGATIVO');
|
||||
expect(root.textContent).toContain('VPH 16/18 detectado');
|
||||
expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(root.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vida de la selección y de la memoria de sesión', () => {
|
||||
it('sobrevive a nuevas instancias de selección y rechaza altas de una ficha anterior', () => {
|
||||
const parent = TestBed.inject(EnvironmentInjector);
|
||||
const crear = () => createEnvironmentInjector([PacienteDetalleState], parent);
|
||||
const primero = crear();
|
||||
const segundo = crear();
|
||||
try {
|
||||
const a = primero.get(PacienteDetalleState);
|
||||
const b = segundo.get(PacienteDetalleState);
|
||||
a.abrir(pacientes[0], fixtureData.corte);
|
||||
expect(a.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(true);
|
||||
a.cerrar();
|
||||
expect(a.registrosTemporales()).toEqual([]);
|
||||
primero.destroy();
|
||||
b.abrir(pacientes[0], fixtureData.corte);
|
||||
expect(b.registrosTemporales()).toHaveLength(1);
|
||||
b.abrir(pacientes[1], fixtureData.corte);
|
||||
expect(b.registrosTemporales()).toEqual([]);
|
||||
expect(b.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(false);
|
||||
} finally {
|
||||
if (!primero.destroyed) primero.destroy();
|
||||
segundo.destroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
/** Opciones exclusivamente sintéticas de demostración; no son una clasificación clínica validada. */
|
||||
export const CONDICIONES_DEMO = {
|
||||
embarazo: 'Embarazo',
|
||||
lesion_cervical: 'Lesión cervical',
|
||||
antecedente_cacu: 'Antecedente de cáncer cervicouterino',
|
||||
inmunosupresion: 'Inmunosupresión',
|
||||
} as const;
|
||||
|
||||
export const PROCEDIMIENTOS_DEMO = {
|
||||
colposcopia: 'Colposcopia',
|
||||
escision_cervical: 'Escisión cervical',
|
||||
ablacion_cervical: 'Ablación cervical',
|
||||
histerectomia: 'Histerectomía',
|
||||
} as const;
|
||||
|
||||
export const ESTUDIOS_DEMO = {
|
||||
vph: 'VPH',
|
||||
citologia: 'Citología cervical',
|
||||
histologia: 'Histología cervical',
|
||||
} as const;
|
||||
|
||||
export const RESULTADOS_DEMO = {
|
||||
vph: {
|
||||
negativo: 'VPH no detectado',
|
||||
positivo_16_18: 'VPH 16/18 detectado',
|
||||
positivo_otro: 'Otro VPH de alto riesgo detectado',
|
||||
},
|
||||
citologia: {
|
||||
negativa: 'Negativa para lesión intraepitelial',
|
||||
asc_us: 'ASC-US',
|
||||
lsil: 'Lesión intraepitelial de bajo grado (LSIL)',
|
||||
hsil: 'Lesión intraepitelial de alto grado (HSIL)',
|
||||
insatisfactoria: 'Muestra insatisfactoria',
|
||||
},
|
||||
histologia: {
|
||||
sin_lesion: 'Sin lesión en la muestra',
|
||||
nic1: 'NIC 1',
|
||||
nic2: 'NIC 2',
|
||||
nic3: 'NIC 3',
|
||||
},
|
||||
} as const;
|
||||
|
||||
export type TipoCondicionDemo = keyof typeof CONDICIONES_DEMO;
|
||||
export type TipoProcedimientoDemo = keyof typeof PROCEDIMIENTOS_DEMO;
|
||||
export type TipoEstudioDemo = keyof typeof ESTUDIOS_DEMO;
|
||||
|
||||
export function esOpcion<T extends object>(catalogo: T, valor: unknown): valor is Extract<keyof T, string> {
|
||||
return typeof valor === 'string' && Object.hasOwn(catalogo, valor);
|
||||
}
|
||||
|
||||
export function opciones(catalogo: Readonly<Record<string, string>>) {
|
||||
return Object.entries(catalogo).map(([valor, etiqueta]) => ({ valor, etiqueta }));
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { RESULTADOS_DEMO, TipoCondicionDemo, TipoEstudioDemo, TipoProcedimientoDemo } from './paciente-registro.catalogos';
|
||||
|
||||
type ResultadoDemo = {
|
||||
[E in TipoEstudioDemo]: { estudio: E; resultado: keyof typeof RESULTADOS_DEMO[E] }
|
||||
}[TipoEstudioDemo];
|
||||
|
||||
export type NuevoRegistroTemporal =
|
||||
| { tipo: 'condicion'; condicion: TipoCondicionDemo; fecha: string }
|
||||
| { tipo: 'procedimiento'; procedimiento: TipoProcedimientoDemo; fecha: string }
|
||||
| ({ tipo: 'resultado'; fecha: string } & ResultadoDemo);
|
||||
|
||||
export type TipoRegistroTemporal = NuevoRegistroTemporal['tipo'];
|
||||
|
||||
/** Independiente del resumen recibido y del historial inicial del proveedor. */
|
||||
export type RegistroTemporal = Readonly<NuevoRegistroTemporal & {
|
||||
id: number;
|
||||
id_seudonimo: string;
|
||||
origen: 'sesion-demostracion';
|
||||
}>;
|
||||
|
||||
export interface AltaRegistroTemporal {
|
||||
id_seudonimo: string;
|
||||
registro: NuevoRegistroTemporal;
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
|
||||
import { ESTUDIOS_DEMO, RESULTADOS_DEMO } from './paciente-registro.catalogos';
|
||||
import { PacienteRegistroDialog } from './paciente-registro-dialog';
|
||||
import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
|
||||
import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation';
|
||||
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
|
||||
|
||||
describe('Fecha de calendario de registros temporales', () => {
|
||||
it('acepta días reales, incluyendo años bisiestos y límites de año', () => {
|
||||
for (const fecha of ['2024-02-29', '2000-02-29', '2026-04-30', '0001-01-01', '9999-12-31']) {
|
||||
expect(esFechaReal(fecha), fecha).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('rechaza fechas imposibles, normalizaciones y cadenas arbitrarias', () => {
|
||||
for (const fecha of ['', 'ayer', '2026-02-29', '1900-02-29', '2026-04-31', '2026-00-01', '2026-13-01',
|
||||
'2026-01-00', '0000-01-01', '2026-1-1', '26/10/2026', ' 2026-10-26', '2026-10-26T00:00:00Z', null, new Date()]) {
|
||||
expect(esFechaReal(fecha), String(fecha)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const casos: { tipo: TipoRegistroTemporal; seleccion: string; registro: NuevoRegistroTemporal }[] = [
|
||||
{ tipo: 'condicion', seleccion: 'embarazo', registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } },
|
||||
{ tipo: 'procedimiento', seleccion: 'colposcopia', registro: { tipo: 'procedimiento', procedimiento: 'colposcopia', fecha: '2026-10-26' } },
|
||||
{ tipo: 'resultado', seleccion: 'vph', registro: { tipo: 'resultado', estudio: 'vph', resultado: 'negativo', fecha: '2026-10-26' } },
|
||||
];
|
||||
|
||||
describe.each(casos)('Formulario de $tipo', caso => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<PacienteRegistroDialog>>;
|
||||
let component: PacienteRegistroDialog;
|
||||
let cerrar: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
cerrar = vi.fn();
|
||||
TestBed.configureTestingModule({ providers: [
|
||||
{ provide: MAT_DIALOG_DATA, useValue: { tipo: caso.tipo, id_seudonimo: '001' } },
|
||||
{ provide: MatDialogRef, useValue: { close: cerrar } },
|
||||
] });
|
||||
fixture = TestBed.createComponent(PacienteRegistroDialog);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('muestra destino, campos obligatorios y confirmación deshabilitada sin texto técnico', () => {
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.textContent).not.toMatch(/demostración|sintético|persistencia|solo existe en esta sesión/i);
|
||||
expect(root.textContent).toContain('Paciente 001');
|
||||
expect(root.querySelector<HTMLButtonElement>('[type="submit"]')!.disabled).toBe(true);
|
||||
component.agregar();
|
||||
fixture.detectChanges();
|
||||
expect(root.textContent).toContain('Selecciona una opción');
|
||||
expect(root.textContent).toContain('Ingresa una fecha válida');
|
||||
expect(cerrar).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rechaza opciones ajenas al catálogo y fechas inválidas antes de cerrar', () => {
|
||||
component.form.patchValue({ seleccion: 'toString', fecha: '2026-02-30' });
|
||||
component.agregar();
|
||||
fixture.detectChanges();
|
||||
expect(component.form.invalid).toBe(true);
|
||||
expect(fixture.nativeElement.textContent).toContain('Ingresa una fecha real');
|
||||
expect(cerrar).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('confirma exactamente una vez con un registro válido y tipado', () => {
|
||||
component.form.patchValue({ seleccion: caso.seleccion, fecha: caso.registro.fecha });
|
||||
if (caso.registro.tipo === 'resultado') component.form.controls.resultado.setValue(caso.registro.resultado);
|
||||
fixture.detectChanges();
|
||||
expect(component.form.valid).toBe(true);
|
||||
expect(fixture.nativeElement.querySelector('[type="submit"]').disabled).toBe(false);
|
||||
fixture.nativeElement.querySelector('form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
|
||||
component.agregar();
|
||||
expect(cerrar).toHaveBeenCalledExactlyOnceWith(caso.registro);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Resultados dependientes del estudio', () => {
|
||||
let component: PacienteRegistroDialog;
|
||||
let cerrar: ReturnType<typeof vi.fn>;
|
||||
beforeEach(() => {
|
||||
cerrar = vi.fn();
|
||||
TestBed.configureTestingModule({ providers: [
|
||||
{ provide: MAT_DIALOG_DATA, useValue: { tipo: 'resultado', id_seudonimo: 'A' } },
|
||||
{ provide: MatDialogRef, useValue: { close: cerrar } },
|
||||
] });
|
||||
const fixture = TestBed.createComponent(PacienteRegistroDialog);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('limpia el resultado al cambiar de estudio y exige elegir uno compatible', () => {
|
||||
expect(component.form.controls.resultado.disabled).toBe(true);
|
||||
component.form.patchValue({ seleccion: 'vph', fecha: '2026-10-26' });
|
||||
component.form.controls.resultado.setValue('positivo_16_18');
|
||||
expect(component.form.valid).toBe(true);
|
||||
component.form.controls.seleccion.setValue('citologia');
|
||||
expect(component.form.controls.resultado.value).toBe('');
|
||||
expect(component.form.invalid).toBe(true);
|
||||
expect(component.resultados.map(r => r.valor)).not.toContain('positivo_16_18');
|
||||
component.form.controls.resultado.setValue('positivo_16_18');
|
||||
component.agregar();
|
||||
expect(cerrar).not.toHaveBeenCalled();
|
||||
component.form.controls.resultado.setValue('asc_us');
|
||||
expect(component.form.valid).toBe(true);
|
||||
component.form.controls.seleccion.setValue('');
|
||||
expect(component.form.controls.resultado.value).toBe('');
|
||||
expect(component.form.controls.resultado.disabled).toBe(true);
|
||||
expect(component.resultados).toEqual([]);
|
||||
expect(component.form.invalid).toBe(true);
|
||||
});
|
||||
|
||||
it('admite cada pareja de los tres catálogos y rechaza combinaciones cruzadas', () => {
|
||||
for (const estudio of Object.keys(ESTUDIOS_DEMO) as (keyof typeof ESTUDIOS_DEMO)[]) {
|
||||
component.form.patchValue({ seleccion: estudio, fecha: '2026-10-26' });
|
||||
expect(component.resultados.map(r => r.valor)).toEqual(Object.keys(RESULTADOS_DEMO[estudio]));
|
||||
for (const resultado of Object.keys(RESULTADOS_DEMO[estudio])) {
|
||||
component.form.controls.resultado.setValue(resultado);
|
||||
expect(component.form.valid).toBe(true);
|
||||
expect(crearRegistroTemporal('resultado', estudio, '2026-10-26', resultado)).toEqual({ tipo: 'resultado', estudio, fecha: '2026-10-26', resultado });
|
||||
}
|
||||
}
|
||||
expect(crearRegistroTemporal('resultado', 'histologia', '2026-10-26', 'positivo_16_18')).toBeNull();
|
||||
expect(crearRegistroTemporal('resultado', 'vph', '2026-10-26', 'nic3')).toBeNull();
|
||||
expect(crearRegistroTemporal('resultado', 'toString', '2026-10-26', 'toString')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Memoria de registros temporales', () => {
|
||||
it('asocia las tres altas al seudónimo exacto sin convertir ni mezclar identidades', () => {
|
||||
const sesion = TestBed.inject(PacienteRegistrosSesion);
|
||||
for (const caso of casos) expect(sesion.agregar('001', caso.registro)).toBe(true);
|
||||
expect(sesion.paraPaciente('001').map(r => r.tipo)).toEqual(['condicion', 'procedimiento', 'resultado']);
|
||||
expect(sesion.paraPaciente('001').every(r => r.id_seudonimo === '001' && r.origen === 'sesion-demostracion')).toBe(true);
|
||||
for (const id of ['1', ' 001', '001 ', 'otro', 'toString']) expect(sesion.paraPaciente(id)).toEqual([]);
|
||||
sesion.agregar('toString', casos[0].registro);
|
||||
expect(sesion.paraPaciente('toString')).toHaveLength(1);
|
||||
expect(sesion.paraPaciente('001')).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('conserva instantáneas inmutables y no retiene el objeto de entrada', () => {
|
||||
const sesion = TestBed.inject(PacienteRegistrosSesion);
|
||||
const nuevo = { ...casos[0].registro };
|
||||
const vacio = sesion.paraPaciente('A');
|
||||
sesion.agregar('A', nuevo);
|
||||
const primera = sesion.paraPaciente('A');
|
||||
nuevo.fecha = '2000-01-01';
|
||||
sesion.agregar('A', casos[1].registro);
|
||||
expect(vacio).toEqual([]);
|
||||
expect(primera).toHaveLength(1);
|
||||
expect(primera[0].fecha).toBe('2026-10-26');
|
||||
expect(Object.isFrozen(primera)).toBe(true);
|
||||
expect(Object.isFrozen(primera[0])).toBe(true);
|
||||
expect(new Set(sesion.paraPaciente('A').map(r => r.id)).size).toBe(2);
|
||||
});
|
||||
|
||||
it('defiende la escritura en memoria de fechas y combinaciones inválidas', () => {
|
||||
const sesion = TestBed.inject(PacienteRegistrosSesion);
|
||||
expect(sesion.agregar('A', { ...casos[0].registro, fecha: 'ayer' })).toBe(false);
|
||||
expect(sesion.agregar('', casos[0].registro)).toBe(false);
|
||||
expect(sesion.agregar('A', { tipo: 'resultado', estudio: 'vph', resultado: 'nic3', fecha: '2026-10-26' } as unknown as NuevoRegistroTemporal)).toBe(false);
|
||||
expect(sesion.paraPaciente('A')).toEqual([]);
|
||||
});
|
||||
|
||||
it('una nueva instancia de aplicación empieza vacía, sin leer ni escribir almacenamiento web', () => {
|
||||
const storage = [vi.spyOn(Storage.prototype, 'setItem'), vi.spyOn(Storage.prototype, 'getItem')];
|
||||
const anterior = TestBed.inject(PacienteRegistrosSesion);
|
||||
anterior.agregar('001', casos[0].registro);
|
||||
TestBed.resetTestingModule();
|
||||
const nueva = TestBed.inject(PacienteRegistrosSesion);
|
||||
expect(nueva).not.toBe(anterior);
|
||||
expect(nueva.paraPaciente('001')).toEqual([]);
|
||||
for (const spy of storage) { expect(spy).not.toHaveBeenCalled(); spy.mockRestore(); }
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { CONDICIONES_DEMO, PROCEDIMIENTOS_DEMO, ESTUDIOS_DEMO, RESULTADOS_DEMO, esOpcion } from './paciente-registro.catalogos';
|
||||
import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
|
||||
|
||||
/** Fecha de calendario ISO estricta, sin normalización permisiva de Date.parse ni huso horario. */
|
||||
export function esFechaReal(valor: unknown): valor is string {
|
||||
if (typeof valor !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(valor)) return false;
|
||||
const [anio, mes, dia] = valor.split('-').map(Number);
|
||||
if (anio < 1 || mes < 1 || mes > 12 || dia < 1) return false;
|
||||
const bisiesto = anio % 4 === 0 && (anio % 100 !== 0 || anio % 400 === 0);
|
||||
const dias = [31, bisiesto ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
return dia <= dias[mes - 1];
|
||||
}
|
||||
|
||||
/** La misma frontera de validación se usa al enviar el formulario y al escribir en memoria. */
|
||||
export function crearRegistroTemporal(
|
||||
tipo: TipoRegistroTemporal,
|
||||
seleccion: string,
|
||||
fecha: string,
|
||||
resultado = '',
|
||||
): NuevoRegistroTemporal | null {
|
||||
if (!esFechaReal(fecha)) return null;
|
||||
switch (tipo) {
|
||||
case 'condicion':
|
||||
return esOpcion(CONDICIONES_DEMO, seleccion) ? { tipo, condicion: seleccion, fecha } : null;
|
||||
case 'procedimiento':
|
||||
return esOpcion(PROCEDIMIENTOS_DEMO, seleccion) ? { tipo, procedimiento: seleccion, fecha } : null;
|
||||
case 'resultado':
|
||||
if (!esOpcion(ESTUDIOS_DEMO, seleccion) || !esOpcion(RESULTADOS_DEMO[seleccion], resultado)) return null;
|
||||
// La pertenencia al catálogo del estudio se comprobó arriba; conserva esa pareja en el modelo.
|
||||
return { tipo, estudio: seleccion, resultado, fecha } as NuevoRegistroTemporal;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Injectable, signal } from '@angular/core';
|
||||
import { CONDICIONES_DEMO, PROCEDIMIENTOS_DEMO, ESTUDIOS_DEMO, RESULTADOS_DEMO } from './paciente-registro.catalogos';
|
||||
import { NuevoRegistroTemporal, RegistroTemporal } from './paciente-registro.models';
|
||||
import { crearRegistroTemporal } from './paciente-registro.validation';
|
||||
|
||||
const SIN_REGISTROS: readonly RegistroTemporal[] = Object.freeze([]);
|
||||
|
||||
/** Una instancia por aplicación Angular. Se pierde en una recarga completa, sin almacenamiento externo. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class PacienteRegistrosSesion {
|
||||
private readonly registros = signal<ReadonlyMap<string, readonly RegistroTemporal[]>>(new Map());
|
||||
private siguienteId = 0;
|
||||
|
||||
paraPaciente(idSeudonimo: string): readonly RegistroTemporal[] {
|
||||
return this.registros().get(idSeudonimo) ?? SIN_REGISTROS;
|
||||
}
|
||||
|
||||
agregar(idSeudonimo: string, nuevo: NuevoRegistroTemporal): boolean {
|
||||
if (!idSeudonimo || !nuevo) return false;
|
||||
const seleccion = nuevo.tipo === 'condicion' ? nuevo.condicion
|
||||
: nuevo.tipo === 'procedimiento' ? nuevo.procedimiento : nuevo.estudio;
|
||||
const validado = crearRegistroTemporal(nuevo.tipo, seleccion, nuevo.fecha, nuevo.tipo === 'resultado' ? nuevo.resultado : '');
|
||||
if (!validado) return false;
|
||||
const registro: RegistroTemporal = Object.freeze({
|
||||
...validado, id: ++this.siguienteId, id_seudonimo: idSeudonimo, origen: 'sesion-demostracion',
|
||||
});
|
||||
this.registros.update(actual => new Map(actual).set(idSeudonimo, Object.freeze([
|
||||
...(actual.get(idSeudonimo) ?? []), registro,
|
||||
])));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export function etiquetaRegistro(registro: RegistroTemporal): string {
|
||||
switch (registro.tipo) {
|
||||
case 'condicion': return CONDICIONES_DEMO[registro.condicion];
|
||||
case 'procedimiento': return PROCEDIMIENTOS_DEMO[registro.procedimiento];
|
||||
case 'resultado': return ESTUDIOS_DEMO[registro.estudio];
|
||||
}
|
||||
}
|
||||
|
||||
export function etiquetaResultado(registro: RegistroTemporal): string {
|
||||
return registro.tipo === 'resultado'
|
||||
? (RESULTADOS_DEMO[registro.estudio] as Readonly<Record<string, string>>)[registro.resultado] : '';
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<h4>Riesgo individual CaCu</h4>
|
||||
@let lectura = estado();
|
||||
@switch (lectura.tipo) {
|
||||
@case ('cargando') { <p role="status">Cargando riesgo individual…</p> }
|
||||
@case ('no-disponible') {
|
||||
<p role="status">Riesgo individual no disponible para esta paciente.</p>
|
||||
<p class="availability">La consulta de riesgo individual aún no está habilitada.</p>
|
||||
}
|
||||
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
|
||||
@case ('disponible') {
|
||||
<p class="simulated-label" id="riesgo-simulado">Información simulada · Entorno DEV · Sin evaluación clínica</p>
|
||||
@if (lectura.datos.cohorte; as cohorte) {
|
||||
<h5>Cohorte</h5>
|
||||
<dl class="metadata">
|
||||
<div><dt>Definición de cohorte</dt><dd>{{ cohorte.url }}</dd></div>
|
||||
<div><dt>Versión de cohorte</dt><dd>{{ cohorte.version }}</dd></div>
|
||||
<div><dt>Fecha índice</dt><dd>{{ cohorte.fecha_indice }}</dd></div>
|
||||
</dl>
|
||||
<details>
|
||||
<summary>Variables del modelo PIMM</summary>
|
||||
<p class="availability">Códigos técnicos del modelo; no constituyen un diagnóstico.</p>
|
||||
<dl class="metadata">
|
||||
<div><dt>tipo_censura</dt><dd>{{ cohorte.tipo_censura ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>c (estado basal)</dt><dd>{{ cohorte.c ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>l (años desde índice)</dt><dd>{{ cohorte.l ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>r (años desde índice)</dt><dd>{{ cohorte.r ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>pap_0 (citología índice)</dt><dd>{{ cohorte.pap_0 ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>hpv_0 (VPH índice)</dt><dd>{{ cohorte.hpv_0 ?? 'No disponible' }}</dd></div>
|
||||
</dl>
|
||||
</details>
|
||||
} @else {
|
||||
<p role="status">Sin membresía en la cohorte vigente.</p>
|
||||
}
|
||||
@if (lectura.datos.riesgo; as riesgo) {
|
||||
<h5>Modelo y evaluación</h5>
|
||||
<dl class="metadata">
|
||||
<div><dt>Modelo</dt><dd>{{ riesgo.modelo_nombre }}</dd></div>
|
||||
<div><dt>Versión del modelo</dt><dd>{{ riesgo.modelo_version }}</dd></div>
|
||||
<div><dt>Evaluado en (UTC)</dt><dd>{{ riesgo.evaluado_en }}</dd></div>
|
||||
<div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
|
||||
</dl>
|
||||
@if (riesgo.horizontes.length) {
|
||||
<div class="risk-scroll" role="region" aria-label="Probabilidades por horizonte, tabla desplazable" tabindex="0">
|
||||
<table aria-describedby="riesgo-simulado">
|
||||
<caption>Probabilidades simuladas por horizonte desde la fecha índice</caption>
|
||||
<thead><tr>
|
||||
<th scope="col">Horizonte (años)</th>
|
||||
<th scope="col">Probabilidad (%)</th>
|
||||
<th scope="col">Intervalo de confianza (%)</th>
|
||||
<th scope="col">Estado de evaluación</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
@for (h of riesgo.horizontes; track h.horizonte_anios) {
|
||||
<tr>
|
||||
<th scope="row">{{ h.horizonte_anios }}</th>
|
||||
<td class="percentage">{{ h.probabilidad * 100 | number:'1.0-4' }} %</td>
|
||||
<td class="interval">@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }</td>
|
||||
<td>{{ h.estado === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
|
||||
} @else { <p role="status">Sin riesgo disponible: no hay lote vigente.</p> }
|
||||
}
|
||||
}
|
||||
<p class="recommendations">Recomendaciones no disponibles.</p>
|
||||
@@ -0,0 +1,20 @@
|
||||
:host { display: block; min-width: 0; max-width: 100%; }
|
||||
h4 { margin-block: 0 .5rem; font-size: 1.05rem; }
|
||||
h5 { margin-block: 1rem .5rem; font-size: 1rem; }
|
||||
.simulated-label { border-inline-start: 3px solid var(--issste-accent); padding: .75rem; font-weight: 600; }
|
||||
.availability, .recommendations { color: var(--issste-text-secondary); font-size: .9rem; margin-block: .5rem 1rem; }
|
||||
.metadata { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 13rem), 1fr)); gap: 1rem; }
|
||||
.metadata div { min-width: 0; }
|
||||
dt { color: var(--issste-text-secondary); font-size: .9rem; }
|
||||
dd { margin: .3rem 0 0; overflow-wrap: anywhere; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
.risk-scroll { width: 100%; min-width: 0; max-width: 100%; max-height: 28rem; overflow: auto;
|
||||
border: 1px solid var(--issste-border); border-radius: .5rem; box-sizing: border-box; }
|
||||
.risk-scroll:focus-visible, summary:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
|
||||
table { width: 100%; min-width: 36rem; border-collapse: separate; border-spacing: 0; text-align: start; font-size: .9rem; }
|
||||
caption { text-align: start; padding: .75rem; color: var(--issste-text-secondary); }
|
||||
th, td { padding: .85rem .75rem; vertical-align: top; border-bottom: 1px solid var(--issste-border); overflow-wrap: anywhere; }
|
||||
thead th { position: sticky; top: 0; background: var(--issste-background, var(--issste-surface)); font-weight: 600; z-index: 1; }
|
||||
tbody th, td { background: var(--issste-surface); }
|
||||
tbody tr:last-child > * { border-bottom: 0; }
|
||||
.percentage, .interval { font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { PacienteRiesgoState } from './paciente-riesgo.state';
|
||||
import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
|
||||
@Component({
|
||||
selector: 'app-paciente-riesgo-tabla',
|
||||
imports: [DecimalPipe],
|
||||
providers: [PacienteRiesgoState],
|
||||
templateUrl: './paciente-riesgo-tabla.html',
|
||||
styleUrl: './paciente-riesgo-tabla.scss',
|
||||
})
|
||||
export class PacienteRiesgoTabla {
|
||||
readonly estado = inject(PacienteRiesgoState).estado;
|
||||
readonly tieneIntervalo = tieneIntervalo;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
export type EstadoEvaluacionCacu = 'preliminary' | 'final';
|
||||
export type TipoCensuraCacu = 'prevalente' | 'incidente' | 'izquierda' | 'derecha' | 'derechaBasal' | 'no_informativo';
|
||||
|
||||
export interface CohorteRiesgoCacu {
|
||||
url: string;
|
||||
version: string;
|
||||
fecha_indice: string;
|
||||
tipo_censura: TipoCensuraCacu | null;
|
||||
c: number | null;
|
||||
l: number | null;
|
||||
r: number | null;
|
||||
pap_0: string | null;
|
||||
hpv_0: string | null;
|
||||
}
|
||||
|
||||
export interface HorizonteRiesgoCacu {
|
||||
horizonte_anios: number;
|
||||
/** Transport values remain probabilities in [0, 1], never percentages. */
|
||||
probabilidad: number;
|
||||
ic_bajo?: number | null;
|
||||
ic_alto?: number | null;
|
||||
estado: EstadoEvaluacionCacu;
|
||||
}
|
||||
|
||||
export interface LoteRiesgoCacu {
|
||||
lote_id: number;
|
||||
modelo_nombre: string;
|
||||
modelo_version: string;
|
||||
evaluado_en: string;
|
||||
estado_lote: EstadoEvaluacionCacu;
|
||||
horizontes: HorizonteRiesgoCacu[];
|
||||
}
|
||||
|
||||
/** DEV-only contract from cacu_riesgo_paciente.md, 2026-10-28. */
|
||||
export interface RiesgoPacienteCacu {
|
||||
simulado: true;
|
||||
cohorte: CohorteRiesgoCacu | null;
|
||||
riesgo: LoteRiesgoCacu | null;
|
||||
}
|
||||
|
||||
/** Deliberately no patient argument until secure identity resolution is authorized. */
|
||||
export interface PacienteRiesgoProvider {
|
||||
obtener(): Observable<unknown>;
|
||||
}
|
||||
|
||||
export type PacienteRiesgoEstado =
|
||||
| { tipo: 'cargando' | 'no-disponible' | 'error' }
|
||||
| { tipo: 'disponible'; datos: RiesgoPacienteCacu };
|
||||
@@ -0,0 +1,8 @@
|
||||
import { InjectionToken } from '@angular/core';
|
||||
import { of } from 'rxjs';
|
||||
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
|
||||
|
||||
// No HTTP, fixtures or identity conversion. A real adapter requires separate authorization.
|
||||
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
|
||||
providedIn: 'root', factory: () => ({ obtener: () => of(null) }),
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { of, Subject, throwError } from 'rxjs';
|
||||
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
|
||||
describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
function setup(provider?: PacienteRiesgoProvider) {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
|
||||
...(provider ? [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: provider }] : [])] });
|
||||
const fixture = TestBed.createComponent(PacienteRiesgoTabla);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
afterEach(() => {
|
||||
TestBed.inject(HttpTestingController).expectNone(() => true);
|
||||
TestBed.inject(HttpTestingController).verify();
|
||||
});
|
||||
|
||||
it('ejecución normal sin fixtures, HTTP, identidad o controles de preview', () => {
|
||||
const f = setup(), root: HTMLElement = f.nativeElement;
|
||||
expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(root.textContent).toContain('aún no está habilitada');
|
||||
expect(root.textContent).toContain('Recomendaciones no disponibles');
|
||||
expect(root.textContent).not.toMatch(/simulad|ilustrativ|modelo-cacu|CIN3|2\.4|6\.8/);
|
||||
expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0);
|
||||
TestBed.inject(PACIENTE_RIESGO_PROVIDER).obtener().subscribe(v => expect(v).toBeNull());
|
||||
});
|
||||
|
||||
it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => {
|
||||
const data = riesgoCacuEjemplo(), obtener = vi.fn(() => of(data));
|
||||
data.riesgo!.horizontes[1].estado = 'preliminary';
|
||||
const baseline = structuredClone(data);
|
||||
const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith();
|
||||
expect(root.querySelectorAll('thead th')).toHaveLength(4);
|
||||
expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
|
||||
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']);
|
||||
expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %');
|
||||
expect(root.textContent).toContain('Final (final)');
|
||||
expect(root.textContent).toContain('Preliminar (preliminary)');
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', 'cacu/cohorte_vigilancia', '0.2.0', '2023-04-15', 'incidente', 'ASC-US', 'POSITIVO']) {
|
||||
expect(root.textContent).toContain(value);
|
||||
}
|
||||
expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-simulado');
|
||||
expect(root.querySelector('#riesgo-simulado')!.textContent).toContain('Información simulada · Entorno DEV');
|
||||
expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/);
|
||||
// Internal batch key stays in the contract, never in a UI label.
|
||||
expect(root.textContent).not.toContain('lote_id');
|
||||
expect(data).toEqual(baseline);
|
||||
});
|
||||
|
||||
it('mantiene tabla desplazable, foco de teclado y detalles técnicos accesibles', () => {
|
||||
const f = setup({ obtener: () => of(riesgoCacuEjemplo()) }), root: HTMLElement = f.nativeElement;
|
||||
const scroll = root.querySelector<HTMLElement>('.risk-scroll')!;
|
||||
expect(scroll.tabIndex).toBe(0);
|
||||
expect(scroll.getAttribute('role')).toBe('region');
|
||||
expect(scroll.getAttribute('aria-label')).toContain('tabla desplazable');
|
||||
expect(getComputedStyle(scroll).overflow).toBe('auto');
|
||||
expect(getComputedStyle(scroll).maxWidth).toBe('100%');
|
||||
expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem');
|
||||
expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky');
|
||||
expect(root.querySelector('details summary')!.textContent).toBe('Variables del modelo PIMM');
|
||||
expect(root.textContent).toContain('no constituyen un diagnóstico');
|
||||
});
|
||||
|
||||
it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => {
|
||||
const data = riesgoCacuEjemplo();
|
||||
data.riesgo!.estado_lote = 'preliminary';
|
||||
data.riesgo!.horizontes = [
|
||||
{ horizonte_anios: 0.5, probabilidad: 0, ic_bajo: 0, ic_alto: 0, estado: 'preliminary' },
|
||||
{ horizonte_anios: 8, probabilidad: 1, ic_bajo: null, ic_alto: 1, estado: 'final' },
|
||||
{ horizonte_anios: 12.25, probabilidad: 0.00123, estado: 'final' },
|
||||
];
|
||||
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
|
||||
expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']);
|
||||
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['0 %', '100 %', '0.123 %']);
|
||||
expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['0 % – 0 %', 'No disponible', 'No disponible']);
|
||||
expect(root.textContent).toContain('Preliminar (preliminary)');
|
||||
});
|
||||
|
||||
it('preserva variables nulas y el cero basal sin convertirlos en hallazgos', () => {
|
||||
const data = riesgoCacuEjemplo();
|
||||
data.cohorte = { ...data.cohorte!, c: 0, l: null, r: null, pap_0: null, hpv_0: null, tipo_censura: null };
|
||||
const f = setup({ obtener: () => of(data) });
|
||||
const valores = [...f.nativeElement.querySelectorAll('details dd')].map((d: any) => d.textContent);
|
||||
expect(valores).toEqual(['No disponible', '0', 'No disponible', 'No disponible', 'No disponible', 'No disponible']);
|
||||
expect(f.nativeElement.textContent).not.toMatch(/undefined|null/);
|
||||
});
|
||||
|
||||
it.each(['cohorte', 'riesgo', 'horizontes', 'ambos'])('distingue ausencia de %s', caso => {
|
||||
const data = riesgoCacuEjemplo();
|
||||
if (caso === 'cohorte' || caso === 'ambos') data.cohorte = null;
|
||||
if (caso === 'riesgo' || caso === 'ambos') data.riesgo = null;
|
||||
if (caso === 'horizontes') data.riesgo!.horizontes = [];
|
||||
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
|
||||
if (!data.cohorte) expect(root.textContent).toContain('Sin membresía en la cohorte vigente');
|
||||
if (!data.riesgo) expect(root.textContent).toContain('Sin riesgo disponible: no hay lote vigente');
|
||||
if (caso === 'horizontes') expect(root.textContent).toContain('Sin horizontes evaluados');
|
||||
if (caso !== 'cohorte') expect(root.querySelector('table')).toBeNull();
|
||||
expect(root.textContent).toContain('Información simulada');
|
||||
expect(root.textContent).toContain('Recomendaciones no disponibles');
|
||||
});
|
||||
|
||||
it.each([false, 'true', undefined])('no expone una respuesta no simulada (%s)', simulado => {
|
||||
const data = { ...riesgoCacuEjemplo(), simulado };
|
||||
const f = setup({ obtener: () => of(data) });
|
||||
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(f.nativeElement.textContent).not.toContain('modelo-cacu');
|
||||
expect(f.nativeElement.querySelector('table')).toBeNull();
|
||||
});
|
||||
|
||||
it('rechaza probabilidades inválidas sin presentar parcialmente la cohorte', () => {
|
||||
const data = riesgoCacuEjemplo(); data.riesgo!.horizontes[0].probabilidad = 12;
|
||||
const f = setup({ obtener: () => of(data) });
|
||||
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(f.nativeElement.querySelectorAll('table, dl')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('representa carga y cancela la suscripción al desmontarse', () => {
|
||||
const source = new Subject<unknown>(), f = setup({ obtener: () => source });
|
||||
expect(f.nativeElement.textContent).toContain('Cargando riesgo individual');
|
||||
expect(source.observed).toBe(true);
|
||||
f.destroy(); expect(source.observed).toBe(false);
|
||||
});
|
||||
|
||||
it('aísla estado y fixture entre instancias sin reutilizar información', () => {
|
||||
const source = new Subject<unknown>(), f = setup({ obtener: () => source });
|
||||
const data = riesgoCacuEjemplo(); source.next(data); f.detectChanges();
|
||||
data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges();
|
||||
expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %');
|
||||
f.destroy();
|
||||
const otra = TestBed.createComponent(PacienteRiesgoTabla); otra.detectChanges();
|
||||
expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual');
|
||||
expect(otra.nativeElement.querySelector('table')).toBeNull();
|
||||
expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08);
|
||||
otra.destroy(); expect(source.observed).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['observable', 'sincrono'])('oculta detalles internos del error %s', tipo => {
|
||||
const error = new Error('private pac_id=4821');
|
||||
const f = setup({ obtener: () => { if (tipo === 'sincrono') throw error; return throwError(() => error); } });
|
||||
expect(f.nativeElement.querySelector('[role="alert"]')!.textContent).toContain('No se pudo validar o cargar');
|
||||
expect(f.nativeElement.textContent).not.toMatch(/private|4821|pac_id/);
|
||||
expect(f.nativeElement.textContent).toContain('Recomendaciones no disponibles');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of } from 'rxjs';
|
||||
import { PacienteRiesgoEstado } from './paciente-riesgo.models';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { riesgoPacienteResponse } from './paciente-riesgo.validation';
|
||||
|
||||
@Injectable()
|
||||
export class PacienteRiesgoState {
|
||||
private readonly provider = inject(PACIENTE_RIESGO_PROVIDER);
|
||||
readonly estado = toSignal(defer(() => this.provider.obtener()).pipe(
|
||||
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
|
||||
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
|
||||
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
|
||||
), { initialValue: { tipo: 'cargando' } as PacienteRiesgoEstado });
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
|
||||
/** TEST ONLY. Exact external contract example; never belongs to the selected patient. */
|
||||
export function riesgoCacuEjemplo(): RiesgoPacienteCacu {
|
||||
return {
|
||||
simulado: true,
|
||||
cohorte: {
|
||||
url: 'cacu/cohorte_vigilancia', version: '0.2.0', fecha_indice: '2023-04-15',
|
||||
tipo_censura: 'incidente', c: 0, l: 0.164, r: 0.548, pap_0: 'ASC-US', hpv_0: 'POSITIVO',
|
||||
},
|
||||
riesgo: {
|
||||
lote_id: 12, modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0',
|
||||
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final',
|
||||
horizontes: [
|
||||
{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12, estado: 'final' },
|
||||
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28, estado: 'final' },
|
||||
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44, estado: 'final' },
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { riesgoPacienteResponse, tieneIntervalo } from './paciente-riesgo.validation';
|
||||
import { TipoCensuraCacu } from './paciente-riesgo.models';
|
||||
|
||||
describe('RIESGO-CACU-02: frontera del contrato DEV', () => {
|
||||
it('conserva todos los campos del ejemplo externo y copia los objetos', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
const salida = riesgoPacienteResponse(entrada);
|
||||
expect(salida).toEqual(entrada);
|
||||
salida.riesgo!.horizontes[0].probabilidad = 0;
|
||||
salida.cohorte!.c = -999;
|
||||
expect(entrada).toEqual(riesgoCacuEjemplo());
|
||||
});
|
||||
|
||||
it('admite campos aditivos sin eliminarlos ni renombrarlos', () => {
|
||||
const entrada = { ...riesgoCacuEjemplo(), futuro: { estado: null } };
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
});
|
||||
|
||||
it.each(['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo', null])(
|
||||
'preserva tipo_censura %s sin inferir etiquetas clínicas', tipo => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.cohorte!.tipo_censura = tipo as TipoCensuraCacu | null;
|
||||
expect(riesgoPacienteResponse(entrada).cohorte!.tipo_censura).toBe(tipo);
|
||||
},
|
||||
);
|
||||
|
||||
it('preserva los nulos independientes y el sentinel basal del contrato', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.cohorte = { ...entrada.cohorte!, tipo_censura: null, c: -999, l: null, r: null, pap_0: null, hpv_0: null };
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
entrada.riesgo = null;
|
||||
entrada.cohorte.c = null;
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
entrada.cohorte = null;
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual({ simulado: true, cohorte: null, riesgo: null });
|
||||
});
|
||||
|
||||
it('no impone dependencia entre cohorte nullable y riesgo nullable', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.cohorte = null;
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
});
|
||||
|
||||
it.each([[], [2.5], [0, 0.5, 7, 12]])('acepta horizontes dinámicos/parciales/vacíos %j', (...anios: number[]) => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.riesgo!.horizontes = anios.map((horizonte_anios, i) => ({
|
||||
horizonte_anios, probabilidad: i % 2, estado: i % 2 ? 'preliminary' : 'final',
|
||||
}));
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{}, { ic_bajo: null, ic_alto: null }, { ic_bajo: 0, ic_alto: null },
|
||||
{ ic_bajo: null, ic_alto: 1 }, { ic_bajo: 0 }, { ic_alto: 1 },
|
||||
])('conserva IC incompletos sin generar límites: %j', limites => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.riesgo!.horizontes = [{ horizonte_anios: 2, probabilidad: 0.5, estado: 'preliminary', ...limites }];
|
||||
const salida = riesgoPacienteResponse(entrada);
|
||||
expect(salida).toEqual(entrada);
|
||||
expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(false);
|
||||
});
|
||||
|
||||
it.each([0, 1])('acepta probabilidad y límites extremos %s sin convertir el transporte a porcentaje', p => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.riesgo!.estado_lote = 'preliminary';
|
||||
entrada.riesgo!.horizontes = [{ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p, estado: 'preliminary' }];
|
||||
const salida = riesgoPacienteResponse(entrada);
|
||||
expect(salida).toEqual(entrada);
|
||||
expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(true);
|
||||
});
|
||||
|
||||
const invalidos: [string, (v: any) => void][] = [
|
||||
['no simulado', v => v.simulado = false],
|
||||
['simulado string', v => v.simulado = 'true'],
|
||||
['sin simulado', v => delete v.simulado],
|
||||
['sin cohorte', v => delete v.cohorte],
|
||||
['sin riesgo', v => delete v.riesgo],
|
||||
['cohorte lista', v => v.cohorte = []],
|
||||
['URL ajena', v => v.cohorte.url = 'otra'],
|
||||
['versión ausente', v => delete v.cohorte.version],
|
||||
['fecha inválida', v => v.cohorte.fecha_indice = '2026-02-30'],
|
||||
['enum PIMM desconocido', v => v.cohorte.tipo_censura = 'diagnostico'],
|
||||
['basal string', v => v.cohorte.c = '0'],
|
||||
['variable no finita', v => v.cohorte.l = Infinity],
|
||||
['variable omitida', v => delete v.cohorte.r],
|
||||
['pap no textual', v => v.cohorte.pap_0 = 5],
|
||||
['hpv no textual', v => v.cohorte.hpv_0 = false],
|
||||
['lote fraccionario', v => v.riesgo.lote_id = 1.5],
|
||||
['lote string', v => v.riesgo.lote_id = '12'],
|
||||
['modelo omitido', v => delete v.riesgo.modelo_nombre],
|
||||
['versión no textual', v => v.riesgo.modelo_version = 2],
|
||||
['evaluación fecha imposible', v => v.riesgo.evaluado_en = '2026-02-30T00:00:00Z'],
|
||||
['evaluación sin UTC', v => v.riesgo.evaluado_en = '2026-10-01T00:00:00-06:00'],
|
||||
['hora inválida', v => v.riesgo.evaluado_en = '2026-10-01T25:00:00Z'],
|
||||
['estado lote desconocido', v => v.riesgo.estado_lote = 'confirmado'],
|
||||
['sin horizontes', v => delete v.riesgo.horizontes],
|
||||
['horizontes nulos', v => v.riesgo.horizontes = null],
|
||||
['horizonte nulo', v => v.riesgo.horizontes[0] = null],
|
||||
['horizonte string', v => v.riesgo.horizontes[0].horizonte_anios = '1'],
|
||||
['horizonte no finito', v => v.riesgo.horizontes[0].horizonte_anios = NaN],
|
||||
['horizontes desordenados', v => v.riesgo.horizontes.reverse()],
|
||||
['horizontes repetidos', v => v.riesgo.horizontes[1].horizonte_anios = 1],
|
||||
['probabilidad negativa', v => v.riesgo.horizontes[0].probabilidad = -0.01],
|
||||
['probabilidad mayor a uno', v => v.riesgo.horizontes[0].probabilidad = 1.01],
|
||||
['probabilidad string', v => v.riesgo.horizontes[0].probabilidad = '0.08'],
|
||||
['probabilidad nula', v => v.riesgo.horizontes[0].probabilidad = null],
|
||||
['probabilidad no finita', v => v.riesgo.horizontes[0].probabilidad = NaN],
|
||||
['estado horizonte inválido', v => v.riesgo.horizontes[0].estado = 'FINAL'],
|
||||
['IC bajo inválido', v => v.riesgo.horizontes[0].ic_bajo = -0.01],
|
||||
['IC alto inválido', v => v.riesgo.horizontes[0].ic_alto = 1.01],
|
||||
['IC string', v => v.riesgo.horizontes[0].ic_alto = '0.12'],
|
||||
['IC invertido', v => Object.assign(v.riesgo.horizontes[0], { ic_bajo: 0.12, ic_alto: 0.05 })],
|
||||
['IC fuera de probabilidad', v => v.riesgo.horizontes[0].ic_alto = 0.07],
|
||||
];
|
||||
it.each(invalidos)('rechaza %s sin coerción ni datos parciales', (_, mutar) => {
|
||||
const entrada = riesgoCacuEjemplo(); mutar(entrada);
|
||||
expect(() => riesgoPacienteResponse(entrada)).toThrow('Respuesta de riesgo individual DEV inválida');
|
||||
});
|
||||
it.each([null, undefined, [], 0, 'respuesta'])('rechaza cuerpo inválido %j', entrada => {
|
||||
expect(() => riesgoPacienteResponse(entrada)).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { isoDate } from '../cacu-seguimiento.models';
|
||||
import { HorizonteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
const nullableNumber = (v: unknown) => v === null || finite(v);
|
||||
const nullableText = (v: unknown) => v === null || typeof v === 'string';
|
||||
const text = (v: unknown) => typeof v === 'string';
|
||||
const estado = (v: unknown) => v === 'preliminary' || v === 'final';
|
||||
const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1;
|
||||
const censuras = ['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo'];
|
||||
|
||||
function utcTimestamp(v: unknown) {
|
||||
return typeof v === 'string'
|
||||
&& /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|\+00:00)$/.test(v)
|
||||
&& isoDate(v.slice(0, 10)) && Number.isFinite(Date.parse(v));
|
||||
}
|
||||
|
||||
function cohorteValida(v: unknown) {
|
||||
return v === null || record(v)
|
||||
&& v['url'] === 'cacu/cohorte_vigilancia' && text(v['version']) && isoDate(v['fecha_indice'])
|
||||
&& (v['tipo_censura'] === null || censuras.includes(v['tipo_censura'] as string))
|
||||
&& nullableNumber(v['c']) && nullableNumber(v['l']) && nullableNumber(v['r'])
|
||||
&& nullableText(v['pap_0']) && nullableText(v['hpv_0']);
|
||||
}
|
||||
|
||||
function horizonteValido(v: unknown) {
|
||||
if (!record(v) || !finite(v['horizonte_anios']) || !probability(v['probabilidad']) || !estado(v['estado'])) return false;
|
||||
for (const key of ['ic_bajo', 'ic_alto']) {
|
||||
if (Object.hasOwn(v, key) && v[key] !== null && !probability(v[key])) return false;
|
||||
}
|
||||
// Missing/null endpoints are preserved. A complete interval must contain the probability.
|
||||
return !(probability(v['ic_bajo']) && probability(v['ic_alto']))
|
||||
|| v['ic_bajo'] <= v['probabilidad'] && v['probabilidad'] <= v['ic_alto'];
|
||||
}
|
||||
|
||||
function riesgoValido(v: unknown) {
|
||||
if (v === null) return true;
|
||||
if (!record(v) || !Number.isSafeInteger(v['lote_id']) || !text(v['modelo_nombre']) || !text(v['modelo_version'])
|
||||
|| !utcTimestamp(v['evaluado_en']) || !estado(v['estado_lote']) || !Array.isArray(v['horizontes'])) return false;
|
||||
const horizontes = v['horizontes'];
|
||||
return horizontes.every(horizonteValido)
|
||||
&& horizontes.every((h, i) => i === 0 || horizontes[i - 1]['horizonte_anios'] < h['horizonte_anios']);
|
||||
}
|
||||
|
||||
/** Validate at the boundary. Reject real data, coercions and malformed fields; retain additive fields. */
|
||||
export function riesgoPacienteResponse(v: unknown): RiesgoPacienteCacu {
|
||||
if (!record(v) || v['simulado'] !== true || !cohorteValida(v['cohorte']) || !riesgoValido(v['riesgo'])) {
|
||||
throw new Error('Respuesta de riesgo individual DEV inválida');
|
||||
}
|
||||
return structuredClone(v) as unknown as RiesgoPacienteCacu;
|
||||
}
|
||||
|
||||
/** Presentation helper: an incomplete interval must never become a fabricated range. */
|
||||
export function tieneIntervalo(h: HorizonteRiesgoCacu): boolean {
|
||||
return probability(h.ic_bajo) && probability(h.ic_alto)
|
||||
&& h.ic_bajo <= h.probabilidad && h.probabilidad <= h.ic_alto;
|
||||
}
|
||||
@@ -26,6 +26,27 @@ describe('PlotlyChart lifecycle', () => {
|
||||
fixture.destroy(); expect(disconnect).toHaveBeenCalled(); expect(mocks.purge).toHaveBeenCalled();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
it.each([[false, true], [true, false]])('animated respeta prefers-reduced-motion=%s (transición: %s) y es opcional', async (reduce, transition) => {
|
||||
vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({ matches: reduce }));
|
||||
const settle = async () => { await fixture.whenStable(); for (let i = 0; i < 40; i++) await Promise.resolve(); };
|
||||
const fixture = TestBed.createComponent(PlotlyChart);
|
||||
fixture.componentRef.setInput('animated', true);
|
||||
fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [1] }], layout: {} });
|
||||
fixture.detectChanges(); await settle();
|
||||
fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [2] }], layout: {} });
|
||||
fixture.detectChanges(); await settle();
|
||||
expect(mocks.react).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.react.mock.calls[1][2]['transition'] !== undefined).toBe(transition);
|
||||
fixture.destroy(); vi.unstubAllGlobals();
|
||||
});
|
||||
it('sin animated las actualizaciones no llevan transición', async () => {
|
||||
const fixture = TestBed.createComponent(PlotlyChart);
|
||||
fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [1] }], layout: {} });
|
||||
fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 40; i++) await Promise.resolve();
|
||||
fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [2] }], layout: {} });
|
||||
fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 40; i++) await Promise.resolve();
|
||||
expect(mocks.react.mock.calls[1][2]['transition']).toBeUndefined(); fixture.destroy();
|
||||
});
|
||||
it('muestra error asíncrono y se recupera con reintento', async () => {
|
||||
mocks.react.mockRejectedValueOnce(new Error('render failed'));
|
||||
const fixture = TestBed.createComponent(PlotlyChart);
|
||||
|
||||
@@ -5,6 +5,10 @@ import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
|
||||
import { PlotlyController } from './plotly-controller';
|
||||
import { PLOTLY_LOADER } from './plotly-runtime';
|
||||
|
||||
function prefersReducedMotion(): boolean {
|
||||
return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-plotly-chart',
|
||||
imports: [MatButtonModule, MatProgressBarModule],
|
||||
@@ -27,6 +31,8 @@ import { PLOTLY_LOADER } from './plotly-runtime';
|
||||
export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
|
||||
@Input() showNotes = true;
|
||||
@Input() label = 'Figura estadística';
|
||||
// Opt-in: updates of the same visible figure move smoothly instead of redrawing.
|
||||
@Input() animated = false;
|
||||
@Input({ required: true }) figure!: PlotlyFigure;
|
||||
@ViewChild('host', { static: true }) host!: ElementRef<HTMLElement>;
|
||||
readonly renderError = output<void>();
|
||||
@@ -57,7 +63,7 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
|
||||
this.controller = new PlotlyController(this.host.nativeElement, this.loadPlotly, state => {
|
||||
this.status.set(state);
|
||||
if (state === 'error') this.renderError.emit();
|
||||
}, event => this.plotClick.emit(event));
|
||||
}, event => this.plotClick.emit(event), { animate: () => this.animated && !prefersReducedMotion() });
|
||||
if (typeof ResizeObserver !== 'undefined') {
|
||||
this.observer = new ResizeObserver(this.windowResize);
|
||||
this.observer.observe(this.host.nativeElement);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { syntheticFigures } from '../../features/indicadores/indicadores.synthetic-fixtures';
|
||||
import { vi } from 'vitest';
|
||||
import { PlotlyController } from './plotly-controller';
|
||||
import { cubicInOut, pieFrame, piesInterpolable, PlotlyController, TRANSITION_MS } from './plotly-controller';
|
||||
import { PlotlyRuntime } from './plotly-runtime';
|
||||
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
|
||||
function deferred() {
|
||||
@@ -151,6 +151,33 @@ describe('PlotlyController con Plotly instalado', () => {
|
||||
runtime = (module.default ?? module) as typeof runtime;
|
||||
} finally { canvas.mockRestore(); }
|
||||
});
|
||||
it('Plotly real acepta las transiciones de barras y los fotogramas de pies y termina en la figura destino', async () => {
|
||||
const host = document.createElement('div');
|
||||
document.body.append(host);
|
||||
let clock = 0, controller: PlotlyController | undefined;
|
||||
const ready = () => new Promise<void>((resolve, reject) => { pending = { resolve, reject }; });
|
||||
let pending!: { resolve: () => void; reject: (e: Error) => void };
|
||||
try {
|
||||
controller = new PlotlyController(host, () => Promise.resolve(runtime), state => {
|
||||
if (state === 'ready') pending?.resolve();
|
||||
if (state === 'error') pending?.reject(new Error('Plotly transition failed'));
|
||||
}, undefined, { animate: () => true, nextFrame: () => Promise.resolve(clock += 150) });
|
||||
const bars = (x: number[]): PlotlyFigure => ({ data: x.map((v, i) => ({ type: 'bar', uid: 'c' + i, orientation: 'h', x: [v], y: ['A'] })), layout: { barmode: 'stack' } });
|
||||
let done = ready(); controller.setFigure(bars([40, 60])); await done;
|
||||
done = ready(); controller.setFigure(bars([0, 60])); await done;
|
||||
expect((host as unknown as { data: { x: number[] }[] }).data.map(t => t.x)).toEqual([[0], [60]]);
|
||||
controller.destroy(); controller = undefined;
|
||||
const pies = (values: number[]): PlotlyFigure => ({ data: [{ type: 'pie', name: 'grupos', values, marker: { colors: ['rgba(1,2,3,1)', 'rgba(4,5,6,1)'] } }], layout: {} });
|
||||
controller = new PlotlyController(host, () => Promise.resolve(runtime), state => {
|
||||
if (state === 'ready') pending?.resolve();
|
||||
if (state === 'error') pending?.reject(new Error('Plotly pie frames failed'));
|
||||
}, undefined, { animate: () => true, nextFrame: () => Promise.resolve(clock += 150) });
|
||||
done = ready(); controller.setFigure(pies([10, 0])); await done;
|
||||
done = ready(); controller.setFigure(pies([3, 7])); await done;
|
||||
expect((host as unknown as { data: { values: number[] }[] }).data[0].values).toEqual([3, 7]);
|
||||
expect(host.style.visibility).toBe('visible');
|
||||
} finally { controller?.destroy(); host.remove(); }
|
||||
});
|
||||
it('usa propiedades admitidas por el esquema de Plotly 4.1.2', () => {
|
||||
expect(runtime.version).toBe('4.1.2');
|
||||
const config = runtime.PlotSchema.get().config;
|
||||
@@ -212,3 +239,183 @@ describe('PlotlyController con Plotly instalado', () => {
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('PlotlyController transiciones opcionales', () => {
|
||||
const pie = (values: number[], alpha = 1): PlotlyFigure => ({ data: [
|
||||
{ type: 'pie', name: 'centro', values: [1], text: ['Total'] },
|
||||
{ type: 'pie', name: 'grupos', values, text: values.map(String), marker: { colors: values.map(() => `rgba(10,20,30,${alpha})`) } },
|
||||
], layout: { height: 440 } });
|
||||
const bars = (x: number[]): PlotlyFigure => ({ data: x.map((v, i) => ({ type: 'bar', uid: 'c' + i, x: [v], y: ['A'] })), layout: {} });
|
||||
let host: HTMLElement, plotly: PlotlyRuntime, clock: number, animate: boolean;
|
||||
let state: ReturnType<typeof vi.fn<(state: 'loading' | 'ready' | 'error') => void>>;
|
||||
const nextFrame = () => Promise.resolve(clock += 100);
|
||||
beforeEach(() => {
|
||||
host = document.createElement('div'); clock = 0; animate = true;
|
||||
plotly = { react: vi.fn().mockResolvedValue(undefined), purge: vi.fn(), Plots: { resize: vi.fn().mockResolvedValue(undefined) },
|
||||
addFrames: vi.fn().mockResolvedValue(undefined), deleteFrames: vi.fn().mockResolvedValue(undefined) };
|
||||
state = vi.fn();
|
||||
});
|
||||
const controller = () => new PlotlyController(host, () => Promise.resolve(plotly), state, undefined, { animate: () => animate, nextFrame });
|
||||
async function settleLong() { for (let i = 0; i < 80; i++) await Promise.resolve(); }
|
||||
|
||||
it('easing cubic-in-out y fotogramas intermedios de pies: valores y alfa se mueven, textos esperan', () => {
|
||||
expect([0, .5, 1].map(cubicInOut)).toEqual([0, .5, 1]);
|
||||
expect(cubicInOut(.25)).toBeLessThan(.25); expect(cubicInOut(.75)).toBeGreaterThan(.75);
|
||||
const from = pie([10, 0], .3), to = pie([4, 6], 1);
|
||||
expect(piesInterpolable(from, to)).toBe(true);
|
||||
expect(piesInterpolable(from, bars([1]))).toBe(false);
|
||||
expect(piesInterpolable(from, { ...to, data: [to.data[0]] })).toBe(false);
|
||||
const half = pieFrame(from, to, .5);
|
||||
expect(half.data[0]['values']).toEqual([1]);
|
||||
expect(half.data[0]['text']).toEqual(['']);
|
||||
expect(half.data[1]['values']).toEqual([7, 3]); expect(half.data[1]['text']).toEqual(['', '']);
|
||||
expect((half.data[1]['marker'] as { colors: string[] }).colors).toEqual(['rgba(10,20,30,0.65)', 'rgba(10,20,30,0.65)']);
|
||||
expect(to.data[1]['values']).toEqual([4, 6]);
|
||||
for (const trace of half.data) {
|
||||
expect(trace['textinfo']).toBe('none'); expect(trace['hoverinfo']).toBe('skip');
|
||||
expect(trace['hovertemplate']).toBeNull(); expect(trace['customdata']).toEqual([]);
|
||||
}
|
||||
// Same values, only dimming (a selection that keeps the totals): colors move, texts stay.
|
||||
const dimmed = pieFrame(pie([4, 6], .3), pie([4, 6], 1), .5);
|
||||
expect(dimmed.data[1]['values']).toEqual([4, 6]); expect(dimmed.data[1]['text']).toEqual(['4', '6']);
|
||||
expect((dimmed.data[1]['marker'] as { colors: string[] }).colors).toEqual(['rgba(10,20,30,0.65)', 'rgba(10,20,30,0.65)']);
|
||||
expect(pieFrame(pie([4, 6]), pie([4, 6]), .5).data[1]).toEqual(pie([4, 6]).data[1]);
|
||||
});
|
||||
it('la dona interpola en varios react sin ocultar el host ni pasar por carga, y termina en la figura exacta', async () => {
|
||||
const c = controller();
|
||||
c.setFigure(pie([10, 0])); await settleLong();
|
||||
expect(host.style.visibility).toBe('visible'); state.mockClear(); vi.mocked(plotly.react).mockClear();
|
||||
const target = pie([4, 6]);
|
||||
c.setFigure(target);
|
||||
expect(host.style.visibility).toBe('visible'); expect(state).not.toHaveBeenCalledWith('loading');
|
||||
await settleLong();
|
||||
const calls = vi.mocked(plotly.react).mock.calls;
|
||||
// 100 ms per frame over TRANSITION_MS, plus the exact final figure.
|
||||
expect(calls.length).toBe(Math.ceil(TRANSITION_MS / 100));
|
||||
const values = calls.map(call => call[1][1]['values'] as number[]);
|
||||
expect(values[0][0]).toBeLessThan(10); expect(values[0][0]).toBeGreaterThan(4);
|
||||
for (let i = 1; i < values.length - 1; i++) expect(values[i][0]).toBeLessThan(values[i - 1][0]);
|
||||
expect(calls.at(-1)![1]).toEqual(target.data); expect(calls.at(-1)![2]).toEqual(target.layout);
|
||||
expect(state).toHaveBeenLastCalledWith('ready'); expect(host.style.visibility).toBe('visible');
|
||||
});
|
||||
it('las barras usan layout.transition de 450 ms cubic-in-out en un solo react', async () => {
|
||||
const c = controller();
|
||||
c.setFigure(bars([1, 2])); await settleLong();
|
||||
expect(vi.mocked(plotly.react).mock.calls[0][2]['transition']).toBeUndefined();
|
||||
c.setFigure(bars([3, 0])); await settleLong();
|
||||
expect(plotly.react).toHaveBeenCalledTimes(2);
|
||||
expect(vi.mocked(plotly.react).mock.calls[1][2]['transition']).toEqual({ duration: TRANSITION_MS, easing: 'cubic-in-out' });
|
||||
});
|
||||
it('sin animación (opción desactivada o movimiento reducido) conserva el renderizado oculto original', async () => {
|
||||
animate = false;
|
||||
const c = controller();
|
||||
c.setFigure(pie([10, 0])); await settleLong(); state.mockClear();
|
||||
c.setFigure(pie([4, 6]));
|
||||
expect(host.style.visibility).toBe('hidden'); expect(state).toHaveBeenCalledWith('loading');
|
||||
await settleLong();
|
||||
expect(plotly.react).toHaveBeenCalledTimes(2);
|
||||
expect(vi.mocked(plotly.react).mock.calls[1][2]['transition']).toBeUndefined();
|
||||
});
|
||||
it('una selección nueva interrumpe la animación y parte del último fotograma dibujado', async () => {
|
||||
const c = controller();
|
||||
c.setFigure(pie([10, 0])); await settleLong(); vi.mocked(plotly.react).mockClear();
|
||||
c.setFigure(pie([0, 10]));
|
||||
for (let i = 0; i < 6; i++) await Promise.resolve();
|
||||
c.setFigure(pie([10, 0]));
|
||||
await settleLong();
|
||||
const last = vi.mocked(plotly.react).mock.calls.at(-1)!;
|
||||
expect(last[1][1]['values']).toEqual([10, 0]);
|
||||
expect(state).toHaveBeenLastCalledWith('ready');
|
||||
});
|
||||
|
||||
it('no interpola pies con nulos, otra identidad u orden de categorías', () => {
|
||||
const source = pie([10, 0]);
|
||||
const changed = pie([5, 5]); changed.data[1]['values'] = [null, 5];
|
||||
expect(piesInterpolable(source, changed)).toBe(false);
|
||||
changed.data[1]['values'] = [5, 5]; changed.data[1]['name'] = 'otro';
|
||||
expect(piesInterpolable(source, changed)).toBe(false);
|
||||
source.data[1]['labels'] = ['A', 'B'];
|
||||
const reordered = pie([5, 5]); reordered.data[1]['labels'] = ['B', 'A'];
|
||||
expect(piesInterpolable(source, reordered)).toBe(false);
|
||||
});
|
||||
it('ningún cuadro geométrico expone conteos, plantillas, tooltips ni el total destino adelantado', async () => {
|
||||
const source = pie([10, 0]), target = pie([4, 6]);
|
||||
target.data.forEach(trace => Object.assign(trace, { customdata: [[4, 40], [6, 60]],
|
||||
hovertemplate: '%{value} / %{customdata[0]}', hovertext: ['4', '6'], texttemplate: '%{value}' }));
|
||||
const original = structuredClone(target), c = controller();
|
||||
c.setFigure(source); await settleLong(); vi.mocked(plotly.react).mockClear();
|
||||
c.setFigure(target); await settleLong();
|
||||
const calls = vi.mocked(plotly.react).mock.calls;
|
||||
for (const call of calls.slice(0, -1)) for (const trace of call[1]) {
|
||||
expect(trace['hoverinfo']).toBe('skip'); expect(trace['hovertemplate']).toBeNull();
|
||||
expect(trace['customdata']).toEqual([]); expect(trace['hovertext']).toEqual([]);
|
||||
expect(trace['texttemplate']).toBe(''); expect(trace['textinfo']).toBe('none');
|
||||
expect((trace['text'] as string[]).every(text => text === '')).toBe(true);
|
||||
}
|
||||
expect(calls.at(-1)![1]).toEqual(target.data); expect(target).toEqual(original); c.destroy();
|
||||
});
|
||||
it('interrumpe tras un react pendiente y usa el último cuadro completado sin renders concurrentes', async () => {
|
||||
const frames: ((time: number) => void)[] = [];
|
||||
const c = new PlotlyController(host, () => Promise.resolve(plotly), state, undefined,
|
||||
{ animate: () => true, nextFrame: () => new Promise(resolve => frames.push(resolve)) });
|
||||
const step = async (time: number) => { expect(frames.length).toBeGreaterThan(0); frames.shift()!(time); await settleLong(); };
|
||||
c.setFigure(pie([10, 0])); await settleLong(); state.mockClear(); vi.mocked(plotly.react).mockClear();
|
||||
const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise);
|
||||
c.setFigure(pie([0, 10])); await settleLong(); await step(0); await step(150);
|
||||
const drawn = vi.mocked(plotly.react).mock.calls[0][1][1]['values'] as number[];
|
||||
c.setFigure(pie([8, 2])); c.resize(); await settleLong();
|
||||
expect(plotly.react).toHaveBeenCalledTimes(1); expect(plotly.Plots.resize).not.toHaveBeenCalled();
|
||||
pending.resolve(); await settleLong();
|
||||
await step(200); // Discard stale frame; start the latest transition.
|
||||
await step(250); await step(400);
|
||||
const resumed = vi.mocked(plotly.react).mock.calls[1][1][1]['values'] as number[];
|
||||
expect(resumed[0]).toBeCloseTo(drawn[0] + (8 - drawn[0]) * cubicInOut(150 / TRANSITION_MS));
|
||||
await step(700);
|
||||
expect(vi.mocked(plotly.react).mock.calls.at(-1)![1]).toEqual(pie([8, 2]).data);
|
||||
expect(state.mock.calls).toEqual([['ready']]); expect(plotly.Plots.resize).toHaveBeenCalledTimes(1); c.destroy();
|
||||
});
|
||||
it('movimiento reducido durante la dona termina inmediatamente con datos exactos', async () => {
|
||||
const frames: ((time: number) => void)[] = [];
|
||||
const c = new PlotlyController(host, () => Promise.resolve(plotly), state, undefined,
|
||||
{ animate: () => animate, nextFrame: () => new Promise(resolve => frames.push(resolve)) });
|
||||
c.setFigure(pie([10, 0])); await settleLong(); vi.mocked(plotly.react).mockClear();
|
||||
const target = pie([4, 6]); c.setFigure(target); await settleLong();
|
||||
frames.shift()!(0); await settleLong(); animate = false;
|
||||
frames.shift()!(150); await settleLong();
|
||||
expect(plotly.react).toHaveBeenCalledTimes(1); expect(vi.mocked(plotly.react).mock.calls[0][1]).toEqual(target.data);
|
||||
expect(state).toHaveBeenLastCalledWith('ready'); c.destroy();
|
||||
});
|
||||
it('destruir mientras espera un fotograma no vuelve a dibujar ni a emitir ready', async () => {
|
||||
let frame!: (time: number) => void;
|
||||
const c = new PlotlyController(host, () => Promise.resolve(plotly), state, undefined,
|
||||
{ animate: () => true, nextFrame: () => new Promise(resolve => frame = resolve) });
|
||||
c.setFigure(pie([10, 0])); await settleLong(); state.mockClear(); vi.mocked(plotly.react).mockClear();
|
||||
c.setFigure(pie([0, 10])); await settleLong(); c.destroy(); frame(0); await settleLong(); frame(100); await settleLong();
|
||||
expect(plotly.react).not.toHaveBeenCalled(); expect(state).not.toHaveBeenCalled();
|
||||
expect(host.style.visibility).toBe('hidden');
|
||||
});
|
||||
it.each(['uid', 'escenario', 'nulo', 'trazas'])('barras con cambio de %s se redibujan exactamente sin interpolación', async kind => {
|
||||
const c = controller(), target = bars([3, 4]);
|
||||
c.setFigure(bars([1, 2])); await settleLong();
|
||||
if (kind === 'uid') target.data[0]['uid'] = 'otro';
|
||||
if (kind === 'escenario') target.data[0]['y'] = ['Otro'];
|
||||
if (kind === 'nulo') target.data[0]['x'] = [null];
|
||||
if (kind === 'trazas') target.data.pop();
|
||||
state.mockClear(); c.setFigure(target);
|
||||
expect(host.style.visibility).toBe('hidden'); expect(state).toHaveBeenCalledWith('loading');
|
||||
await settleLong();
|
||||
expect(vi.mocked(plotly.react).mock.calls[1][2]['transition']).toBeUndefined();
|
||||
expect(vi.mocked(plotly.react).mock.calls[1][1]).toEqual(target.data); c.destroy();
|
||||
});
|
||||
it('barras rápidas se serializan, descartan destinos intermedios y nunca anuncian ready obsoleto', async () => {
|
||||
const c = controller(); c.setFigure(bars([1, 2])); await settleLong(); state.mockClear();
|
||||
const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise);
|
||||
c.setFigure(bars([0, 2])); await settleLong();
|
||||
c.setFigure(bars([3, 0])); c.setFigure(bars([4, 5])); await settleLong();
|
||||
expect(plotly.react).toHaveBeenCalledTimes(2); expect(state).not.toHaveBeenCalled();
|
||||
pending.resolve(); await settleLong();
|
||||
expect(plotly.react).toHaveBeenCalledTimes(3);
|
||||
expect(vi.mocked(plotly.react).mock.calls.at(-1)![1]).toEqual(bars([4, 5]).data);
|
||||
expect(state.mock.calls).toEqual([['ready']]); expect(host.style.visibility).toBe('visible'); c.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,75 @@ interface EventHost extends HTMLElement {
|
||||
removeListener?: (name: string, listener: (event: unknown) => void) => void;
|
||||
}
|
||||
|
||||
export const TRANSITION_MS = 450;
|
||||
export interface PlotlyControllerOptions {
|
||||
// Evaluated per update: animate only an update of an already visible figure.
|
||||
animate?: () => boolean;
|
||||
// Resolves on the next animation frame with its timestamp (injectable for tests).
|
||||
nextFrame?: () => Promise<number>;
|
||||
}
|
||||
const nextAnimationFrame = () => new Promise<number>(resolve => requestAnimationFrame(resolve));
|
||||
// Plotly's 'cubic-in-out', reproduced for the interpolated pie frames.
|
||||
export function cubicInOut(t: number): number {
|
||||
return t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
|
||||
}
|
||||
const RGBA = /^rgba\((\d+),(\d+),(\d+),([\d.]+)\)$/;
|
||||
function mixColor(from: unknown, to: unknown, t: number): unknown {
|
||||
const a = typeof from === 'string' ? RGBA.exec(from.replace(/\s/g, '')) : null;
|
||||
const b = typeof to === 'string' ? RGBA.exec(to.replace(/\s/g, '')) : null;
|
||||
if (!a || !b) return to;
|
||||
const v = [1, 2, 3, 4].map(i => Number(a[i]) + (Number(b[i]) - Number(a[i])) * t);
|
||||
return `rgba(${v.slice(0, 3).map(Math.round).join(',')},${+v[3].toFixed(3)})`;
|
||||
}
|
||||
const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(n => typeof n === 'number' && Number.isFinite(n));
|
||||
/** Pies cannot use layout.transition: both figures must have the same pies and value shapes. */
|
||||
export function piesInterpolable(from: PlotlyFigure, to: PlotlyFigure): boolean {
|
||||
return to.data.length > 0 && from.data.length === to.data.length && to.data.every((trace, i) => {
|
||||
const old = from.data[i];
|
||||
return trace['type'] === 'pie' && old['type'] === 'pie' && trace['name'] === old['name']
|
||||
&& JSON.stringify(trace['labels']) === JSON.stringify(old['labels'])
|
||||
&& numbers(trace['values']) && numbers(old['values']) && trace['values'].length === old['values'].length;
|
||||
});
|
||||
}
|
||||
/** One intermediate pie frame: values and rgba colors move, texts wait for the final frame. */
|
||||
export function pieFrame(from: PlotlyFigure, to: PlotlyFigure, t: number): PlotlyFigure {
|
||||
const moving = to.data.some((trace, i) => (trace['values'] as number[])
|
||||
.some((v, j) => v !== (from.data[i]['values'] as number[])[j]));
|
||||
return { ...to, data: to.data.map((trace, i) => {
|
||||
const a = from.data[i]['values'] as number[], b = trace['values'] as number[];
|
||||
const oldMarker = from.data[i]['marker'] as Record<string, unknown> | undefined;
|
||||
const marker = trace['marker'] as Record<string, unknown> | undefined;
|
||||
const oldColors = oldMarker?.['colors'], colors = marker?.['colors'];
|
||||
const sameValues = a.every((v, j) => v === b[j]);
|
||||
const mixColors = !!marker && Array.isArray(colors) && Array.isArray(oldColors) && oldColors.length === colors.length
|
||||
&& colors.some((c, j) => c !== oldColors[j]);
|
||||
if (sameValues && !mixColors && !moving) return trace;
|
||||
// Geometry is illustrative until the exact target render. Hide all clinical
|
||||
// readouts (including the centre) and never attach counts to moving slices.
|
||||
return { ...trace, ...(sameValues ? {} : { values: b.map((v, j) => a[j] + (v - a[j]) * t) }),
|
||||
...(moving ? { text: b.map(() => ''), textinfo: 'none', texttemplate: '',
|
||||
hoverinfo: 'skip', hovertemplate: null, hovertext: [], customdata: [] } : {}),
|
||||
...(mixColors ? { marker: { ...marker, colors: (colors as unknown[]).map((c, j) => mixColor((oldColors as unknown[])[j], c, t)) } } : {}) };
|
||||
}) };
|
||||
}
|
||||
const transitionable = (figure: PlotlyFigure) => figure.data.length > 0
|
||||
&& figure.data.every(trace => ['bar', 'scatter'].includes(String(trace['type'] ?? 'scatter')));
|
||||
// A changed catalogue, scenario axis or availability mask is an exact redraw.
|
||||
// In particular, never tween a published value into an unavailable/suppressed one.
|
||||
function cartesianInterpolable(from: PlotlyFigure, to: PlotlyFigure): boolean {
|
||||
return transitionable(from) && transitionable(to) && from.data.length === to.data.length
|
||||
&& to.data.every((trace, i) => {
|
||||
const old = from.data[i];
|
||||
if (trace['type'] !== old['type'] || trace['uid'] !== old['uid']) return false;
|
||||
return ['x', 'y'].every(axis => {
|
||||
const a = old[axis], b = trace[axis];
|
||||
if (!Array.isArray(a) || !Array.isArray(b)) return a === b;
|
||||
return a.length === b.length && b.every((v, j) =>
|
||||
typeof v === 'number' && typeof a[j] === 'number' ? true : v === a[j]);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// One serialized queue owns the host. A completed stale operation cannot expose
|
||||
// its graph or overwrite a newer react operation. Resize uses the same queue.
|
||||
export class PlotlyController {
|
||||
@@ -18,17 +87,28 @@ export class PlotlyController {
|
||||
private plotly?: PlotlyRuntime;
|
||||
private frameCount = 0;
|
||||
private listenerAttached = false;
|
||||
// Last figure drawn on the host (target or intermediate frame); origin of the next transition.
|
||||
private shown?: PlotlyFigure;
|
||||
private animating = false;
|
||||
private readonly handleClick = (event: unknown) => {
|
||||
if (!this.destroyed && !this.busy && this.rendered === this.version) this.click?.(event);
|
||||
};
|
||||
constructor(private host: HTMLElement, private load: () => Promise<PlotlyRuntime>,
|
||||
private state: (state: 'loading' | 'ready' | 'error') => void,
|
||||
private click?: (event: unknown) => void) {}
|
||||
private click?: (event: unknown) => void,
|
||||
private options: PlotlyControllerOptions = {}) {}
|
||||
private get config() { return { responsive: false, displaylogo: false, showSendToCloud: false, modeBarButtonsToRemove: ['sendChartToCloud'] }; }
|
||||
|
||||
setFigure(figure: PlotlyFigure) {
|
||||
if (this.destroyed) return;
|
||||
this.desired = figure;
|
||||
this.version++;
|
||||
// A visible figure that will animate stays on screen; hiding it is the flash
|
||||
// between selections. Every other update keeps the original hidden render.
|
||||
this.animating = this.rendered >= 0 && this.host.style.visibility === 'visible' && !!this.shown && !!this.options.animate?.()
|
||||
&& !this.shown.frames?.length && !figure.frames?.length
|
||||
&& (piesInterpolable(this.shown, figure) || cartesianInterpolable(this.shown, figure));
|
||||
if (this.animating) return void this.drain();
|
||||
this.host.style.visibility = 'hidden';
|
||||
this.state('loading');
|
||||
void this.drain();
|
||||
@@ -55,15 +135,33 @@ export class PlotlyController {
|
||||
try {
|
||||
if (this.rendered !== version && this.desired) {
|
||||
// Plotly may mutate inputs; clone the complete JSON without changing values.
|
||||
const figure = structuredClone(this.desired);
|
||||
const target = structuredClone(this.desired);
|
||||
const figure = structuredClone(target);
|
||||
if (this.frameCount) await this.plotly.deleteFrames(this.host, Array.from({ length: this.frameCount }, (_, i) => i));
|
||||
this.frameCount = 0;
|
||||
if (this.destroyed) break;
|
||||
await this.plotly.react(this.host, figure.data, figure.layout, {
|
||||
...figure.config, responsive: false, displaylogo: false,
|
||||
showSendToCloud: false,
|
||||
modeBarButtonsToRemove: ['sendChartToCloud'],
|
||||
});
|
||||
const animate = this.animating && !!this.options.animate?.() && !!this.shown
|
||||
&& !this.shown.frames?.length && !figure.frames?.length;
|
||||
const config = { ...figure.config, ...this.config };
|
||||
if (animate && piesInterpolable(this.shown!, figure)) {
|
||||
const from = this.shown!, nextFrame = this.options.nextFrame ?? nextAnimationFrame;
|
||||
const start = await nextFrame();
|
||||
for (;;) {
|
||||
const t = Math.min(1, ((await nextFrame()) - start) / TRANSITION_MS);
|
||||
if (this.destroyed || version !== this.version || !this.options.animate?.() || t >= 1) break;
|
||||
const frame = pieFrame(from, figure, cubicInOut(t));
|
||||
const copy = structuredClone(frame);
|
||||
await this.plotly.react(this.host, copy.data, copy.layout, config);
|
||||
this.shown = frame;
|
||||
}
|
||||
if (this.destroyed) break;
|
||||
if (version !== this.version) continue;
|
||||
}
|
||||
const layout = animate && this.shown && cartesianInterpolable(this.shown, figure)
|
||||
&& figure.layout['transition'] === undefined
|
||||
? { ...figure.layout, transition: { duration: TRANSITION_MS, easing: 'cubic-in-out' } } : figure.layout;
|
||||
await this.plotly.react(this.host, figure.data, layout, config);
|
||||
this.shown = target;
|
||||
if (!this.destroyed && !this.listenerAttached && this.click && (this.host as EventHost).on) {
|
||||
(this.host as EventHost).on!('plotly_click', this.handleClick);
|
||||
this.listenerAttached = true;
|
||||
@@ -88,6 +186,7 @@ export class PlotlyController {
|
||||
if (version !== this.version) continue;
|
||||
this.rendered = version;
|
||||
this.resizePending = false;
|
||||
this.shown = undefined;
|
||||
this.host.style.visibility = 'hidden';
|
||||
this.state('error');
|
||||
}
|
||||
|
||||
@@ -72,6 +72,22 @@ body {
|
||||
font-family: var(--issste-font-body);
|
||||
}
|
||||
|
||||
.dashboard .catalog-grid > app-indicador-catalog-card { scroll-margin-top: var(--issste-header-clearance, 6rem); }
|
||||
.dashboard .graphic-navigation-trigger {
|
||||
position: fixed;
|
||||
z-index: 90;
|
||||
inset-inline-start: max(.5rem, env(safe-area-inset-left));
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
color: var(--issste-text);
|
||||
background: var(--issste-accent);
|
||||
box-shadow: 0 2px 8px rgb(0 0 0 / 18%);
|
||||
}
|
||||
.dashboard .graphic-navigation-trigger:focus-visible { outline: 3px solid var(--issste-text); outline-offset: 3px; }
|
||||
.cdk-overlay-pane.indicator-navigation-overlay:has(.panel-closing) { pointer-events: none; }
|
||||
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
font-family: var(--issste-font-heading);
|
||||
font-weight: 700;
|
||||
|
||||
Reference in New Issue
Block a user