Gobernanza: TEA · EEG tab with cluster check, reference data, training, baselines, reports, promotion, run monitor, analysis and result

This commit is contained in:
ulises
2026-11-23 09:29:33 -06:00
parent 6ade415f63
commit 0b22b3c309
60 changed files with 4759 additions and 4 deletions
@@ -0,0 +1,23 @@
<div class="controls">
<button mat-stroked-button type="button" [disabled]="!active() || summary.isLoading() || indicators.isLoading()" (click)="refresh()">Actualizar</button>
<a mat-button routerLink="/indicadores/tea-estatus">Consultar resumen de pacientes TEA</a>
</div>
<h3>Resumen de EEGs</h3>
@if (summary.isLoading()) { <p role="status">Cargando resumen de EEGs…</p> }
@else if (summary.error()) { <p role="alert">No se pudo cargar el resumen de EEGs.</p> }
@if (summary.hasValue()) {
@let totals = summary.value();
@if (!totals.eegs) { <p>Todavía no hay EEGs registrados.</p> }
<dl class="cards">
@for (card of cards; track card.key) {
<div><dt>{{ card.label }}</dt><dd>{{ totals[card.key] }}</dd></div>
}
</dl>
}
<h3>Ciclo de indicadores TEA</h3>
@if (indicators.hasValue() && indicators.value(); as status) {
<p>{{ states[status.estado] }} · Pendiente: {{ status.pendiente ? 'Sí' : 'No' }}</p>
@if (status.error; as error) { <p role="alert">{{ error.mensaje }}</p> }
} @else if (indicators.isLoading()) { <p role="status">Consultando ciclo de indicadores…</p> }
@else if (!indicators.error()) { <p>Sin información del ciclo de indicadores.</p> }
@if (indicators.error()) { <p role="alert">No se pudo consultar el ciclo de indicadores.</p> }
@@ -0,0 +1,3 @@
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 9rem), 1fr)); gap: .5rem; }
.cards div { border: 1px solid var(--mat-sys-outline-variant); border-radius: .4rem; padding: .75rem; }
.cards dd { margin: .25rem 0 0; font-size: 1.4rem; font-weight: 600; font-variant-numeric: tabular-nums; }
@@ -0,0 +1,88 @@
/** Pins EEG totals and visible-step polling with HTTP fixtures and a fake clock. */
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { ResultStepComponent } from './result-step';
const summary = '/governance/tea/eeg/summary';
const indicators = '/reportes/indicadores';
describe('ResultStepComponent', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([])] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
/** Fails if totals disappear or status stops refreshing at five seconds or continues on a closed step. */
it('refreshes indicators while active and shows EEG and FHIR counts', async () => {
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
const hidden = vi.spyOn(document, 'hidden', 'get').mockReturnValue(false);
try {
const fixture = TestBed.createComponent(ResultStepComponent);
fixture.componentRef.setInput('active', true);
fixture.detectChanges();
http.expectOne(summary).flush({
eegs: 6, analysed: 5, valid: 3, not_valid: 1, failed: 1, metrics: 12,
metrics_with_z: 10, high: 2, low: 1, fhir_eegs: 5, fhir_metrics: 12,
});
http.expectOne(indicators).flush({ tea: { estado: 'en_curso', pendiente: true } });
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('dd')).toHaveLength(11);
expect(fixture.nativeElement.textContent).toContain('En curso · Pendiente: Sí');
vi.advanceTimersByTime(5000);
fixture.detectChanges();
http.expectOne(indicators).flush({ tea: { estado: 'ok', pendiente: false } });
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Actualizado · Pendiente: No');
hidden.mockReturnValue(true);
document.dispatchEvent(new Event('visibilitychange'));
fixture.detectChanges();
vi.advanceTimersByTime(5000);
http.expectNone(indicators);
hidden.mockReturnValue(false);
document.dispatchEvent(new Event('visibilitychange'));
fixture.detectChanges();
http.expectOne(indicators).flush({ tea: { estado: 'ok', pendiente: false } });
fixture.componentRef.setInput('active', false);
fixture.detectChanges();
vi.advanceTimersByTime(5000);
http.expectNone(indicators);
fixture.destroy();
} finally {
hidden.mockRestore();
vi.useRealTimers();
}
});
/** Fails if failures hide the refresh control or refreshing skips one of the two endpoints. */
it('shows load failures and lets both requests be retried', async () => {
const hidden = vi.spyOn(document, 'hidden', 'get').mockReturnValue(false);
try {
const fixture = TestBed.createComponent(ResultStepComponent);
fixture.componentRef.setInput('active', true);
fixture.detectChanges();
http.expectOne(summary).flush(null, { status: 500, statusText: 'Server Error' });
http.expectOne(indicators).flush(null, { status: 500, statusText: 'Server Error' });
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('[role=alert]')).toHaveLength(2);
fixture.nativeElement.querySelector('button').click();
fixture.detectChanges();
http.expectOne(summary).flush({ eegs: 0 });
http.expectOne(indicators).flush({ tea: { estado: 'sin_correr', pendiente: true } });
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Todavía no hay EEGs registrados.');
} finally {
hidden.mockRestore();
}
});
});
@@ -0,0 +1,64 @@
import { DOCUMENT } from '@angular/common';
import { Component, computed, inject, input, signal } from '@angular/core';
import { rxResource, takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { RouterLink } from '@angular/router';
import { EMPTY, fromEvent, map, switchMap, timer } from 'rxjs';
import { ReportsApi, RecomputeStatus } from '../../../reportes/reportes.api';
import { TeaEegApi } from '../../api/tea-eeg.api';
import { EegSummary } from '../../api/tea-eeg.types';
@Component({
selector: 'app-result-step',
imports: [MatButtonModule, RouterLink],
templateUrl: './result-step.html',
styleUrls: ['../eeg-step.scss', './result-step.scss'],
})
export class ResultStepComponent {
private readonly api = inject(TeaEegApi);
private readonly reports = inject(ReportsApi);
private readonly document = inject(DOCUMENT);
readonly active = input(false);
private readonly visible = signal(!this.document.hidden);
private readonly shown = computed(() => this.active() && this.visible());
private readonly refreshCount = signal(0);
readonly summary = rxResource({
params: () => this.active() ? this.refreshCount() : undefined,
stream: () => this.api.eegSummary(),
});
readonly indicators = rxResource({
params: () => this.shown() ? this.refreshCount() : undefined,
stream: () => this.reports.indicatorStatus().pipe(map((status) => status.tea ?? null)),
});
readonly states: Record<RecomputeStatus['estado'], string> = {
en_curso: 'En curso', ok: 'Actualizado', error: 'Error en el cálculo', sin_correr: 'Sin ejecutar',
};
readonly cards: { key: keyof EegSummary; label: string }[] = [
{ key: 'eegs', label: 'EEGs' },
{ key: 'analysed', label: 'Analizados' },
{ key: 'valid', label: 'Válidos' },
{ key: 'not_valid', label: 'No válidos' },
{ key: 'failed', label: 'Fallidos' },
{ key: 'metrics', label: 'Métricas' },
{ key: 'metrics_with_z', label: 'Con puntuación z' },
{ key: 'high', label: 'Altas' },
{ key: 'low', label: 'Bajas' },
{ key: 'fhir_eegs', label: 'Filas FHIR de EEGs' },
{ key: 'fhir_metrics', label: 'Filas FHIR de métricas' },
];
constructor() {
fromEvent(this.document, 'visibilitychange').pipe(takeUntilDestroyed()).subscribe(() => this.visible.set(!this.document.hidden));
toObservable(this.shown).pipe(
switchMap((shown) => shown ? timer(5000, 5000) : EMPTY),
takeUntilDestroyed(),
).subscribe(() => {
if (this.shown() && !this.indicators.isLoading()) this.indicators.reload();
});
}
refresh(): void {
if (this.summary.isLoading() || this.indicators.isLoading()) return;
this.refreshCount.update((count) => count + 1);
}
}