Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bd3f63b20a | |||
| 860c66ba5c | |||
| 5c8e2866ef | |||
| 29d021b347 | |||
| 98e9b60e83 | |||
| 5061350dd8 | |||
| eb887be447 | |||
| 0b22b3c309 | |||
| 6ade415f63 | |||
| 5791928976 | |||
| f4d1829cd3 | |||
| 069cc459a4 | |||
| 881c613744 |
@@ -14,3 +14,25 @@ npx ng build # compilación de producción en dist/WebApp
|
||||
`ng serve` envía las rutas de la API a WebApi en `localhost:5050`
|
||||
(`proxy.conf.json`). La imagen de Docker (`Dockerfile`) sirve la compilación con
|
||||
nginx (`nginx.conf`), que reenvía esas mismas rutas al servicio `webapi`.
|
||||
|
||||
## CaCu en Windows con la instalación del puerto 5210
|
||||
|
||||
En `feature/cacu-update`, desde la carpeta de WebApp:
|
||||
|
||||
```powershell
|
||||
npm ci
|
||||
npm run start:cacu
|
||||
```
|
||||
|
||||
Abre [Indicadores CaCu](http://127.0.0.1:4300/indicadores/cacu) e inicia sesión
|
||||
con la cuenta de CaCu de la aplicación. La sesión se valida en el navegador.
|
||||
Detén Angular con `Ctrl+C` en la misma terminal.
|
||||
|
||||
El lockfile de Angular admite Node.js `^22.22.3`, `^24.15.0` o `>=26.0.0`.
|
||||
`package.json` declara npm `11.17.0`. El arranque se probó con Node.js
|
||||
`26.13.0` y npm `11.20.0`.
|
||||
|
||||
`start:cacu` escucha en `127.0.0.1:4300`. El proxy de Angular reenvía
|
||||
solicitudes GET de CaCu a `http://10.0.10.41:5210`, incluida la lista
|
||||
`/cacu/seguimiento` y los recursos FHIR `Measure`, `MeasureReport` y
|
||||
`RiskAssessment`. La ruta `/indicadores/cacu` la sirve Angular.
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve",
|
||||
"start:cacu": "ng serve --host 127.0.0.1 --port 4300 --proxy-config proxy.cacu-readonly.cjs",
|
||||
"build": "ng build",
|
||||
"watch": "ng build --watch --configuration development",
|
||||
"test": "ng test"
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
// Keep the installed API read-only for local CaCu development.
|
||||
module.exports = {
|
||||
'^/(?:health|cacu/(?:seguimiento|fhir/(?:Measure|MeasureReport|RiskAssessment|metadata)))(?:\\?|$)': {
|
||||
target: 'http://10.0.10.41:5210',
|
||||
changeOrigin: true,
|
||||
bypass(request, response) {
|
||||
if (request.method === 'GET') return;
|
||||
if (!response) return false;
|
||||
response.writeHead(405, { Allow: 'GET' });
|
||||
response.end();
|
||||
return request.url;
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -78,6 +78,76 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
fixture.componentRef.setInput('active',false); fixture.detectChanges(); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
|
||||
expect(fixture.componentInstance.data?.paginacion.page).toBe(2);
|
||||
});
|
||||
it('busca parcialmente por identificador en la página, conserva la búsqueda al paginar y permite limpiarla', () => {
|
||||
const items = fixtureData.items.slice(0, 2).map((item, i) => ({ ...item, id_seudonimo: ['PRUEBA-Á42', 'PRUEBA-73'][i] }));
|
||||
const pagina = { ...fixtureData, items };
|
||||
open().flush(pagina);
|
||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} });
|
||||
fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const escribir = (texto: string) => {
|
||||
const input = root.querySelector<HTMLInputElement>('input[type="search"]')!;
|
||||
input.value = texto;
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
fixture.detectChanges();
|
||||
};
|
||||
escribir(' a42 ');
|
||||
expect(root.querySelectorAll('tr[data-paciente]')).toHaveLength(1);
|
||||
expect(root.querySelector('tr[data-paciente]')?.textContent).toContain('PRUEBA-Á42');
|
||||
expect(root.querySelector('#alcance-busqueda-cacu')?.textContent).toContain('1 de 2 registros de esta página');
|
||||
http.expectNone(() => true);
|
||||
|
||||
root.querySelectorAll<HTMLButtonElement>('nav button')[1].click();
|
||||
const siguiente = http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page') === '2');
|
||||
expect(siguiente.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']);
|
||||
siguiente.flush({ ...pagina, items: items.slice(1), paginacion: { ...pagina.paginacion, page: 2 } });
|
||||
fixture.detectChanges();
|
||||
expect(root.textContent).toContain('No hay coincidencias en esta página.');
|
||||
expect(root.querySelector<HTMLInputElement>('input[type="search"]')?.value).toBe(' a42 ');
|
||||
[...root.querySelectorAll('button')].find(button => button.textContent === 'Limpiar búsqueda')!.click();
|
||||
fixture.detectChanges();
|
||||
expect(root.querySelectorAll('tr[data-paciente]')).toHaveLength(1);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('muestra el grupo de edad y señala la ausencia de edad exacta y fecha de nacimiento', () => {
|
||||
respond();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const fila = root.querySelector<HTMLElement>('tr[data-paciente]')!;
|
||||
expect(root.querySelector('thead th:nth-child(2)')?.textContent).toBe('Edad');
|
||||
expect(fila.querySelector('td:nth-child(2)')?.textContent).toContain('No disponible');
|
||||
expect(root.querySelector('td small')?.textContent).toContain('Grupo de edad');
|
||||
fila.querySelector('button')!.click();
|
||||
fixture.detectChanges();
|
||||
const nacimiento = [...root.querySelectorAll('app-paciente-detalle dt')].find(dt => dt.textContent === 'Fecha de nacimiento');
|
||||
expect(nacimiento?.nextElementSibling?.textContent).toBe('No disponible');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it.each(['Excel', 'PDF'])('la exportación %s usa el contrato y los filtros aplicados de CaCu, incluso con la búsqueda de página activa', formato => {
|
||||
const pagina = {
|
||||
...fixtureData, filtros: { estatus: 'PRE_COLPOSCOPIA', orden: 'lieag', horizonte: 3 },
|
||||
paginacion: { ...fixtureData.paginacion, total_items: 201 },
|
||||
};
|
||||
open().flush(pagina);
|
||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} });
|
||||
fixture.componentInstance.busquedaCaCu = 'no coincide';
|
||||
fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector('tr[data-paciente]')).toBeNull();
|
||||
const botones = () => [...root.querySelectorAll<HTMLButtonElement>('app-seguimiento-exportar button')];
|
||||
botones().find(button => button.textContent!.includes(formato))!.click();
|
||||
const exportacion = http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page_size') === '200');
|
||||
expect(exportacion.request.params.get('estatus')).toBe('PRE_COLPOSCOPIA');
|
||||
expect(exportacion.request.params.get('orden')).toBe('lieag');
|
||||
expect(exportacion.request.params.get('horizonte')).toBe('3');
|
||||
expect(exportacion.request.params.get('corte')).toBe(pagina.corte);
|
||||
expect(exportacion.request.params.get('page')).toBe('1');
|
||||
const items = Array.from({ length: 200 }, (_, i) => ({ ...pagina.items[0], id_seudonimo: `PRUEBA-${i}` }));
|
||||
exportacion.flush({ ...pagina, items, paginacion: { page: 1, page_size: 200, total_items: 201, total_pages: 2 } });
|
||||
const siguiente = http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page') === '2');
|
||||
fixture.detectChanges();
|
||||
botones().find(button => button.textContent === 'Cancelar')!.click();
|
||||
expect(siguiente.cancelled).toBe(true);
|
||||
});
|
||||
it.each([404,400,0,503])('HTTP %s no introduce registros ficticios; reintento conserva consulta', code => {
|
||||
const req=open(); if(code===0) req.error(new ProgressEvent('error')); else req.flush({error:'private'}, {status:code,statusText:'Failure'});
|
||||
fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull(); expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { COLUMNAS_DE_PROBABILIDAD, ETIQUETA_PROBABILIDAD, latestStudy, ProbabilidadClave, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse } from '../cacu-seguimiento.models';
|
||||
import { ETIQUETA_IDENTIDAD, identidadDe } from '../paciente-identidad';
|
||||
import { SeguimientoTablaQuery, SeguimientoTablaResponse } from '../seguimiento-tabla.service';
|
||||
|
||||
const ORDEN_RECIENTE = { codigo: 'reciente', etiqueta: 'Estudio más reciente' };
|
||||
|
||||
export function consultaExportacionCaCu(q: SeguimientoTablaQuery): SeguimientoQuery {
|
||||
const { corte, meses, page, page_size, filtros } = q;
|
||||
if (meses === 0) throw new Error('Ventana de seguimiento CaCu inválida');
|
||||
const orden = filtros?.['orden'];
|
||||
return {
|
||||
corte, meses, page, page_size, estatus: filtros?.['estatus'],
|
||||
orden: orden === 'lieag' || orden === 'cancer' || orden === 'supervivencia' ? orden : 'reciente',
|
||||
horizonte: filtros?.['horizonte'] === undefined ? undefined : Number(filtros['horizonte']),
|
||||
};
|
||||
}
|
||||
|
||||
/** Adapts the validated CaCu list to the shared export table. */
|
||||
export function tablaExportacionCaCu(
|
||||
respuesta: SeguimientoResponse,
|
||||
citologia: (estudio: NonNullable<SeguimientoPaciente['ultima_citologia']>) => string,
|
||||
probabilidad: (item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte: number) => string | null,
|
||||
): SeguimientoTablaResponse {
|
||||
const identidad = (respuesta.items[0] && identidadDe(respuesta.items[0]))?.campo ?? 'id_seudonimo';
|
||||
const { estatus, orden, horizonte } = respuesta.filtros;
|
||||
const probabilidades = estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] ?? [] : [];
|
||||
const horizonteMostrado = horizonte ?? 5;
|
||||
return {
|
||||
simulado: true,
|
||||
corte: respuesta.corte,
|
||||
ventana: respuesta.ventana,
|
||||
paginacion: respuesta.paginacion,
|
||||
filtros: { estatus, orden: orden ?? 'reciente', horizonte: horizonte?.toString() ?? null },
|
||||
filtros_disponibles: [
|
||||
{ clave: 'estatus', etiqueta: 'Estatus de seguimiento', opciones: respuesta.estatus_disponibles },
|
||||
{ clave: 'orden', etiqueta: 'Orden', opciones: [ORDEN_RECIENTE, ...probabilidades.map(c => ({ codigo: c, etiqueta: ETIQUETA_PROBABILIDAD[c] }))] },
|
||||
{ clave: 'horizonte', etiqueta: 'Horizonte de la probabilidad', opciones: (respuesta.horizontes_disponibles ?? [0, 1, 3, 5])
|
||||
.map(h => ({ codigo: String(h), etiqueta: `${h} ${h === 1 ? 'año' : 'años'}` })) },
|
||||
],
|
||||
columnas: [
|
||||
{ clave: identidad, etiqueta: ETIQUETA_IDENTIDAD[identidad] },
|
||||
{ clave: 'grupo_edad', etiqueta: 'Grupo de edad' },
|
||||
{ clave: 'estatus', etiqueta: 'Estatus de seguimiento' },
|
||||
{ clave: 'citologia', etiqueta: 'Última citología', detalles: [{ clave: 'fecha_citologia', etiqueta: 'Fecha' }, { clave: 'calidad', etiqueta: 'Calidad' }] },
|
||||
{ clave: 'vph', etiqueta: 'Último resultado de VPH', detalles: [{ clave: 'fecha_vph', etiqueta: 'Fecha' }, { clave: 'genotipo', etiqueta: 'Genotipo 16/18' }] },
|
||||
{ clave: 'biopsia', etiqueta: 'Última biopsia', detalles: [{ clave: 'fecha_biopsia', etiqueta: 'Fecha' }] },
|
||||
...probabilidades.map(clave => ({ clave, etiqueta: `${ETIQUETA_PROBABILIDAD[clave]} a ${horizonteMostrado} años (%)` })),
|
||||
{ clave: 'reciente', etiqueta: 'Estudio más reciente' },
|
||||
{ clave: 'dias', etiqueta: 'Días de toma a diagnóstico' },
|
||||
{ clave: 'prioridad', etiqueta: 'Prioridad' },
|
||||
],
|
||||
items: respuesta.items.map(item => ({
|
||||
[identidad]: identidadDe(item)!.id,
|
||||
grupo_edad: item.grupo_edad === 'sin_dato' ? null : item.grupo_edad,
|
||||
estatus: item.estatus.etiqueta,
|
||||
citologia: item.ultima_citologia ? citologia(item.ultima_citologia) : null,
|
||||
fecha_citologia: item.ultima_citologia?.fecha ?? null,
|
||||
calidad: item.ultima_citologia?.calidad ?? null,
|
||||
vph: item.ultimo_vph?.resultado ?? null,
|
||||
fecha_vph: item.ultimo_vph?.fecha ?? null,
|
||||
genotipo: item.ultimo_vph?.genotipo_16_18 == null ? null : item.ultimo_vph.genotipo_16_18 ? 'Presente' : 'No detectado',
|
||||
biopsia: item.ultima_biopsia ? item.ultima_biopsia.grado ?? 'Sin grado' : null,
|
||||
fecha_biopsia: item.ultima_biopsia?.fecha ?? null,
|
||||
...Object.fromEntries(probabilidades.map(c => [c, probabilidad(item, c, horizonteMostrado)])),
|
||||
reciente: latestStudy(item),
|
||||
dias: item.dias_toma_diagnostico,
|
||||
prioridad: item.prioridad?.etiqueta ?? null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -4,7 +4,7 @@ const pad = (n: number) => String(n).padStart(2, '0');
|
||||
* Name of a downloaded file. It carries the report kind, the cut-off date and the moment it was made, and never a
|
||||
* patient identifier, because file names end up in download lists, backups and mail attachments.
|
||||
*/
|
||||
export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'seguimiento-cancer-de-mama-seleccion' | 'ficha-cancer-de-mama', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string {
|
||||
export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'seguimiento-cancer-de-mama-seleccion' | 'ficha-cancer-de-mama' | 'seguimiento-cancer-cervicouterino' | 'ficha-cancer-cervicouterino', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string {
|
||||
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;
|
||||
return `${kind}_corte-${corte.replace(/[^0-9-]/g, '')}_${stamp}.${extension}`;
|
||||
}
|
||||
|
||||
@@ -57,9 +57,11 @@ export class TrackingExportBar {
|
||||
readonly habilitado = input(true);
|
||||
/** How the analysis named the selection this answer belongs to; it travels into the files. */
|
||||
readonly seleccion = input<string | undefined>(undefined);
|
||||
readonly origen = input<Pick<SeguimientoTablaService, 'consultar'> | undefined>();
|
||||
|
||||
private readonly service = inject(SeguimientoTablaService);
|
||||
private subscription?: Subscription;
|
||||
private exportacion = 0;
|
||||
readonly formatos: readonly ExportFormat[] = ['xlsx', 'pdf'];
|
||||
readonly label = FORMAT_LABEL;
|
||||
readonly limits = EXPORT_LIMITS;
|
||||
@@ -80,14 +82,14 @@ export class TrackingExportBar {
|
||||
});
|
||||
|
||||
constructor() {
|
||||
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
|
||||
inject(DestroyRef).onDestroy(() => this.detenerExportacion());
|
||||
// A result message belongs to the query it was made for: it goes away when another query is shown. An export still
|
||||
// being read belongs to a query that is no longer on screen: it is cancelled, never downloaded as the current one.
|
||||
effect(() => {
|
||||
this.queryKey();
|
||||
untracked(() => {
|
||||
if (this.estado() === 'working') {
|
||||
this.subscription?.unsubscribe();
|
||||
this.detenerExportacion();
|
||||
this.estado.set('error'); this.listo.set(''); this.mensaje.set('La consulta cambió; se canceló la exportación. Vuelve a exportar.');
|
||||
} else { this.listo.set(''); this.mensaje.set(''); if (this.estado() === 'error') this.estado.set('idle'); }
|
||||
});
|
||||
@@ -101,35 +103,44 @@ export class TrackingExportBar {
|
||||
exportar(formato: ExportFormat) {
|
||||
if (!this.available(formato)) return;
|
||||
this.estado.set('working'); this.mensaje.set(''); this.listo.set(''); this.progress.set({ fetched: 0, total: 0 });
|
||||
this.subscription?.unsubscribe();
|
||||
this.detenerExportacion();
|
||||
const exportacion = this.exportacion;
|
||||
const clave = this.queryKey(), seleccion = this.seleccion();
|
||||
this.subscription = fetchAllTracking(this.service, this.dominio(), queryOf(this.respuesta()), EXPORT_LIMITS[formato]).subscribe({
|
||||
const esCaCu = this.dominio() === 'cacu';
|
||||
this.subscription = fetchAllTracking(this.origen() ?? this.service, this.dominio(), queryOf(this.respuesta()), EXPORT_LIMITS[formato]).subscribe({
|
||||
next: event => {
|
||||
if (event.kind === 'progress') this.progress.set({ fetched: event.fetched, total: event.total });
|
||||
else void this.generar(formato, seleccion ? { ...event.snapshot, seleccion } : event.snapshot, clave);
|
||||
else void this.generar(formato, { ...event.snapshot, seleccion, titulo: esCaCu ? 'Cáncer cervicouterino' : undefined }, clave, exportacion, esCaCu);
|
||||
},
|
||||
error: error => this.fallar(error),
|
||||
});
|
||||
}
|
||||
|
||||
cancelar() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.detenerExportacion();
|
||||
this.estado.set('idle');
|
||||
}
|
||||
|
||||
private async generar(formato: ExportFormat, snapshot: TrackingSnapshot, clave: string) {
|
||||
private detenerExportacion() {
|
||||
this.exportacion++;
|
||||
this.subscription?.unsubscribe();
|
||||
}
|
||||
|
||||
private async generar(formato: ExportFormat, snapshot: TrackingSnapshot, clave: string, exportacion: number, esCaCu: boolean) {
|
||||
try {
|
||||
// Each generator (and its library) downloads only when its button is used.
|
||||
const blob = formato === 'xlsx'
|
||||
? await (await import('./tracking-xlsx')).buildTrackingXlsx(snapshot)
|
||||
: await (await import('./tracking-pdf')).buildTrackingPdf(snapshot);
|
||||
// The query on screen changed while the file was being made: it is not the one that was asked for.
|
||||
if (clave !== this.queryKey()) return;
|
||||
downloadBlob(blob, exportFilename(snapshot.seleccion ? 'seguimiento-cancer-de-mama-seleccion' : 'seguimiento-cancer-de-mama', snapshot.corte, formato));
|
||||
if (exportacion !== this.exportacion || clave !== this.queryKey()) return;
|
||||
const nombre = esCaCu ? 'seguimiento-cancer-cervicouterino'
|
||||
: snapshot.seleccion ? 'seguimiento-cancer-de-mama-seleccion' : 'seguimiento-cancer-de-mama';
|
||||
downloadBlob(blob, exportFilename(nombre, snapshot.corte, formato));
|
||||
this.estado.set('idle');
|
||||
this.listo.set(`Se generó el archivo con ${snapshot.items.length} registros.`);
|
||||
} catch {
|
||||
this.fallar(new Error('generation'));
|
||||
if (exportacion === this.exportacion && clave === this.queryKey()) this.fallar(new Error('generation'));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ const sameQuery = consultaAplicada;
|
||||
* Reads every row a follow-up query matches, page by page, with the cut-off fixed by the first answer.
|
||||
* Unsubscribing cancels the pending requests. It fails instead of returning a partial or unstable list.
|
||||
*/
|
||||
export function fetchAllTracking(service: SeguimientoTablaService, dominio: Dominio, query: SeguimientoTablaQuery, limit: number): Observable<TrackingExportEvent> {
|
||||
export function fetchAllTracking(service: Pick<SeguimientoTablaService, 'consultar'>, dominio: Dominio, query: SeguimientoTablaQuery, limit: number): Observable<TrackingExportEvent> {
|
||||
const ask = (q: SeguimientoTablaQuery) => defer(() => service.consultar(dominio, q));
|
||||
return ask({ ...query, page: 1, page_size: PAGE_SIZE_MAX }).pipe(
|
||||
switchMap(first => {
|
||||
|
||||
@@ -8,6 +8,7 @@ export type TrackingRow = Record<string, SeguimientoValor>;
|
||||
|
||||
/** Everything one export needs: the first answer (columns, filters, window) and all the rows it announced. */
|
||||
export interface TrackingSnapshot {
|
||||
titulo?: string;
|
||||
/** How the analysis named the selection this list opens, when it does; the files carry it so they say where they come from. */
|
||||
seleccion?: string;
|
||||
corte: string;
|
||||
|
||||
@@ -48,7 +48,7 @@ function dataTable(snapshot: TrackingSnapshot) {
|
||||
|
||||
/** The document definition of a follow-up report. Exported so its content can be checked without rendering. */
|
||||
export function trackingDocument(snapshot: TrackingSnapshot, now: Date, logo?: string): PdfDefinition {
|
||||
return institutionalDocument({ title: TRACKING_TITLE, logo, now, orientation: 'landscape' }, [
|
||||
return institutionalDocument({ title: snapshot.titulo ?? TRACKING_TITLE, logo, now, orientation: 'landscape' }, [
|
||||
{ text: 'Resultados de seguimiento', style: 'h1' },
|
||||
parameters(snapshot),
|
||||
{ text: 'Pacientes', style: 'h2' },
|
||||
|
||||
@@ -48,7 +48,7 @@ export function parameterRows(snapshot: TrackingSnapshot, now: Date): SheetData
|
||||
});
|
||||
return [
|
||||
[header('Parámetro'), header('Valor')],
|
||||
row('Reporte', 'Cáncer de mama'),
|
||||
row('Reporte', snapshot.titulo ?? 'Cáncer de mama'),
|
||||
...(snapshot.seleccion ? [row('Selección del análisis', snapshot.seleccion)] : []),
|
||||
row('Fecha de corte', snapshot.corte),
|
||||
row('Ventana consultada', ventanaConsultada(snapshot)),
|
||||
|
||||
@@ -0,0 +1,835 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "collection",
|
||||
"entry": [
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "ados2-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2",
|
||||
"display": "ADOS-2"
|
||||
}
|
||||
]
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.modulo",
|
||||
"display": "Módulo"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.modulo.MODULO_2"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.css",
|
||||
"display": "Puntaje de severidad (CSS)"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 8
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.clasificacion",
|
||||
"display": "Clasificación"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.clasificacion.AUTISMO"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio",
|
||||
"code": "SA",
|
||||
"display": "Afecto social"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 10
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio",
|
||||
"code": "RRB",
|
||||
"display": "Comportamiento restringido y repetitivo"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.rrb_a4",
|
||||
"display": "Uso estereotipado o idiosincrásico de palabras o frases"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "RRB"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.rrb_d2",
|
||||
"display": "Manierismos de manos y dedos y otros manierismos complejos"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "RRB"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.rrb_d4",
|
||||
"display": "Intereses inusualmente repetitivos o comportamientos estereotipados"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "RRB"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_a6",
|
||||
"display": "Señalar"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_a7",
|
||||
"display": "Señalar"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 0,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b1",
|
||||
"display": "Contacto visual inusual"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b12",
|
||||
"display": "Características de las iniciaciones sociales"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b2",
|
||||
"display": "Expresiones faciales dirigidas a otros"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b3",
|
||||
"display": "Expresiones faciales dirigidas a otros"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 0,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b5",
|
||||
"display": "Disfrute compartido durante la interacción"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b6",
|
||||
"display": "Iniciación espontánea de la atención conjunta"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b8",
|
||||
"display": "Características de las iniciaciones sociales"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Procedure",
|
||||
"id": "eeg-vista-previa",
|
||||
"status": "completed",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "eeg",
|
||||
"display": "Electroencefalograma"
|
||||
}
|
||||
]
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"performedDateTime": "1985-01-01",
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "DiagnosticReport",
|
||||
"id": "eeg-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "eeg",
|
||||
"display": "Electroencefalograma"
|
||||
}
|
||||
]
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"result": [
|
||||
{
|
||||
"reference": "Observation/calidad-bad-scalp-triage-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-clean-windows-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-internal-coverage-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-line-noise-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-triage-level-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-usable-scalp-vista-previa"
|
||||
}
|
||||
],
|
||||
"conclusionCode": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/calidad",
|
||||
"code": "MALO"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "not-valid"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/duracion-min",
|
||||
"valueDecimal": 2.0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/edad-meses",
|
||||
"valueDecimal": 30.0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/canales",
|
||||
"valueInteger": 24
|
||||
}
|
||||
],
|
||||
"conclusion": "EEG de mala calidad: no es válido para el estudio (nivel de triaje: no_analizable).",
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-bad-scalp-triage-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "bad-scalp-triage",
|
||||
"display": "bad-scalp-triage"
|
||||
}
|
||||
],
|
||||
"text": "bad-scalp-triage"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 0.0,
|
||||
"unit": "electrodes"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"high": {
|
||||
"value": 2.0,
|
||||
"unit": "electrodes"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-clean-windows-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "clean-windows",
|
||||
"display": "clean-windows"
|
||||
}
|
||||
],
|
||||
"text": "clean-windows"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 100.0,
|
||||
"unit": "%"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"low": {
|
||||
"value": 60.0,
|
||||
"unit": "%"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-internal-coverage-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "internal-coverage",
|
||||
"display": "internal-coverage"
|
||||
}
|
||||
],
|
||||
"text": "internal-coverage"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 1.0,
|
||||
"unit": "fraction"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"low": {
|
||||
"value": 0.9,
|
||||
"unit": "fraction"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-line-noise-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "line-noise",
|
||||
"display": "line-noise"
|
||||
}
|
||||
],
|
||||
"text": "line-noise"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 9.231034526452635,
|
||||
"unit": "dB"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"high": {
|
||||
"value": 45.0,
|
||||
"unit": "dB"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": false
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-triage-level-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "triage-level",
|
||||
"display": "triage-level"
|
||||
}
|
||||
],
|
||||
"text": "triage-level"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "A"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueString": "no_analizable",
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-usable-scalp-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "usable-scalp",
|
||||
"display": "usable-scalp"
|
||||
}
|
||||
],
|
||||
"text": "usable-scalp"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 19.0,
|
||||
"unit": "electrodes"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"low": {
|
||||
"value": 12.0,
|
||||
"unit": "electrodes"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -33,15 +33,20 @@
|
||||
@if (status() === 'empty') { <p role="status">No hay citologías de alto grado publicadas para este periodo.</p> }
|
||||
@else {
|
||||
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
||||
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista base de la confirmación">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
<div class="tab-bar"><div class="tabs" role="group" aria-label="Grupos del anillo interior">
|
||||
@for (g of m.grupos; track g.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
<button type="button" class="tab" [style.--swatch]="g.color" [attr.aria-pressed]="selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<div class="keys" role="group" aria-label="Grados del anillo exterior">
|
||||
@for (c of m.grados; track c.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
</div></div>
|
||||
<div class="child-groups" role="group" aria-label="Categorías del anillo exterior">
|
||||
@for (g of m.grupos; track g.id) {
|
||||
<div class="tab-panel" role="group" [attr.aria-label]="g.etiqueta">
|
||||
@for (c of m.grados; track c.id; let i = $index) {
|
||||
@if (c.grupo === g.id) {
|
||||
<button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -64,3 +64,16 @@ app-plotly-chart { --plot-height: 360px; }
|
||||
.figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); }
|
||||
.histo .figure + .figure { border-top: 0; border-inline-start: 1px solid var(--issste-border); padding-top: 0; padding-inline-start: 1rem; }
|
||||
}
|
||||
|
||||
|
||||
.confirmacion:not(.histo) .legend { display: flex; flex-direction: column; gap: 0; margin-block: .15rem 1rem; }
|
||||
.confirmacion:not(.histo) .legend > button { align-self: flex-start; margin-bottom: .4rem; }
|
||||
.confirmacion:not(.histo) .tab-bar { display: flex; align-items: flex-end; border-bottom: 1px solid var(--issste-border); }
|
||||
.confirmacion:not(.histo) .tabs { display: flex; flex-wrap: wrap; gap: .2rem; min-width: 0; }
|
||||
.confirmacion:not(.histo) .tabs .tab { display: inline-flex; align-items: center; gap: .45rem; border: 1px solid transparent; border-bottom: 0; border-radius: .75rem .75rem 0 0; background: transparent; box-shadow: none; }
|
||||
.confirmacion:not(.histo) .tabs .tab[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 18%, var(--issste-surface)); border-color: var(--issste-border); box-shadow: inset 0 -3px 0 var(--swatch); font-weight: 700; }
|
||||
.confirmacion:not(.histo) .child-groups { display: flex; flex-wrap: wrap; align-items: center; column-gap: 2rem; row-gap: .45rem; padding: .65rem .1rem .1rem; }
|
||||
.confirmacion:not(.histo) .tab-panel { display: flex; flex-wrap: wrap; gap: .45rem; }
|
||||
.confirmacion:not(.histo) .tab-panel .child { display: inline-flex; align-items: center; gap: .45rem; border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); text-align: start; overflow-wrap: anywhere; }
|
||||
.confirmacion:not(.histo) .tab-panel .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); box-shadow: inset 0 0 0 1px var(--swatch); }
|
||||
.confirmacion:not(.histo) .tab .swatch, .confirmacion:not(.histo) .tab-panel .swatch { display: block; width: .35rem; height: 1em; margin: 0; border: 0; border-radius: .2rem; background: var(--swatch); align-self: center; }
|
||||
|
||||
@@ -33,15 +33,20 @@
|
||||
@if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
|
||||
@else {
|
||||
<div class="legend" role="group" aria-label="Explorar grupos y categorías de EU7">
|
||||
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección de EU7">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
<div class="tab-bar"><div class="tabs" role="group" aria-label="Grupos del anillo interior">
|
||||
@for (g of m.grupos; track g.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
<button type="button" class="tab" [style.--swatch]="g.color" [attr.aria-pressed]="selection.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
|
||||
@for (c of m.categorias; track c.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection.categoria === c.id" [disabled]="!!selection.grupo && selection.grupo !== c.grupo" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
</div></div>
|
||||
<div class="child-groups" role="group" aria-label="Categorías del anillo exterior">
|
||||
@for (g of m.grupos; track g.id) {
|
||||
<div class="tab-panel" role="group" [attr.aria-label]="g.etiqueta">
|
||||
@for (c of m.categorias; track c.id; let i = $index) {
|
||||
@if (c.grupo === g.id) {
|
||||
<button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection.categoria === c.id" [disabled]="!!selection.grupo && selection.grupo !== c.grupo" (click)="select('categorias', i)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@@ -53,7 +58,7 @@
|
||||
<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>
|
||||
<p>Número de pacientes por categoría en cada escenario, en una escala común; excluye «Sin dato».</p>
|
||||
@if (m.escenarios.length && barsFigure) {
|
||||
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7, barras por escenario clínico, ' + m.periodo + ', ' + selectionLabel" />
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
@use './indicadores-cacu-botones';
|
||||
:host { display: block; min-width: 0; }
|
||||
.eu7 { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
|
||||
@@ -49,7 +49,7 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
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');
|
||||
expect((f.componentInstance.barsFigure!.layout['yaxis'] as { categoryarray: string[] }).categoryarray[0]).not.toContain('Total válido');
|
||||
const general = data.general; const original = structuredClone(applied);
|
||||
const anormal = Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>).find(b => b.textContent!.includes('Anormal'))!;
|
||||
anormal.click(); f.detectChanges(); expect(f.componentInstance.selection.grupo).toBe('ANORMAL');
|
||||
@@ -63,6 +63,21 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
expect(f.componentInstance.donutFigure!.layout['paper_bgcolor']).toBe('#081839');
|
||||
expect(applied).toEqual(original); expect(data.general).toEqual(general); http.expectNone(() => true); kpi.unsubscribe();
|
||||
});
|
||||
it('desde TOTAL, elegir un hijo activa y abre su grupo sin volver a pedir datos', () => {
|
||||
f.detectChanges(); flush();
|
||||
const button = (name: string) => Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>)
|
||||
.find(item => item.textContent?.trim() === name)!;
|
||||
const child = button('LIEAG'), parent = button('Anormal');
|
||||
expect(parent.getAttribute('aria-pressed')).toBe('false');
|
||||
child.click(); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL', categoria: 'LIEAG' });
|
||||
expect(parent.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(child.getAttribute('aria-pressed')).toBe('true');
|
||||
expect((f.componentInstance.donutFigure!.data[2]['values'] as number[])[0]).toBe(0);
|
||||
child.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
|
||||
parent.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({});
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('dos periodos en una petición por alcance; navegación coordinada limpia selección sin GET', () => {
|
||||
const periods: [string, string] = ['2025-S1', '2025-S2'];
|
||||
for (const d of [data.general, data.estatus_seguimiento]) {
|
||||
@@ -75,7 +90,7 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
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.componentInstance.barsFigure!.layout['barmode']).toBe('group');
|
||||
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');
|
||||
|
||||
@@ -297,7 +297,7 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
this.estratos = stratumOptions(data);
|
||||
const publicados = new Set(this.estratos.map(e => e.valor));
|
||||
if ([...this.ocultos].some(v => !publicados.has(v))) this.ocultos = new Set([...this.ocultos].filter(v => publicados.has(v)));
|
||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida, this.ocultos);
|
||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida, this.ocultos, this.dominio);
|
||||
this.cells = adapted.cells;
|
||||
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
|
||||
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { c2Capability, c2Descendants, c2Figure } from './indicadores-c2-adapter';
|
||||
import { c2Color, C2_PALETTE, seriesColors } from './indicadores-c2-palette';
|
||||
import { c2Color, C2_PALETTE, recolorFigure, seriesColors } from './indicadores-c2-palette';
|
||||
import { c2Fixture } from './indicadores-c2-adapter.testing';
|
||||
import { FigureSelection } from './indicadores.models';
|
||||
import { FigureSelection, IndicadorDatos } from './indicadores.models';
|
||||
import { donutFixture } from './indicadores-donut-drilldown.testing';
|
||||
import { donutLegend, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
import { figurePresentation } from './indicadores.presentation';
|
||||
import { historicoFigura } from './indicadores-historico-figures';
|
||||
import { stratifiedBars } from './indicadores-stratified';
|
||||
|
||||
const selection: FigureSelection = { dominio: 'tea', indicador: 'i1', figura: 'fig_c2_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
|
||||
function supported(data = c2Fixture(), s = selection) {
|
||||
@@ -13,6 +15,32 @@ function supported(data = c2Fixture(), s = selection) {
|
||||
return result;
|
||||
}
|
||||
describe('C2: datos publicados a Plotly', () => {
|
||||
it('comparte el color de LIEBG entre dona, barras, estratos e histórico solo para CaCu', () => {
|
||||
const data: IndicadorDatos = { ...c2Fixture(), id: 'cacu_eu7' };
|
||||
const original = data['categorias'] as Record<string, object>;
|
||||
data['categorias'] = { LIEBG: { ...original['A'], color: '#E8C28E' }, B: original['B'], C: original['C'] };
|
||||
data.filas[0]['categoria'] = 'LIEBG';
|
||||
const cacu = { ...selection, dominio: 'cacu' as const, indicador: data.id };
|
||||
const pie = supported(data, cacu).figure;
|
||||
const bars = supported(data, { ...cacu, figura: 'fig_c2_barras' }).figure;
|
||||
const history = historicoFigura(data, 'claro').figure;
|
||||
const stratum = { ...data, estrato: 'grupo_edad', valores_estrato: ['estrato'], etiquetas_estrato: { estrato: 'Estrato' },
|
||||
filas: data.filas.map(row => ({ ...row, estrato: 'estrato' as const })) };
|
||||
const chart = (domain: 'cacu' | 'tea' | 'cama') => stratifiedBars(stratum, 'grupo_edad', '2025-S2', 'claro', {}, 'conteo', new Set(), domain);
|
||||
expect(pie.data[0]['marker']).toMatchObject({ colors: expect.arrayContaining(['#AD8F20']) });
|
||||
expect(bars.data[0]['marker']).toMatchObject({ color: expect.arrayContaining(['#AD8F20']) });
|
||||
expect(history.data[0]['marker']).toMatchObject({ color: '#AD8F20' });
|
||||
expect(chart('cacu').figure.data[0]['marker']).toMatchObject({ color: expect.arrayContaining(['#AD8F20']) });
|
||||
expect(chart('cacu').figure.data[0]['marker']).not.toHaveProperty('pattern');
|
||||
expect(chart('cacu').cells).toEqual(chart('tea').cells);
|
||||
for (const domain of ['tea', 'cama'] as const) {
|
||||
expect(chart(domain).figure.data[0]['marker']).toHaveProperty('pattern.shape', '');
|
||||
expect(chart(domain).figure.data[0]['marker']).toMatchObject({ color: [C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]] });
|
||||
expect(supported(data, { ...selection, indicador: data.id, dominio: domain }).figure.data[0]['marker']).toMatchObject({ colors: [C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]] });
|
||||
}
|
||||
expect(recolorFigure(pie)).toBe(pie); expect(recolorFigure(bars)).toBe(bars);
|
||||
expect(recolorFigure(history)).toBe(history);
|
||||
});
|
||||
it('equivale a los dos anillos publicados: valores, orden, relaciones, periodo y total', () => {
|
||||
const data = c2Fixture(), before = structuredClone(data), result = supported(data), server = donutFixture().figure;
|
||||
expect(result.figure.data.map(t => [t['labels'], t['values'], t['name']])).toEqual(server.data.map(t => [t['labels'], t['values'], t['name']]));
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models';
|
||||
import { DonutHierarchy } from './indicadores-donut-drilldown';
|
||||
import { basesPorGrupo, C2_PALETTE, c2Theme, seriesColors } from './indicadores-c2-palette';
|
||||
import { cacuCategoryColor, cacuGroupColor } from './indicadores-cacu-palette';
|
||||
|
||||
export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; }
|
||||
// Normalized presentation nodes and a selection path are independent of Plotly.
|
||||
@@ -81,8 +82,13 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
||||
const nodes: C2Node[] = [...parents, ...categories.map(c => ({ id: 'category:' + c.id, label: c.label, parentId: c.parentId ? 'group:' + c.parentId : undefined }))];
|
||||
const model: C2Distribution = { period, unit: data['unidad'], title: data['titulo'], categories, parents, nodes, total, notes: [...data.notas] };
|
||||
const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label);
|
||||
const colors = seriesColors(categories.map(c => c.color), categories.map(c => c.parentId ?? c.id));
|
||||
const isCaCu = selection.dominio === 'cacu';
|
||||
const defaults = seriesColors(categories.map(c => c.color), categories.map(c => c.parentId ?? c.id));
|
||||
const cacuColors = isCaCu ? categories.map(c => cacuCategoryColor(c.id)) : [];
|
||||
const colors = defaults.map((color, i) => cacuColors[i] ?? color);
|
||||
const bases = basesPorGrupo(parentIds);
|
||||
const groupColors = parentIds.map(id => (isCaCu ? cacuGroupColor(id) : undefined) ?? bases.get(id) ?? C2_PALETTE.series[0]);
|
||||
const edge = cacuColors.some(Boolean) ? { color: theme.background, width: 1.5 } : { color: theme.outline, width: 0.7 };
|
||||
const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined;
|
||||
const layout: Record<string, unknown> = { title: { text: model.title + ', ' + period }, autosize: true,
|
||||
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 },
|
||||
@@ -94,7 +100,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
||||
const figure: PlotlyFigure = { data: [], layout };
|
||||
if (selection.figura === 'fig_c2_barras') {
|
||||
if (rows.length) figure.data = [{ type: 'bar', orientation: 'h', name: period, x: values, y: labels,
|
||||
marker: { color: colors, line: { color: theme.outline, width: 0.7 } },
|
||||
marker: { color: colors, line: edge },
|
||||
hovertemplate: '%{y}<br>%{x} ' + model.unit + '<extra></extra>' }];
|
||||
layout['xaxis'] = { title: { text: 'Conteo (' + model.unit + ')' }, rangemode: 'tozero', showgrid: true,
|
||||
gridcolor: theme.grid, zeroline: false, tickformat: ',d', showline: true, linecolor: '#AEB7C2', linewidth: 1,
|
||||
@@ -105,12 +111,12 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
||||
} else if (total > 0) {
|
||||
layout['annotations'] = [{ x: 0.5, y: 0.5, xref: 'paper', yref: 'paper', showarrow: false,
|
||||
text: '<b>' + total + '</b>', font: { color: theme.text, size: 18 } }];
|
||||
figure.data = [{ type: 'pie', labels, values, marker: { colors, line: { color: theme.outline, width: 0.7 } },
|
||||
figure.data = [{ type: 'pie', labels, values, marker: { colors, line: edge },
|
||||
hole: 0.62, sort: false, name: period, textinfo: 'none', legendgroup: 'categorias', domain: { x: [0, 0.72], y: [0, 1] },
|
||||
hovertemplate: '%{label}<br>%{value} ' + model.unit + '<br>%{percent} de los ' + total + ' ' + model.unit + ' publicados<extra></extra>' }];
|
||||
if (parents.length) figure.data.push({ type: 'pie', labels: parents.map(p => p.label),
|
||||
values: parentIds.map(p => categories.filter(c => c.parentId === p).reduce((sum, c) => sum + c.value, 0)),
|
||||
marker: { colors: parents.map(p => bases.get(p.id.replace(/^group:/, '')) ?? C2_PALETTE.series[0]), line: { color: theme.outline, width: 0.7 } },
|
||||
marker: { colors: groupColors, line: edge },
|
||||
hole: 0.55, sort: false, name: period + ', grupos', textinfo: 'none', domain: { x: [0.14, 0.58], y: [0.29, 0.71] } });
|
||||
}
|
||||
const hierarchy = selection.figura === 'fig_c2_donas' && parents.length && total > 0
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
|
||||
.legend { display: flex; flex-direction: column; gap: 0; margin-block: .15rem 1rem; }
|
||||
.legend > button { align-self: flex-start; margin-bottom: .4rem; }
|
||||
.tab-bar { display: flex; align-items: flex-end; border-bottom: 1px solid var(--issste-border); }
|
||||
.tabs { display: flex; flex-wrap: wrap; gap: .2rem; min-width: 0; }
|
||||
.tabs .tab { display: inline-flex; align-items: center; gap: .45rem; border: 1px solid transparent; border-bottom: 0; border-radius: .75rem .75rem 0 0; background: transparent; box-shadow: none; }
|
||||
.tabs .tab[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 18%, var(--issste-surface)); border-color: var(--issste-border); box-shadow: inset 0 -3px 0 var(--swatch); font-weight: 700; }
|
||||
.child-groups { display: flex; flex-wrap: wrap; align-items: center; column-gap: 2rem; row-gap: .45rem; padding: .65rem .1rem .1rem; }
|
||||
.tab-panel { display: flex; flex-wrap: wrap; gap: .45rem; }
|
||||
.tab-panel .child { display: inline-flex; align-items: center; gap: .45rem; border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); text-align: start; overflow-wrap: anywhere; }
|
||||
.tab-panel .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); box-shadow: inset 0 0 0 1px var(--swatch); }
|
||||
.tab .swatch, .tab-panel .swatch { display: block; width: .35rem; height: 1em; margin: 0; border: 0; border-radius: .2rem; background: var(--swatch); align-self: center; }
|
||||
@@ -0,0 +1,40 @@
|
||||
import { isCoffeeColor } from './indicadores-c2-palette';
|
||||
|
||||
// Exact codes from the CaCu catalog. Cytology and biopsy keep their own groups.
|
||||
// The ochre sits outside the coffee range that the shared Plotly renderer recolors.
|
||||
const CATEGORY_COLORS: Readonly<Record<string, string>> = Object.freeze({
|
||||
NORMAL: '#438B53',
|
||||
'ASC-US': '#2879BD',
|
||||
LIEBG: '#AD8F20',
|
||||
'ASC-H': '#7959B8',
|
||||
LIEAG: '#D14D78',
|
||||
CIS: '#AE4050',
|
||||
CARCINOMA: '#925078',
|
||||
SIN_DATO: '#C9CDD2',
|
||||
SIN_BIOPSIA: '#C9CDD2',
|
||||
});
|
||||
|
||||
const GROUP_COLORS: Readonly<Record<string, string>> = Object.freeze({
|
||||
NO_ANORMAL: '#247A71',
|
||||
ANORMAL: '#656677',
|
||||
SIN_DATO: '#C9CDD2',
|
||||
});
|
||||
|
||||
export function cacuCategoryColor(id: string): string | undefined {
|
||||
return Object.hasOwn(CATEGORY_COLORS, id) ? CATEGORY_COLORS[id] : undefined;
|
||||
}
|
||||
|
||||
export function cacuGroupColor(id: string): string | undefined {
|
||||
return Object.hasOwn(GROUP_COLORS, id) ? GROUP_COLORS[id] : undefined;
|
||||
}
|
||||
|
||||
export function cacuClinicalColor(id: string, published: string | null): string {
|
||||
// A new catalog code can keep a valid published color when the renderer can keep it too.
|
||||
return cacuCategoryColor(id) ?? (published && !isCoffeeColor(published) ? published : '#8A9199');
|
||||
}
|
||||
|
||||
|
||||
export function cacuRgba(hex: string, alpha: number): string {
|
||||
const v = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
import { recolorFigure } from './indicadores-c2-palette';
|
||||
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
|
||||
periodosConfirmacion, rangoTasas, seleccionBase, tasas, wilson } from './indicadores-confirmacion-citologia';
|
||||
|
||||
@@ -128,7 +129,16 @@ describe('Confirmación histopatológica: modelo', () => {
|
||||
const otra = donaConfirmacion(m, { grupo: 'NO_ANORMAL', categoria: 'NORMAL' }, 'claro');
|
||||
expect(otra.data[2]['values']).toEqual(d.data[2]['values']);
|
||||
expect((otra.data[2]['marker'] as { colors: string[] }).colors[0]).toMatch(/,1\)$/);
|
||||
expect((otra.data[2]['marker'] as { colors: string[] }).colors[2]).toMatch(/,0.3\)$/);
|
||||
expect((otra.data[2]['marker'] as { colors: string[] }).colors[2]).toMatch(/,0\.45\)$/);
|
||||
});
|
||||
it('el carcinoma conserva el color del marcador, intervalo y dona al seleccionar', () => {
|
||||
const m = modeloConfirmacion(respuesta(), '2026-S2');
|
||||
const sel = { grupo: 'ANORMAL', categoria: 'CARCINOMA' };
|
||||
const tasa = figuraTasas(m, sel, 'oscuro'), pie = donaConfirmacion(m, sel, 'oscuro');
|
||||
expect(tasa.data[0]).toMatchObject({ marker: { color: '#925078' }, error_x: { color: '#925078' } });
|
||||
const i = m.grados.findIndex(g => g.id === 'CARCINOMA');
|
||||
expect((pie.data[2]['marker'] as { colors: string[] }).colors[i]).toBe('rgba(146,80,120,1)');
|
||||
expect(recolorFigure(tasa)).toBe(tasa); expect(recolorFigure(pie)).toBe(pie);
|
||||
});
|
||||
it('rechaza otro indicador, otro estrato, periodos no solicitados o filas duplicadas', () => {
|
||||
expect(() => periodosConfirmacion({ ...respuesta(), id: 'cacu_eu7' }, 'semestre')).toThrow(ConfirmacionIncompatible);
|
||||
@@ -169,7 +179,7 @@ describe('Confirmación histopatológica: componente', () => {
|
||||
const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[];
|
||||
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']);
|
||||
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub);
|
||||
const normal = [...f.nativeElement.querySelectorAll('.keys button')].find((b: Element) => b.textContent!.trim() === 'NORMAL') as HTMLButtonElement;
|
||||
const normal = [...f.nativeElement.querySelectorAll('.legend .child, .legend .tab')].find((b: Element) => b.textContent!.trim() === 'NORMAL') as HTMLButtonElement;
|
||||
normal.click(); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
|
||||
expect(normal.getAttribute('aria-pressed')).toBe('true');
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { cacuClinicalColor, cacuGroupColor, cacuRgba } from './indicadores-cacu-palette';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
|
||||
// Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia):
|
||||
@@ -69,10 +70,6 @@ function suma(celdas: Celda[]): number | null {
|
||||
function estado(celdas: Celda[]): Celda['estado'] {
|
||||
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
||||
}
|
||||
function rgba(hex: string, alfa: number): string {
|
||||
const v = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
||||
}
|
||||
// grupos_de_categoria publishes a label, or an object with `etiqueta`.
|
||||
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
|
||||
|
||||
@@ -97,20 +94,15 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
|
||||
const c = cats[a.id];
|
||||
return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta };
|
||||
});
|
||||
const gradosCrudos: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
|
||||
const grados: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
|
||||
if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])))
|
||||
|| typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Grados de biopsia incompatibles.');
|
||||
return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null) ?? COLOR_RESPALDO, grupo: c['grupo'] };
|
||||
return { id, etiqueta: c['etiqueta'], color: cacuClinicalColor(id, c['color'] as string | null), grupo: c['grupo'] };
|
||||
});
|
||||
const conColor = gradosCrudos.filter(g => g.color !== COLOR_RESPALDO);
|
||||
const colores = paintByGroup(conColor.map(g => g.grupo));
|
||||
const colorDe = new Map(conColor.map((g, i) => [g.id, colores[i]]));
|
||||
const grados = gradosCrudos.map(g => ({ ...g, color: colorDe.get(g.id) ?? g.color }));
|
||||
const bases = basesPorGrupo(conColor.map(g => g.grupo));
|
||||
const grupos = [...new Set(grados.map(g => g.grupo))].map(id => {
|
||||
// Off-catalogue grades keep the neutral fallback and do not take the group hue.
|
||||
const propios = grados.filter(g => g.grupo === id);
|
||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: bases.get(id) ?? COLOR_RESPALDO,
|
||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: cacuGroupColor(id) ?? COLOR_RESPALDO,
|
||||
grados: propios.map(g => g.id) };
|
||||
});
|
||||
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
|
||||
@@ -204,7 +196,7 @@ export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, t
|
||||
const y = valores.map(t => t.fila.etiqueta);
|
||||
return { data: [{
|
||||
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
||||
marker: { size: 12, color }, cliponaxis: false,
|
||||
marker: { size: 12, color, line: { color: p.text, width: 1 } }, cliponaxis: false,
|
||||
error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6,
|
||||
array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) },
|
||||
customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
|
||||
@@ -237,10 +229,10 @@ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
|
||||
marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), hovertext: hoverText(interior),
|
||||
marker: { colors: m.grupos.map(g => rgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
marker: { colors: m.grupos.map(g => cacuRgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .45)), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||
labels: m.grados.map(g => escapar(g.etiqueta)), hovertext: hoverText(exterior),
|
||||
marker: { colors: m.grados.map(g => rgba(g.color, activos.has(g.id) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
marker: { colors: m.grados.map(g => cacuRgba(g.color, activos.has(g.id) ? 1 : .45)), line: { color: p.background, width: 2 } } },
|
||||
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import fixture from './fixtures/eu7-c2-ejemplos.json';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { barras, clic, dona, modelo, porcentaje, periodosCompatibles, Seleccion } from './indicadores-eu7-escenario';
|
||||
import { percentNumber } from './indicadores-format';
|
||||
import { recolorFigure } from './indicadores-c2-palette';
|
||||
|
||||
function eu7Datos() {
|
||||
return structuredClone({ general: fixture.general as IndicadorDatos, escenarios: fixture.estatus_seguimiento as IndicadorDatos });
|
||||
@@ -19,6 +20,30 @@ describe('EU7 modelo de presentación del entregable', () => {
|
||||
expect(f.data[2]['values']).toEqual([798, 62, 46, 17, 19, 4]);
|
||||
expect(data).toEqual(original);
|
||||
});
|
||||
it.each(['claro', 'oscuro'] as const)('conserva colores lisos en dona y barras hasta Plotly, tema %s', tema => {
|
||||
const m = model();
|
||||
const expected = {
|
||||
NORMAL: '#438B53', 'ASC-US': '#2879BD', LIEBG: '#AD8F20', 'ASC-H': '#7959B8', LIEAG: '#D14D78', CIS: '#AE4050',
|
||||
};
|
||||
expect(Object.fromEntries(m.categorias.map(c => [c.id, c.color]))).toEqual(expected);
|
||||
for (const payload of [data.general, data.escenarios]) {
|
||||
payload['categorias'] = Object.fromEntries(Object.entries(payload['categorias'] as object).reverse());
|
||||
payload.filas.reverse();
|
||||
for (const row of payload.filas) if (typeof row['orden'] === 'number') row['orden'] = 10 - row['orden'];
|
||||
}
|
||||
expect(model().categorias.map(c => c.id)).not.toEqual(m.categorias.map(c => c.id));
|
||||
expect(Object.fromEntries(model().categorias.map(c => [c.id, c.color]))).toEqual(expected);
|
||||
const pie = dona(m, {}, tema), bar = barras(m, {}, tema);
|
||||
expect(recolorFigure(pie)).toBe(pie); expect(recolorFigure(bar)).toBe(bar);
|
||||
expect(pie.data[2]['marker']).not.toHaveProperty('pattern');
|
||||
const i = m.categorias.findIndex(c => c.id === 'LIEBG');
|
||||
expect(pie.data[2]['marker']).toMatchObject({ colors: expect.arrayContaining(['rgba(173,143,32,1)']) });
|
||||
expect(bar.data[i]).toMatchObject({ uid: 'LIEBG', marker: { color: '#AD8F20' } });
|
||||
expect(bar.data[i]['marker']).not.toHaveProperty('pattern');
|
||||
const selected = dona(m, { categoria: 'LIEBG' }, tema);
|
||||
expect(recolorFigure(selected)).toBe(selected);
|
||||
expect(selected.data[2]['marker']).toMatchObject({ colors: expect.arrayContaining(['rgba(121,89,184,0.45)']) });
|
||||
});
|
||||
it('TOTAL → Anormal → LIEAG → grupo → TOTAL y toggles', () => {
|
||||
const m = model(); let s: Seleccion = {};
|
||||
const g = m.grupos.findIndex(g => g.id === 'ANORMAL'), c = m.categorias.findIndex(c => c.id === 'LIEAG');
|
||||
@@ -29,26 +54,33 @@ describe('EU7 modelo de presentación del entregable', () => {
|
||||
s = clic(m, s, 'centro', 0); expect(s).toEqual({});
|
||||
expect(clic(m, { grupo: 'ANORMAL' }, 'grupos', g)).toEqual({});
|
||||
expect(clic(m, { categoria: 'LIEAG' }, 'centro', 0)).toEqual({});
|
||||
expect(clic(m, {}, 'categorias', c)).toEqual({ grupo: undefined, categoria: 'LIEAG' });
|
||||
expect(clic(m, {}, 'categorias', c)).toEqual({ grupo: 'ANORMAL', categoria: 'LIEAG' });
|
||||
expect(clic(m, {}, 'otra', c)).toEqual({});
|
||||
expect(clic(m, {}, 'grupos', -1)).toEqual({});
|
||||
expect(clic(m, { grupo: 'ANORMAL' }, 'categorias', 0)).toEqual({ grupo: 'ANORMAL' });
|
||||
});
|
||||
it('cada escenario suma 100 % en TOTAL y Anormal conserva 5.0, 24.3, 21.7, 7.8 %', () => {
|
||||
it('barras agrupadas: conteos absolutos por categoría y escenario, sin apilar ni normalizar', () => {
|
||||
const m = model(), f = barras(m, {}, 'claro');
|
||||
m.escenarios.forEach((s, i) => expect(f.data.reduce((n, t) => n + (t['x'] as number[])[i], 0)).toBeCloseTo(100, 8));
|
||||
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text)).toEqual(m.escenarios.map(s => `${s.den}`));
|
||||
expect(f.layout['barmode']).toBe('group');
|
||||
expect(f.data.map(t => t['uid'])).toEqual(m.categorias.map(c => c.id));
|
||||
f.data.forEach((t, i) => expect(t['x']).toEqual(m.escenarios.map(s => s.celdas[m.categorias[i].id].n)));
|
||||
m.escenarios.forEach((s, i) => expect(f.data.reduce((n, t) => n + (t['x'] as number[])[i], 0)).toBe(s.den));
|
||||
const labels = (f.layout['yaxis'] as { categoryarray: string[] }).categoryarray;
|
||||
m.escenarios.forEach((s, i) => { expect(labels[i]).toContain(s.etiqueta); expect(labels[i]).not.toContain('Total válido'); });
|
||||
expect((f.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Número de pacientes');
|
||||
const todos = f.data.flatMap(t => t['x'] as number[]);
|
||||
expect((f.layout['xaxis'] as { range: number[] }).range[0]).toBe(0);
|
||||
expect((f.layout['xaxis'] as { range: number[] }).range[1]).toBeGreaterThan(Math.max(...todos));
|
||||
const selected = barras(m, { grupo: 'ANORMAL' }, 'claro');
|
||||
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']);
|
||||
expect(selected.data.map(t => t['uid'])).toEqual(m.categorias.filter(c => c.grupo === 'ANORMAL').map(c => c.id));
|
||||
const anormales = m.categorias.filter(c => c.grupo === 'ANORMAL');
|
||||
m.escenarios.forEach((s, i) => expect(selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0)).toBe(anormales.reduce((n, c) => n + s.celdas[c.id].n!, 0)));
|
||||
// The selected scale is common and fits the selected counts, not the whole distribution.
|
||||
expect((selected.layout['xaxis'] as { range: number[] }).range[1]).toBeLessThan((f.layout['xaxis'] as { range: number[] }).range[1]);
|
||||
const category = barras(m, { categoria: 'LIEAG' }, 'claro');
|
||||
// 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(category.data).toHaveLength(1);
|
||||
expect(category.data[0]['x']).toEqual(m.escenarios.map(s => s.celdas['LIEAG'].n));
|
||||
expect(category.data[0]['text']).toEqual(m.escenarios.map(s => String(s.celdas['LIEAG'].n)));
|
||||
expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]);
|
||||
});
|
||||
it.each(['estrato', 'categorias', 'periodos', 'orden', 'duplicado', 'version', 'filtros', 'total', 'diferencia'])('rechaza incompatibilidad de %s', kind => {
|
||||
@@ -71,16 +103,19 @@ describe('EU7 modelo de presentación del entregable', () => {
|
||||
data.general['reportes'] = [{ periodo, report_id: 1 }]; data.escenarios['reportes'] = [{ periodo, report_id: 2 }];
|
||||
expect(model).toThrow(/reportes distintos/);
|
||||
});
|
||||
it.each(['suprimido', 'nulo', 'sin fila', 'sin dato suprimido', 'total suprimido'])('escenario con %s: todos los puntos son null y no hay denominador inventado', kind => {
|
||||
it.each(['suprimido', 'nulo', 'sin fila', 'sin dato suprimido', 'total suprimido'])('escenario con %s: el estado se dice, nunca se dibuja un cero ni un total inventado', kind => {
|
||||
const row = data.escenarios.filas.find(f => f['estrato'] === 'VIGILANCIA' && f['categoria'] === (kind === 'sin dato suprimido' ? 'SIN_DATO' : 'LIEAG'))!;
|
||||
if (kind === 'sin fila') data.escenarios.filas = data.escenarios.filas.filter(f => f !== row);
|
||||
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.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(m.escenarios[0].den).toBeNull();
|
||||
const t = f.data[0], celda = m.escenarios[0].celdas['LIEAG'];
|
||||
expect(f.data).toHaveLength(1);
|
||||
expect(t['x']).toEqual(m.escenarios.map(s => s.celdas['LIEAG'].n ?? 0));
|
||||
expect(t['text']).toEqual(m.escenarios.map(s => s.celdas['LIEAG'].n === null ? s.celdas['LIEAG'].estado : String(s.celdas['LIEAG'].n)));
|
||||
if (celda.n === null) expect((t['hovertext'] as string[])[0]).toContain('no es cero');
|
||||
expect((f.layout['yaxis'] as { categoryarray: string[] }).categoryarray[0]).toMatch(/Total (suprimido|no disponible)/);
|
||||
expect(JSON.stringify(f)).not.toContain('123456');
|
||||
expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull();
|
||||
});
|
||||
@@ -96,30 +131,30 @@ describe('EU7 modelo de presentación del entregable', () => {
|
||||
const m = model(); expect(m.escenarios.map(s => s.id)).not.toContain('INFO_INSUFICIENTE');
|
||||
expect(barras(m, {}, 'claro').data[0]['x']).toHaveLength(3);
|
||||
});
|
||||
it('escenario vacío y periodo de ceros no producen porcentajes 0/0', () => {
|
||||
it('escenario vacío y periodo de ceros: ceros publicados, sin porcentajes ni totales inventados', () => {
|
||||
data.general.filas.forEach(f => f['n'] = 0); data.escenarios.filas.forEach(f => f['n'] = 0);
|
||||
(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' })]));
|
||||
for (const sel of [{}, { categoria: 'LIEAG' }]) {
|
||||
const f = barras(m, sel, 'claro');
|
||||
expect(f.data.every(t => (t['x'] as number[]).every(v => v === 0) && (t['text'] as string[]).every(x => x === '0'))).toBe(true);
|
||||
expect((f.layout['yaxis'] as { categoryarray: string[] }).categoryarray.every(l => l.includes('Sin pacientes con resultado'))).toBe(true);
|
||||
}
|
||||
});
|
||||
it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => {
|
||||
data.general.filas = []; data.escenarios.filas = []; data.escenarios['totales_estrato'] = [];
|
||||
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', () => {
|
||||
it('selección jerárquica y Volver conservan orden, denominadores y datos fuente; las barras solo eligen categorías', () => {
|
||||
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 esperadas = (s: Seleccion) => m.categorias.filter(c => s.categoria ? c.id === s.categoria : s.grupo ? c.grupo === s.grupo : true).map(c => c.id);
|
||||
for (const selection of [{}, { grupo: 'ANORMAL' }, { grupo: 'ANORMAL', categoria: 'LIEAG' }, { categoria: 'LIEAG' }, { grupo: 'NO_ANORMAL' }, {}]) {
|
||||
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])));
|
||||
expect(f.data.map(t => t['uid'])).toEqual(esperadas(selection));
|
||||
f.data.forEach(t => {
|
||||
expect(t['x']).toEqual(m.escenarios.map(s => s.celdas[t['uid'] as string].n));
|
||||
expect(t['marker']).toMatchObject({ color: m.categorias.find(c => c.id === t['uid'])!.color });
|
||||
});
|
||||
dona(m, selection, 'claro');
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { cacuClinicalColor, cacuGroupColor, cacuRgba } from './indicadores-cacu-palette';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
|
||||
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
|
||||
@@ -39,10 +40,6 @@ function estado(celdas: Celda[]): Escenario['estado'] {
|
||||
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido'
|
||||
: celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
||||
}
|
||||
function rgba(hex: string, alfa: number): string {
|
||||
const v = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
||||
}
|
||||
function catalogo(data: IndicadorDatos): Categoria[] {
|
||||
const cats = data['categorias'], grupos = data['grupos_de_categoria'];
|
||||
if (!registro(cats) || !registro(grupos) || !Object.hasOwn(cats, SIN_DATO)) return fail('Catálogo EU7 incompleto.');
|
||||
@@ -129,11 +126,10 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
||||
// Missing rows remain unavailable. Catalog order is used only for the accessible
|
||||
// list of missing categories; a partial distribution is never drawn as a donut.
|
||||
const baseCategorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
|
||||
const claves = baseCategorias.map(c => c.grupo);
|
||||
const bases = basesPorGrupo(claves);
|
||||
const colores = paintByGroup(claves);
|
||||
const categorias = baseCategorias.map((c, i) => ({ ...c, color: colores[i] }));
|
||||
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id], color: bases.get(id)! }));
|
||||
const categorias = baseCategorias.map(c => ({ ...c, color: cacuClinicalColor(c.id, c.color) }));
|
||||
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({
|
||||
id, etiqueta: nombres[id], color: cacuGroupColor(id) ?? '#8A9199',
|
||||
}));
|
||||
const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))]));
|
||||
const totals = porEscenario['totales_estrato'];
|
||||
if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.');
|
||||
@@ -181,7 +177,7 @@ export function clic(m: Modelo, sel: Seleccion, traza: string, indice: number):
|
||||
if (traza !== 'categorias') return sel;
|
||||
const c = m.categorias[indice];
|
||||
if (!c || (sel.grupo && c.grupo !== sel.grupo)) return sel;
|
||||
return sel.categoria === c.id ? { grupo: sel.grupo } : { grupo: sel.grupo, categoria: c.id };
|
||||
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
|
||||
}
|
||||
export function porcentaje(s: Escenario, categoria: string): number | null {
|
||||
const n = s.celdas[categoria]?.n;
|
||||
@@ -193,6 +189,7 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema);
|
||||
const interior = m.grupos.map(g => !sel.grupo || sel.grupo === g.id ? nGrupo(m, g.id)! : 0);
|
||||
const exterior = m.categorias.map(c => !sel.grupo || sel.grupo === c.grupo ? m.celdas[c.id].n! : 0);
|
||||
const alpha = (id: string) => sel.categoria && id !== sel.categoria ? .45 : 1;
|
||||
const centro = sel.categoria ? m.celdas[sel.categoria].n! : sel.grupo ? nGrupo(m, sel.grupo)! : m.total;
|
||||
const rotulos = (values: number[], labels: string[], pct: boolean) => {
|
||||
const total = values.reduce((s, n) => s + n, 0);
|
||||
@@ -209,45 +206,44 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
||||
marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
|
||||
textfont: { color: '#FFFFFF' }, hovertext: hoverText(interior),
|
||||
marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||
hovertext: hoverText(interior),
|
||||
marker: { colors: m.grupos.map(g => cacuRgba(g.color, sel.categoria ? .45 : 1)), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||
labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true),
|
||||
textfont: { size: 11 }, hovertext: hoverText(exterior),
|
||||
marker: { colors: m.categorias.map(c => rgba(c.color, sel.categoria && c.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||
marker: { colors: m.categorias.map(c => cacuRgba(c.color, alpha(c.id))), line: { color: p.background, width: 2 } } },
|
||||
], layout: { autosize: true, height: 440, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
/** Selection never changes the original denominator or renormalizes a subset. */
|
||||
/** Absolute counts, one independent bar per category inside each clinical scenario. The selection only chooses which
|
||||
* categories are drawn; it never renormalizes anything and every scenario shares one horizontal scale. */
|
||||
export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema);
|
||||
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));
|
||||
// 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;
|
||||
});
|
||||
const visibles = m.categorias.filter(c => sel.categoria ? c.id === sel.categoria : sel.grupo ? c.grupo === sel.grupo : true);
|
||||
// The valid total of each scenario travels with its name; an unknown total is said, never drawn as zero.
|
||||
const y = m.escenarios.map(s => `${escapar(s.etiqueta)}${s.den === null ? `<br>Total ${s.estado === 'Suprimido' ? 'suprimido' : 'no disponible'}`
|
||||
: s.den === 0 ? '<br>Sin pacientes con resultado' : ''}`);
|
||||
const traces = visibles.map(c => {
|
||||
const celdas = m.escenarios.map(s => s.celdas[c.id]);
|
||||
// An unknown cell draws no bar (width 0) and says its state instead of a number; a published zero says «0».
|
||||
const x = celdas.map(v => v.n ?? 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),
|
||||
marker: { color: c.color, line: { color: p.background, width: 1 } },
|
||||
text: celdas.map(v => v.n === null ? v.estado : miles(v.n)), textposition: 'outside', cliponaxis: false,
|
||||
textfont: { size: 12, color: p.text },
|
||||
hovertext: celdas.map((v, i) => `${escapar(m.escenarios[i].etiqueta)}<br>${escapar(c.etiqueta)}: ${v.n === null
|
||||
? `${v.estado} (no es cero)` : `${miles(v.n)} ${v.n === 1 ? 'paciente' : 'pacientes'}`}`),
|
||||
hovertemplate: '%{hovertext}<extra></extra>' };
|
||||
});
|
||||
const mayor = Math.max(1, ...traces.flatMap(t => t.x));
|
||||
return { data: traces, layout: { barmode: 'group', bargap: .45, bargroupgap: .08, autosize: true,
|
||||
height: Math.max(360, 110 + m.escenarios.length * (visibles.length * 22 + 36)),
|
||||
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false,
|
||||
margin: { t: 16, l: 150, r: 24, b: 64 }, showlegend: false,
|
||||
// A thin rule between scenarios so each group reads as one unit.
|
||||
shapes: m.escenarios.slice(1).map((_, i) => ({ type: 'line', xref: 'paper', x0: 0, x1: 1, yref: 'y', y0: i + .5, y1: i + .5, line: { color: p.outline, width: 1, dash: 'dot' } })),
|
||||
yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true },
|
||||
xaxis: { title: { text: '% de pacientes del escenario con resultado' }, ticksuffix: ' %', gridcolor: p.grid,
|
||||
range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 112],
|
||||
tickvals: sel.grupo || sel.categoria ? undefined : [0, 20, 40, 60, 80, 100] },
|
||||
annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false,
|
||||
font: { size: 12, color: p.text }, text: s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado'
|
||||
: sel.grupo || sel.categoria ? `<b>${percentNumber(sumas[i]!)} %</b> (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})`
|
||||
: miles(s.den) })),
|
||||
xaxis: { title: { text: 'Número de pacientes' }, tickformat: ',d', gridcolor: p.grid, zeroline: false,
|
||||
range: [0, mayor * 1.2], ...(mayor <= 8 ? { dtick: 1 } : {}) },
|
||||
}, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import { historicoFigura } from './indicadores-historico-figures';
|
||||
import { datosValidos } from './indicadores.service';
|
||||
import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import vistaPreviaBundle from './fixtures/tea_vista_previa_bundle.json';
|
||||
|
||||
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
|
||||
|
||||
@@ -384,4 +385,18 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(mapa.regiones.map(r => [r.codigo, r.etiqueta, r.valor_z])).toEqual([
|
||||
['frontal_media', 'Frontal media', 3], ['central', 'Central', 1.5]]);
|
||||
});
|
||||
|
||||
it('la vista previa de un EDF y su ADOS-2 se lee como la ficha de un paciente guardado', async () => {
|
||||
// The fixture is what `POST /governance/tea/eeg/preview` answered for a short synthetic EDF with an ADOS-2 report.
|
||||
// Pins that the bundle the server builds without storing anything passes the same converter and checks as a
|
||||
// stored patient's summary. Fails if the server's shape and the converter drift apart.
|
||||
const answer = firstValueFrom(service.vistaPrevia(vistaPreviaBundle));
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush({ concept: [] });
|
||||
const detalle = await answer;
|
||||
expect(detalle.id_seudonimo).toBe('vista-previa');
|
||||
expect(detalle.ados2?.modulo).toBe('2');
|
||||
expect(detalle.ados2?.dominios.length).toBe(2);
|
||||
expect(detalle.eeg?.calidad).toBe('malo');
|
||||
expect(detalle.eeg?.criterios_calidad.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Color, c2Theme, C2_PALETTE, tonoDe } from './indicadores-c2-palette';
|
||||
import { cacuCategoryColor } from './indicadores-cacu-palette';
|
||||
import { sortedPeriods } from './indicadores-periodos';
|
||||
|
||||
export interface HistoricoFigura {
|
||||
@@ -203,6 +204,7 @@ function conteo(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones =
|
||||
? periodos.filter(p => !suprimidos.includes(p) && (numero(unidades?.[p]) ? unidades![p] === 0 : suma(p) === 0)) : []);
|
||||
const sinDato = periodos.filter(p => sinPoblacion.has(p) || (!suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n']))));
|
||||
const curso = { frio: 0, calido: 0, neutro: 0 };
|
||||
const isCaCu = data.id.startsWith('cacu_');
|
||||
return {
|
||||
figure: { data: orden.map((id, i) => {
|
||||
const meta = record(catalogo[id]) ? catalogo[id] : {};
|
||||
@@ -211,7 +213,8 @@ function conteo(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones =
|
||||
const slot = tono === 'neutro' ? i : curso[tono]++;
|
||||
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) && !sinPoblacion.has(p) ? n : null; });
|
||||
return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores,
|
||||
marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
|
||||
marker: { color: (isCaCu ? cacuCategoryColor(id) : undefined) ?? c2Color(color, slot, tono),
|
||||
...(isCaCu ? { line: { color: c2Theme(tema).background, width: 1 } } : {}) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
|
||||
}), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
|
||||
comoLeer: data.id === 'cama_birads_456_paciente' ? ''
|
||||
: CONTEOS[data.id]?.comoLeer ?? PIE_CATEGORIAS[data.id] ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
|
||||
|
||||
@@ -53,6 +53,7 @@ export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
|
||||
export const M28_COMPLETO = 'EEG';
|
||||
// M29's category of the EEGs the analysis found valid.
|
||||
export const M29_BUENO = 'BUENO';
|
||||
export const M29_MALO = 'MALO';
|
||||
// What only TEA's summary paragraph needs: the children by stage, the time of each screening step and the EEGs by quality.
|
||||
export const KPI_RESUMEN_TEA: KpiDefinition[] = [
|
||||
{ id: 'M28_casos_por_estado', title: 'Niños en el tamizaje', contrato: 'C2', unit: 'pacientes' },
|
||||
|
||||
@@ -36,7 +36,8 @@ describe('Seguimiento de CaMa: ficha del paciente', () => {
|
||||
// Fails if the export buttons leave the title row or come back under the table.
|
||||
it('has the export buttons in the row of the section title, and nothing after the pagination', () => {
|
||||
const row = root().querySelector('.title-row')!;
|
||||
expect(row.querySelector('h2')!.textContent).toContain('Seguimiento de');
|
||||
// Fails if the section heading goes back to «Seguimiento de …» instead of the name of the section tab.
|
||||
expect(row.querySelector('h2')!.textContent).toBe('Análisis de riesgos');
|
||||
expect([...row.querySelectorAll('button')].map(b => b.textContent!.trim())).toEqual(['Exportar Excel (.xlsx)', 'Exportar PDF']);
|
||||
expect(root().querySelector('nav')!.nextElementSibling).toBeNull();
|
||||
expect(root().textContent).not.toContain('Exportar resultados');
|
||||
|
||||
@@ -48,7 +48,7 @@ const mismosFiltros = (a: Record<string, string | undefined>, b: Record<string,
|
||||
}
|
||||
<div [hidden]="!!ficha()">
|
||||
<div class="title-row">
|
||||
<h2>Seguimiento de {{ domainLabel }}</h2>
|
||||
<h2>Análisis de riesgos</h2>
|
||||
@if (data(); as respuesta) {
|
||||
<app-seguimiento-exportar [dominio]="dominio" [respuesta]="respuesta" [habilitado]="estado() === 'ready' && !diferencia()" [seleccion]="etiquetaDatos()" />
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { DimensionEstrato, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { DimensionEstrato, Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { DonutSelection } from './indicadores-donut-drilldown';
|
||||
import { c2Theme, seriesColors } from './indicadores-c2-palette';
|
||||
import { cacuCategoryColor } from './indicadores-cacu-palette';
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
@@ -39,7 +40,7 @@ export function stratumOptions(data: IndicadorDatos): StratumOption[] {
|
||||
export interface StratifiedCell { category: string; stratum: string; value: number | null; percent: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
||||
/** The bars of one period broken down by `dimension`; the strata in `hidden` are left out of the figure and the cells,
|
||||
* unless that would leave none. */
|
||||
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}, medida: MedidaEstrato = 'conteo', hidden: ReadonlySet<string> = new Set()): { figure: PlotlyFigure; cells: StratifiedCell[] } {
|
||||
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}, medida: MedidaEstrato = 'conteo', hidden: ReadonlySet<string> = new Set(), dominio?: Dominio): { figure: PlotlyFigure; cells: StratifiedCell[] } {
|
||||
if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period
|
||||
|| !record(data['categorias']) || !record(data['grupos_de_categoria']) || !record(data['grupos'])
|
||||
|| Object.keys(data['grupos']).length !== 1
|
||||
@@ -73,7 +74,8 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
|
||||
if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas');
|
||||
const cells: StratifiedCell[] = [];
|
||||
const theme = c2Theme(tema);
|
||||
const palette = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id));
|
||||
const defaults = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id));
|
||||
const palette = dominio === 'cacu' ? categories.map(([id], i) => cacuCategoryColor(id) ?? defaults[i]) : defaults;
|
||||
// The stratum's total: the one published, or else the sum of its cells when every one is published. A share is
|
||||
// only drawn over a known total; a suppressed or missing total leaves the stratum without percentages.
|
||||
const totales = Array.isArray(data['totales_estrato']) ? data['totales_estrato'] as Record<string, unknown>[] : [];
|
||||
@@ -100,7 +102,8 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
|
||||
const x = selected.map(v => porcentaje ? v.percent : v.value);
|
||||
return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x, y: categories.map(([, c]) => escape(c.label)),
|
||||
customdata: selected.map(v => [v.value ?? 'sin valor', v.total ?? 'sin total']),
|
||||
marker: { color: palette, pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } },
|
||||
marker: { color: palette, line: { color: theme.text, width: .5 },
|
||||
...(dominio === 'cacu' ? {} : { pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] } }) },
|
||||
hovertemplate: porcentaje ? '%{y}<br>%{x:.1f} % (%{customdata[0]} de %{customdata[1]})<extra>%{fullData.name}</extra>' : '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
|
||||
}), layout: { title: { text: (porcentaje ? 'Porcentaje en cada estrato, ' : 'Distribución estratificada, ') + period }, barmode: 'group', autosize: true,
|
||||
height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background,
|
||||
|
||||
@@ -11,7 +11,14 @@
|
||||
</section>
|
||||
}
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado' || !!teaFicha">
|
||||
@if (dominio !== 'cama') { <h2>{{ titulo }}</h2> }
|
||||
@if (dominio === 'cacu') {
|
||||
<div class="title-row">
|
||||
<h2>{{ titulo }}</h2>
|
||||
@if (exportacionCaCu; as respuesta) {
|
||||
<app-seguimiento-exportar dominio="cacu" [respuesta]="respuesta" [origen]="origenExportacionCaCu" [habilitado]="active && pacienteDetalle.estado().tipo === 'cerrado'" />
|
||||
}
|
||||
</div>
|
||||
} @else if (dominio !== 'cama') { <h2>{{ titulo }}</h2> }
|
||||
@if (dominio === 'cama') {
|
||||
<app-seguimiento-tabla [dominio]="dominio" [domainLabel]="domainLabel" [active]="active" [seleccion]="seleccion" (fichaAbierta)="cambiaFichaCama($event)"
|
||||
(volverAlAnalisis)="volverAlAnalisis.emit()" />
|
||||
@@ -124,21 +131,36 @@
|
||||
</table>
|
||||
</div>
|
||||
} @else if (data; as response) {
|
||||
<div class="page-search">
|
||||
<label>Buscar identificador en esta página
|
||||
<input #buscadorCaCu type="search" [value]="busquedaCaCu" (input)="busquedaCaCu = buscadorCaCu.value"
|
||||
placeholder="Identificador completo o parcial" aria-describedby="alcance-busqueda-cacu" />
|
||||
</label>
|
||||
<button type="button" [disabled]="!busquedaCaCu" (click)="busquedaCaCu = ''; buscadorCaCu.focus()">Limpiar búsqueda</button>
|
||||
</div>
|
||||
@let visibles = pacientesVisibles(response);
|
||||
<p id="alcance-busqueda-cacu" role="status">
|
||||
@if (buscandoCaCu) { {{ visibles.length }} de {{ response.items.length }} registros de esta página coinciden. }
|
||||
Los archivos de exportación incluyen toda la consulta.
|
||||
</p>
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados disponibles por paciente</caption>
|
||||
<thead><tr><th scope="col">{{ etiquetaIdentidad(response) }}</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">Última biopsia</th>@for (c of columnasProbabilidad(); track c) {<th scope="col">{{ etiquetaProbabilidad[c] }} a {{ horizonteMostrado() }} años (%)</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>
|
||||
<thead><tr><th scope="col">{{ etiquetaIdentidad(response) }}</th><th scope="col">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">Última biopsia</th>@for (c of columnasProbabilidad(); track c) {<th scope="col">{{ etiquetaProbabilidad[c] }} a {{ horizonteMostrado() }} años (%)</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 identidad(item).id) {
|
||||
@for (item of visibles; track identidad(item).id) {
|
||||
<tr tabindex="-1" (click)="abrirPaciente(item, $event)" [attr.data-paciente]="identidad(item).id">
|
||||
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + identidad(item).id" (click)="abrirPaciente(item, $event)">{{ identidad(item).id }}</button></td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
|
||||
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + identidad(item).id" (click)="abrirPaciente(item, $event)">{{ identidad(item).id }}</button></td>
|
||||
<td>No disponible @if (item.grupo_edad !== 'sin_dato') { <small>Grupo de edad: {{ item.grupo_edad }}</small> }</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>@if (item.ultima_biopsia; as b) { {{ b.grado ?? 'Sin grado' }}<small>Fecha: {{ b.fecha }}</small> } @else { No disponible }</td>
|
||||
@for (c of columnasProbabilidad(); track c) { <td class="probabilidad">{{ probabilidad(item, c) ?? 'No disponible' }}</td> }
|
||||
<td>{{ latestStudy(item) ?? 'No disponible' }}</td><td>{{ item.dias_toma_diagnostico ?? 'No disponible' }}</td><td>{{ item.prioridad?.etiqueta ?? 'No disponible' }}</td>
|
||||
</tr>
|
||||
} @empty { <tr><td [attr.colspan]="9 + columnasProbabilidad().length">No hay registros para los filtros aplicados.</td></tr> }
|
||||
} @empty { <tr><td [attr.colspan]="9 + columnasProbabilidad().length">
|
||||
{{ buscandoCaCu ? 'No hay coincidencias en esta página.' : 'No hay registros para los filtros aplicados.' }}
|
||||
</td></tr> }
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
:host { display: block; min-width: 0; padding: var(--issste-space-4); overflow-wrap: anywhere;
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
h2 { font-size: 1.5rem; margin-top: 0; }
|
||||
.title-row { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem 1rem; margin-bottom: 1rem; }
|
||||
.title-row h2 { margin: 0; margin-inline-end: auto; }
|
||||
.page-search { display: flex; flex-wrap: wrap; align-items: end; gap: .5rem 1rem; }
|
||||
p { color: var(--issste-text-secondary); }
|
||||
form { display: flex; flex-wrap: wrap; align-items: end; gap: 1rem; margin-bottom: 1rem; }
|
||||
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
|
||||
|
||||
@@ -4,7 +4,7 @@ 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 { acotarTamano, PAGE_SIZE_MAX } from './seguimiento-tabla.service';
|
||||
import { acotarTamano, PAGE_SIZE_MAX, SeguimientoTablaResponse, SeguimientoTablaService } from './seguimiento-tabla.service';
|
||||
import { COLUMNAS_DE_PROBABILIDAD, ETIQUETA_PROBABILIDAD, latestStudy, probabilidadAl, ProbabilidadClave, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { porcentaje } from './paciente-detalle/paciente-riesgo.presentacion';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
@@ -16,10 +16,14 @@ import { ETIQUETA_IDENTIDAD, IdentidadPaciente, identidadDe } from './paciente-i
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { ALTERACIONES_EEG, EEG_VALIDO, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
|
||||
import { TeaPacienteResumen } from './tea-paciente-resumen';
|
||||
import { TrackingExportBar } from './export/tracking-export-bar';
|
||||
import { consultaExportacionCaCu, tablaExportacionCaCu } from './export/cacu-tracking-export';
|
||||
|
||||
const normalizarBusqueda = (texto: string) => texto.trim().normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-tracking',
|
||||
imports: [FormsModule, MatButtonModule, PacienteDetalleComponent, TeaPacienteResumen, IndicadoresSeguimientoTabla],
|
||||
imports: [FormsModule, MatButtonModule, PacienteDetalleComponent, TeaPacienteResumen, IndicadoresSeguimientoTabla, TrackingExportBar],
|
||||
providers: [PacienteDetalleState],
|
||||
templateUrl: './indicadores-tracking.html',
|
||||
styleUrl: './indicadores-tracking.scss',
|
||||
@@ -58,6 +62,19 @@ export class IndicadoresTracking implements OnChanges {
|
||||
status: 'idle' | 'loading' | 'ready' | 'pending' | 'error' = 'idle';
|
||||
message = '';
|
||||
data?: SeguimientoResponse;
|
||||
exportacionCaCu?: SeguimientoTablaResponse;
|
||||
readonly origenExportacionCaCu: Pick<SeguimientoTablaService, 'consultar'> = {
|
||||
consultar: (_dominio, q) => this.service.consultar(consultaExportacionCaCu(q)).pipe(map(respuesta => this.tablaExportacion(respuesta))),
|
||||
};
|
||||
busquedaCaCu = '';
|
||||
get buscandoCaCu() { return !!normalizarBusqueda(this.busquedaCaCu); }
|
||||
pacientesVisibles(respuesta: SeguimientoResponse) {
|
||||
const consulta = normalizarBusqueda(this.busquedaCaCu);
|
||||
return consulta ? respuesta.items.filter(item => normalizarBusqueda(this.identidad(item).id).includes(consulta)) : respuesta.items;
|
||||
}
|
||||
private tablaExportacion(respuesta: SeguimientoResponse) {
|
||||
return tablaExportacionCaCu(respuesta, estudio => this.cytologyLabel(estudio), (item, clave, horizonte) => this.probabilidad(item, clave, horizonte));
|
||||
}
|
||||
teaData?: TeaSeguimientoResponse;
|
||||
// One open summary at a time, like an accordion.
|
||||
teaAbierto?: string;
|
||||
@@ -84,8 +101,8 @@ export class IndicadoresTracking implements OnChanges {
|
||||
...this.columnasDelEstatus(this.draft.estatus).map(c => ({ codigo: c, etiqueta: ETIQUETA_PROBABILIDAD[c] }))];
|
||||
}
|
||||
/** A probability cell: "12.5 % (8.1 – 18 %)", or `null` when no model gives it at the horizon shown. */
|
||||
probabilidad(item: SeguimientoPaciente, clave: ProbabilidadClave): string | null {
|
||||
const h = probabilidadAl(item, clave, this.horizonteMostrado());
|
||||
probabilidad(item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte = this.horizonteMostrado()): string | null {
|
||||
const h = probabilidadAl(item, clave, horizonte);
|
||||
if (!h) return null;
|
||||
const ic = h.ic_bajo !== null && h.ic_alto !== null ? ` (${porcentaje(h.ic_bajo)} – ${porcentaje(h.ic_alto)} %)` : '';
|
||||
return `${porcentaje(h.probabilidad)} %${ic}`;
|
||||
@@ -110,6 +127,7 @@ export class IndicadoresTracking implements OnChanges {
|
||||
if (!result) return;
|
||||
this.changeDetector.markForCheck();
|
||||
this.status = result.status; this.data = result.data; this.message = result.message;
|
||||
this.exportacionCaCu = result.data && this.tablaExportacion(result.data);
|
||||
if (result.data) {
|
||||
const data = result.data;
|
||||
this.statuses = data.estatus_disponibles;
|
||||
@@ -148,6 +166,7 @@ export class IndicadoresTracking implements OnChanges {
|
||||
this.teaFicha = undefined; this.controlTea = undefined;
|
||||
this.pacienteDetalle.cerrar(); this.controlPaciente = undefined;
|
||||
this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null); this.data = undefined; this.teaData = undefined;
|
||||
this.exportacionCaCu = undefined; this.busquedaCaCu = '';
|
||||
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft };
|
||||
}
|
||||
if (this.dominio === 'cacu' && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); }
|
||||
@@ -157,6 +176,7 @@ export class IndicadoresTracking implements OnChanges {
|
||||
if (this.dominio !== 'cacu' && this.dominio !== 'tea') return;
|
||||
if (!validSeguimientoQuery(q)) { this.message = `Revisa la fecha, la ventana y el tamaño de página (1 a ${PAGE_SIZE_MAX}).`; return; }
|
||||
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
|
||||
this.exportacionCaCu = undefined;
|
||||
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(q);
|
||||
}
|
||||
apply() {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { cacuPatientDocument, buildCacuPatientPdf } from './cacu-patient-pdf';
|
||||
import { PacienteDetalleEstado } from './paciente-detalle.models';
|
||||
import { RegistroTemporal } from './paciente-registro.models';
|
||||
|
||||
const estado: Extract<PacienteDetalleEstado, { tipo: 'disponible' }> = {
|
||||
tipo: 'disponible', resumen: { identidad: { campo: 'id_seudonimo', id: 'PACIENTE-SINTETICO' }, grupoEdad: '40-49', estatus: 'Seguimiento', estatusCodigo: null, corte: '2026-10-20', origen: 'seguimiento-demostracion', citologia: { fecha: '2026-01-01', resultado: 'NORMAL', calidad: null }, vph: null, diasTomaDiagnostico: 0, prioridad: null },
|
||||
detalle: { id_seudonimo: 'PACIENTE-SINTETICO', origen: 'sintetico', historial: [{ descripcion: 'Antecedente sintético', fecha: null }], procedimientos: [], pruebas: null },
|
||||
};
|
||||
const registros: RegistroTemporal[] = [];
|
||||
const now = new Date('2026-11-12T21:30:00Z');
|
||||
|
||||
describe('Ficha CaCu: PDF individual', () => {
|
||||
it('usa el formato institucional y refleja datos, ceros y estados no disponibles', () => {
|
||||
const doc = cacuPatientDocument(estado, registros, { tipo: 'no-disponible' }, { NORMAL: { etiqueta: 'Normal' } }, now);
|
||||
const body = JSON.stringify(doc['content']);
|
||||
expect(doc['pageOrientation']).toBe('portrait');
|
||||
for (const value of ['PACIENTE-SINTETICO', 'Antecedente sintético', 'Normal', 'Riesgo individual no disponible', 'No disponible', 'Sin registros.', '"0"']) expect(body).toContain(value);
|
||||
expect(JSON.stringify(doc['info'])).not.toContain('PACIENTE-SINTETICO');
|
||||
});
|
||||
it('produce un PDF real', async () => {
|
||||
const blob = await buildCacuPatientPdf(estado, registros, { tipo: 'no-disponible' }, {}, now);
|
||||
const bytes = new TextDecoder('latin1').decode(await blob.arrayBuffer());
|
||||
expect(bytes.startsWith('%PDF-')).toBe(true);
|
||||
expect(bytes.trimEnd().endsWith('%%EOF')).toBe(true);
|
||||
}, 30000);
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { PdfDefinition, renderPdf } from '../export/pdf-engine';
|
||||
import { COLORS, institutionalDocument, loadLogo } from '../export/pdf-template';
|
||||
import { ETIQUETA_IDENTIDAD } from '../paciente-identidad';
|
||||
import { PacienteDetalleEstado } from './paciente-detalle.models';
|
||||
import { RegistroTemporal } from './paciente-registro.models';
|
||||
import { etiquetaRegistro, etiquetaResultado } from './paciente-registros-sesion';
|
||||
import { PacienteRiesgoEstado } from './paciente-riesgo.models';
|
||||
import { columnasRiesgo, conIntervalo, covariables, delEstatus, filasRiesgo } from './paciente-riesgo.presentacion';
|
||||
|
||||
type EstadoAbierto = Exclude<PacienteDetalleEstado, { tipo: 'cerrado' }>;
|
||||
type Categorias = Record<string, { etiqueta: string }>;
|
||||
const rule = { hLineWidth: () => 0.5, vLineWidth: () => 0, hLineColor: () => COLORS.rule, paddingTop: () => 4, paddingBottom: () => 4 };
|
||||
const valor = (v: string | number | null | undefined) => v == null ? 'No disponible' : String(v);
|
||||
const section = (title: string, rows: [string, string | number | null | undefined][]) => [
|
||||
{ text: title, style: 'h2' },
|
||||
{ table: { widths: [170, '*'], body: rows.map(([label, v]) => [{ text: label, bold: true }, { text: valor(v) }]) }, layout: rule },
|
||||
];
|
||||
|
||||
/** Instantánea de la ficha mostrada, incluidos los registros de demostración aún sin guardar. */
|
||||
export function cacuPatientDocument(estado: EstadoAbierto, registros: readonly RegistroTemporal[], riesgo: PacienteRiesgoEstado,
|
||||
categorias: Categorias, now: Date, logo?: string): PdfDefinition {
|
||||
const r = estado.resumen;
|
||||
const detalle = estado.tipo === 'disponible' ? estado.detalle : null;
|
||||
const temporal = (tipo: RegistroTemporal['tipo']) => registros.filter(item => item.tipo === tipo);
|
||||
const filas = (items: [string, string][], disponible: boolean): [string, string][] => items.length ? items : [['Estado', disponible ? 'Sin registros.' : 'Información no disponible.']];
|
||||
const condiciones: [string, string][] = detalle?.historial?.map(x => [x.descripcion, [x.fecha ?? 'No disponible', x.notas].filter(Boolean).join(' — ')]) ?? [];
|
||||
const procedimientos: [string, string][] = detalle?.procedimientos?.map(x => [x.nombre, [x.fecha ?? 'No disponible', x.resultado ? `Resultado: ${x.resultado}` : null].filter(Boolean).join(' — ')]) ?? [];
|
||||
for (const item of temporal('condicion')) condiciones.push([etiquetaRegistro(item), `${item.fecha} — Agregado en esta sesión, sin guardar`]);
|
||||
for (const item of temporal('procedimiento')) procedimientos.push([etiquetaRegistro(item), `${item.fecha} — Agregado en esta sesión, sin guardar`]);
|
||||
const pruebas: [string, string][] = detalle?.pruebas?.map(x => [x.nombre, `Fecha: ${valor(x.fecha)} — Resultado: ${valor(x.resultado)}`]) ?? [];
|
||||
for (const item of temporal('resultado')) pruebas.push([etiquetaRegistro(item), `Fecha: ${item.fecha} — Resultado: ${etiquetaResultado(item)} — Agregado en esta sesión, sin guardar`]);
|
||||
const citologia = r.citologia;
|
||||
const resultadoCitologia = citologia?.resultado != null ? categorias[citologia.resultado]?.etiqueta ?? citologia.resultado
|
||||
: citologia?.calidad?.trim().toUpperCase() === 'INSATISFACTORIO' ? 'Insatisfactoria' : 'Sin resultado al corte';
|
||||
let riesgos: [string, string][];
|
||||
if (riesgo.tipo === 'disponible') {
|
||||
const columnas = columnasRiesgo(riesgo.datos.riesgos, 'cacu', r.estatusCodigo);
|
||||
const filasDeRiesgo = filasRiesgo(columnas.map(c => c.lote?.horizontes.length ? c.lote : null));
|
||||
riesgos = filasDeRiesgo.flatMap(f => columnas.map((c, i): [string, string] => [
|
||||
`${c.encabezado} — ${f.horizonte_anios} ${c.lote?.estimando?.horizons_unit ?? 'años'}`,
|
||||
c.vacia ?? (f.celdas[i] ? conIntervalo(f.celdas[i]!) : '—'),
|
||||
]));
|
||||
if (!riesgos.length) riesgos = [['Estado', 'Sin horizontes evaluados en el lote vigente.']];
|
||||
const visibles = delEstatus(riesgo.datos.riesgos, r.estatusCodigo);
|
||||
for (const lote of visibles.filter(x => x.horizontes.length)) riesgos.push([`Fecha índice — ${lote.modelo_nombre}`, lote.fecha_indice]);
|
||||
const cov = covariables(visibles); if (cov) riesgos.push(['Covariables', cov]);
|
||||
} else riesgos = [['Estado', riesgo.tipo === 'cargando' ? 'Cargando riesgo individual.' : riesgo.tipo === 'error' ? 'No se pudo validar o cargar el riesgo individual.' : 'Riesgo individual no disponible para esta paciente.']];
|
||||
return institutionalDocument({ title: 'Ficha de paciente — Cáncer cervicouterino', logo, now, orientation: 'portrait' }, [
|
||||
{ text: `Paciente ${r.identidad.id}`, style: 'h1' }, { text: `Fecha de corte: ${r.corte}`, style: 'muted' },
|
||||
...section('Resumen', [[ETIQUETA_IDENTIDAD[r.identidad.campo], r.identidad.id], ['Fecha de nacimiento', null], ['Grupo de edad', r.grupoEdad], ['Estatus de seguimiento', r.estatus], ['Días de toma a diagnóstico', r.diasTomaDiagnostico], ['Prioridad', r.prioridad]]),
|
||||
...(estado.tipo === 'cargando' ? [{ text: 'Cargando información de la ficha.', style: 'muted' }] : estado.tipo === 'error' ? [{ text: 'No se pudo cargar la información de este paciente.', style: 'muted' }] : []),
|
||||
...section('Condiciones', filas(condiciones, detalle?.historial != null)),
|
||||
...section('Procedimientos', filas(procedimientos, detalle?.procedimientos != null)),
|
||||
...section('Últimos resultados', [
|
||||
['Última citología', citologia ? `Fecha: ${citologia.fecha} — Resultado: ${resultadoCitologia} — Calidad: ${valor(citologia.calidad)}` : null],
|
||||
['Último resultado de VPH', r.vph ? `Fecha: ${r.vph.fecha} — Resultado: ${r.vph.resultado} — Genotipo 16/18: ${r.vph.genotipo16y18 === null ? 'No disponible' : r.vph.genotipo16y18 ? 'Presente' : 'No detectado'}` : null],
|
||||
]),
|
||||
...section('Pruebas y resultados adicionales', filas(pruebas, detalle?.pruebas != null)),
|
||||
...section('Riesgo individual CaCu', riesgos),
|
||||
{ text: 'Recomendaciones no disponibles.', style: 'muted' },
|
||||
{ text: '“No disponible” indica dato no registrado, no ausencia clínica.', style: 'small', margin: [0, 10, 0, 0] },
|
||||
]);
|
||||
}
|
||||
|
||||
export async function buildCacuPatientPdf(estado: EstadoAbierto, registros: readonly RegistroTemporal[], riesgo: PacienteRiesgoEstado,
|
||||
categorias: Categorias, now = new Date(), logo?: string): Promise<Blob> {
|
||||
return renderPdf(cacuPatientDocument(estado, registros, riesgo, categorias, now, logo ?? await loadLogo()));
|
||||
}
|
||||
@@ -11,7 +11,7 @@ export interface CurvasSupervivencia {
|
||||
n: number; events: number; median_follow_up_months: number;
|
||||
horizons_months: number[]; months_max: number; bootstrap_replicas: number;
|
||||
km: { months: number[]; S: number[]; low: number[]; high: number[] };
|
||||
km_adjusted: { months: number[]; S: number[] };
|
||||
km_adjusted?: { months: number[]; S: number[] };
|
||||
weibull: { t: number[]; S: number[] };
|
||||
weibull_fractional: { t: number[]; S: number[] };
|
||||
points: { LR: SerieDeSupervivencia; HBN: SerieDeSupervivencia; COMB: SerieDeSupervivencia };
|
||||
@@ -50,7 +50,7 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas {
|
||||
const km = c['km'], adjusted = c['km_adjusted'], weibull = c['weibull'], fractional = c['weibull_fractional'], points = c['points'];
|
||||
if (!record(km) || !numbers(km['months']) || !probabilities(km['S'], (km['months'] as number[]).length)
|
||||
|| !probabilities(km['low'], (km['months'] as number[]).length) || !probabilities(km['high'], (km['months'] as number[]).length)) invalid();
|
||||
if (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length)) invalid();
|
||||
if (adjusted !== undefined && (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length))) invalid();
|
||||
for (const curve of [weibull, fractional]) {
|
||||
if (!record(curve) || !numbers(curve['t']) || !probabilities(curve['S'], (curve['t'] as number[]).length)) invalid();
|
||||
}
|
||||
@@ -63,7 +63,7 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas {
|
||||
escenario: typeof c['escenario'] === 'string' ? c['escenario'] : undefined,
|
||||
n: c['n'] as number, events: c['events'] as number, median_follow_up_months: c['median_follow_up_months'] as number,
|
||||
horizons_months: horizons as number[], months_max: c['months_max'] as number, bootstrap_replicas: c['bootstrap_replicas'] as number,
|
||||
km: km as CurvasSupervivencia['km'], km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'],
|
||||
km: km as CurvasSupervivencia['km'], ...(adjusted !== undefined ? { km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'] } : {}),
|
||||
weibull: weibull as CurvasSupervivencia['weibull'], weibull_fractional: fractional as CurvasSupervivencia['weibull_fractional'],
|
||||
points: { LR: serie(p['LR'], h), HBN: serie(p['HBN'], h), COMB: serie(p['COMB'], h) }, etiquetas,
|
||||
},
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
@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>
|
||||
<div class="toolbar">
|
||||
<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>
|
||||
<button class="export-button" mat-stroked-button type="button" [disabled]="generandoPdf()" (click)="exportarPdf()"><mat-icon aria-hidden="true">picture_as_pdf</mat-icon><span>Exportar ficha PDF</span></button>
|
||||
@if (generandoPdf()) { <p class="toolbar-message" role="status">Generando PDF…</p> }
|
||||
@if (errorPdf()) { <p class="toolbar-message" role="alert">No se pudo generar el PDF. Intenta nuevamente.</p> }
|
||||
</div>
|
||||
<header>
|
||||
<h2 #titulo tabindex="-1">Paciente {{ estado.resumen.identidad.id }}</h2>
|
||||
<p>Fecha de corte: {{ estado.resumen.corte }}.</p>
|
||||
<dl class="summary">
|
||||
<div><dt>{{ etiquetaIdentidad }}</dt><dd>{{ estado.resumen.identidad.id }}</dd></div>
|
||||
<div><dt>Fecha de nacimiento</dt><dd>No disponible</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>
|
||||
|
||||
@@ -5,6 +5,9 @@ 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; }
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .75rem 1rem; }
|
||||
.toolbar-message { flex: 0 0 100%; margin: 0; }
|
||||
.export-button { margin-inline-start: auto; }
|
||||
.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; }
|
||||
|
||||
@@ -128,6 +128,23 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
|
||||
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('exporta la ficha seleccionada a un PDF sin identificarla en el nombre del archivo', async () => {
|
||||
const pdf = await import('./cacu-patient-pdf');
|
||||
const build = vi.spyOn(pdf, 'buildCacuPatientPdf').mockResolvedValue(new Blob(['pdf']));
|
||||
const descargas: string[] = [];
|
||||
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:test');
|
||||
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
|
||||
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { descargas.push(this.download); });
|
||||
const ficha = abrir();
|
||||
const boton = [...ficha.querySelectorAll('button')].find(b => b.textContent?.includes('Exportar ficha PDF'))!;
|
||||
boton.click();
|
||||
for (let i = 0; i < 50 && !descargas.length; i++) await new Promise(resolve => setTimeout(resolve, 20));
|
||||
expect(build).toHaveBeenCalledOnce();
|
||||
expect(descargas[0]).toMatch(/^ficha-cancer-cervicouterino_corte-[\d-]+_\d{8}-\d{4}\.pdf$/);
|
||||
expect(descargas[0]).not.toContain(pacientes[0].id_seudonimo);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
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');
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AfterViewInit, Component, DestroyRef, ElementRef, inject, Input, OnDestroy, ViewChild, output } from '@angular/core';
|
||||
import { AfterViewInit, Component, DestroyRef, ElementRef, inject, Input, OnDestroy, ViewChild, output, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
@@ -10,6 +10,7 @@ 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';
|
||||
import { downloadBlob, exportFilename } from '../export/download-file';
|
||||
|
||||
@Component({
|
||||
selector: 'app-paciente-detalle',
|
||||
@@ -29,6 +30,9 @@ export class PacienteDetalleComponent implements AfterViewInit, OnDestroy {
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private dialogoActivo?: MatDialogRef<PacienteRegistroDialog, NuevoRegistroTemporal>;
|
||||
@ViewChild('titulo') private titulo?: ElementRef<HTMLElement>;
|
||||
@ViewChild(PacienteRiesgoTabla) private tablaRiesgo?: PacienteRiesgoTabla;
|
||||
readonly generandoPdf = signal(false);
|
||||
readonly errorPdf = signal(false);
|
||||
ngAfterViewInit() { this.titulo?.nativeElement.focus(); }
|
||||
ngOnDestroy() { this.dialogoActivo?.close(); }
|
||||
|
||||
@@ -38,6 +42,20 @@ export class PacienteDetalleComponent implements AfterViewInit, OnDestroy {
|
||||
get pacId() { return this.estado.tipo !== 'cerrado' && this.estado.resumen.identidad.campo === 'pac_id' ? this.estado.resumen.identidad.id : null; }
|
||||
temporales(tipo: TipoRegistroTemporal) { return this.registrosTemporales.filter(item => item.tipo === tipo); }
|
||||
|
||||
async exportarPdf() {
|
||||
if (this.estado.tipo === 'cerrado' || this.generandoPdf()) return;
|
||||
const estado = structuredClone(this.estado);
|
||||
const registros = structuredClone(this.registrosTemporales);
|
||||
const riesgo = structuredClone(this.tablaRiesgo?.estado() ?? { tipo: 'no-disponible' as const });
|
||||
const categorias = structuredClone(this.categorias);
|
||||
this.generandoPdf.set(true); this.errorPdf.set(false);
|
||||
try {
|
||||
const blob = await (await import('./cacu-patient-pdf')).buildCacuPatientPdf(estado, registros, riesgo, categorias);
|
||||
downloadBlob(blob, exportFilename('ficha-cancer-cervicouterino', estado.resumen.corte, 'pdf'));
|
||||
} catch { this.errorPdf.set(true); }
|
||||
finally { this.generandoPdf.set(false); }
|
||||
}
|
||||
|
||||
abrirRegistro(tipo: TipoRegistroTemporal) {
|
||||
if (this.estado.tipo === 'cerrado' || this.dialogoActivo) return;
|
||||
const paciente = this.estado.resumen.identidad;
|
||||
|
||||
@@ -85,7 +85,9 @@ export function normaFigure(m: TeaEegAlteracion, edad: number): PlotlyFigure {
|
||||
styleUrl: './tea-paciente-resumen.scss',
|
||||
})
|
||||
export class TeaPacienteResumen implements OnInit {
|
||||
@Input({ required: true }) id = '';
|
||||
@Input() id = '';
|
||||
/** A summary the host already has (an analysis that was not stored): nothing is requested. */
|
||||
@Input() detalleInicial?: TeaPacienteDetalle;
|
||||
/** `tarjetas`: four summary cards for a table row. `resumen`: the whole record as a summary with collapsible headers. */
|
||||
@Input() modo: 'tarjetas' | 'resumen' = 'tarjetas';
|
||||
/** The cards' button: the host shows the whole record in its own section. */
|
||||
@@ -129,19 +131,20 @@ export class TeaPacienteResumen implements OnInit {
|
||||
readonly nivelCss = NIVEL_CSS;
|
||||
readonly calidad = CALIDAD;
|
||||
readonly estado = ESTADO;
|
||||
ngOnInit() { this.load(); }
|
||||
ngOnInit() { if (this.detalleInicial) this.aplicar(this.detalleInicial); else this.load(); }
|
||||
// Opens on the first altered metric that has a map or a norm, or on the first one with either if none is altered.
|
||||
private aplicar(d: TeaPacienteDetalle) {
|
||||
const e = d.eeg;
|
||||
if (e) {
|
||||
const conPanel = e.alteraciones.filter(a => e.mapas.some(m => m.codigo === a.codigo) || this.conNorma(e, a.codigo));
|
||||
this.mostrar(e, (conPanel.find(a => a.estado === 'aumentado' || a.estado === 'disminuido') ?? conPanel[0])?.codigo);
|
||||
} else { this.mapaElegido = undefined; this.figura = this.figuraNorma = undefined; }
|
||||
this.detalle.set(d); this.status.set('ready');
|
||||
}
|
||||
load() {
|
||||
this.status.set('loading');
|
||||
this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
||||
next: d => {
|
||||
// Opens on the first altered metric that has a map or a norm, or on the first one with either if none is altered.
|
||||
const e = d.eeg;
|
||||
if (e) {
|
||||
const conPanel = e.alteraciones.filter(a => e.mapas.some(m => m.codigo === a.codigo) || this.conNorma(e, a.codigo));
|
||||
this.mostrar(e, (conPanel.find(a => a.estado === 'aumentado' || a.estado === 'disminuido') ?? conPanel[0])?.codigo);
|
||||
} else { this.mapaElegido = undefined; this.figura = this.figuraNorma = undefined; }
|
||||
this.detalle.set(d); this.status.set('ready');
|
||||
},
|
||||
next: d => this.aplicar(d),
|
||||
error: () => this.status.set('error'),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -37,10 +37,10 @@ describe('Resumen TEA por periodo', () => {
|
||||
expect(text).toContain('Al cierre del periodo 2025-S2, se evaluaron 100 niños entre 16 y 36 meses; 15 únicamente tienen M-CHAT, 15 hasta la evaluación psicológica y 70 presentan evaluación neuropediátrica.');
|
||||
expect(text).toContain('En este periodo el 86.5% de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0).');
|
||||
expect(text).toContain('Las ventanas de tiempo* de tamizaje son: 8 días de M-CHAT (psicología) a ADOS-2, 14 días de ADOS-2 a diagnóstico. El tiempo* de tamizaje completo de M-CHAT a diagnóstico fue de 22.5 días.');
|
||||
expect(text).toContain('De los 57 niños con diagnóstico confirmado en este periodo, 41 presentan estudio de EEG y faltan 16 por realizarlo. De los 41 estudios de EEG, 25.0% tienen buena calidad.');
|
||||
expect(text).toContain('De los 57 niños con diagnóstico confirmado en este periodo, 41 presentan estudio de EEG y faltan 16 por realizarlo. 50 estudios de EEG no son aceptables para un análisis.');
|
||||
expect(text).toContain('*tomando la mediana de los tiempos');
|
||||
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim()))
|
||||
.toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '41', '25.0%']);
|
||||
.toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '50']);
|
||||
expect(root.querySelector('button')).toBeNull();
|
||||
expect(root.querySelector('h2')!.textContent).toBe('Resumen');
|
||||
});
|
||||
@@ -57,17 +57,17 @@ describe('Resumen TEA por periodo', () => {
|
||||
for (const p of paneles) p.result.set({ ...p.result(), period: periodo });
|
||||
const text = texto(render(paneles, periodo).nativeElement);
|
||||
expect(text).toContain('se evaluaron 3 niños entre 16 y 36 meses; 1 únicamente tienen M-CHAT, 1 hasta la evaluación psicológica y 1 presentan');
|
||||
expect(text).toContain('De los 1 niños con diagnóstico confirmado en este periodo, 0 presentan estudio de EEG y faltan 1 por realizarlo. De los 0 estudios de EEG, 25.0% tienen buena calidad.');
|
||||
expect(text).toContain('De los 1 niños con diagnóstico confirmado en este periodo, 0 presentan estudio de EEG y faltan 1 por realizarlo. 1 estudios de EEG no son aceptables para un análisis.');
|
||||
for (const ejemplo of ['47', '155.5', '18.6', '54 días', '97 días', '##']) expect(text).not.toContain(ejemplo);
|
||||
});
|
||||
|
||||
it('un cero publicado es un cero y la ausencia de estudios no inventa un porcentaje', () => {
|
||||
// Fails if a published 0 turns into «sin dato», or if 0 studies print a percentage of buena calidad.
|
||||
// Fails if a published 0 turns into «sin dato», or if 0 studies print a count other than 0.
|
||||
const paneles = completos();
|
||||
paneles[3].result.set(c1('0.0', 0, 57)); paneles[4].result.set(c1('100.0', 57, 57));
|
||||
paneles[7].result.set({ ...listo(0), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 0 } });
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(texto(root)).toContain('0 presentan estudio de EEG y faltan 57 por realizarlo. De los 0 estudios de EEG, sin dato (Sin estudios de EEG en el periodo) tienen buena calidad.');
|
||||
expect(texto(root)).toContain('0 presentan estudio de EEG y faltan 57 por realizarlo. 0 estudios de EEG no son aceptables para un análisis.');
|
||||
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())).toContain('0');
|
||||
});
|
||||
|
||||
@@ -76,7 +76,7 @@ describe('Resumen TEA por periodo', () => {
|
||||
const paneles = completos();
|
||||
paneles[7].result.set({ ...listo(6), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 6 } });
|
||||
expect(texto(render(paneles).nativeElement))
|
||||
.toContain('estudios de EEG, 0.0% tienen buena calidad.');
|
||||
.toContain('0 estudios de EEG no son aceptables para un análisis.');
|
||||
});
|
||||
|
||||
it('muestra «sin dato» si falta, está oculto, es de otro periodo o no está publicado', () => {
|
||||
@@ -104,7 +104,7 @@ describe('Resumen TEA por periodo', () => {
|
||||
paneles[4].result.set(c1('28.1', 16, 58));
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(Array.from(root.querySelectorAll('.dato.sin-dato')).map(e => e.getAttribute('title')))
|
||||
.toEqual(Array(4).fill('Las poblaciones de M21 y M22 no coinciden'));
|
||||
.toEqual(Array(3).fill('Las poblaciones de M21 y M22 no coinciden'));
|
||||
});
|
||||
|
||||
it('indica la carga y reintenta solo las consultas con error', () => {
|
||||
|
||||
@@ -2,8 +2,7 @@ import { NgTemplateOutlet } from '@angular/common';
|
||||
import { Component, Input } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { shareNumber } from './indicadores-format';
|
||||
import { M28_COMPLETO, M29_BUENO } from './indicadores-kpi';
|
||||
import { M28_COMPLETO, M29_MALO } from './indicadores-kpi';
|
||||
|
||||
interface Valor { texto: string; estado: 'listo' | 'cargando' | 'sin_dato'; detalle?: string; }
|
||||
|
||||
@@ -33,8 +32,7 @@ const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M2
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: confirmados() }" /> niños con diagnóstico confirmado en este periodo,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: conEegBueno() }" /> presentan estudio de EEG y faltan
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: sinEegBueno() }" /> por realizarlo.
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: conEegBueno() }" /> estudios de EEG,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: buenaCalidad() }" /> tienen buena calidad.
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: eegNoAceptables() }" /> estudios de EEG no son aceptables para un análisis.
|
||||
</p>
|
||||
<p class="nota">*tomando la mediana de los tiempos</p>
|
||||
@if (conError.length) {
|
||||
@@ -109,13 +107,12 @@ export class TeaResumenPeriodo {
|
||||
// Of them, those with a good EEG (M21's numerator) and those without yet (M22's).
|
||||
conEegBueno() { return this.conteo(M21, 'numerador'); }
|
||||
sinEegBueno() { return this.conteo(M22, 'numerador'); }
|
||||
// The share of the period's EEGs (M29 counts exams, not patients) the analysis found valid.
|
||||
buenaCalidad(): Valor {
|
||||
// The period's EEGs (M29 counts exams, not patients) the analysis found not valid.
|
||||
eegNoAceptables(): Valor {
|
||||
const base = this.valor(M29, '');
|
||||
if (base.estado !== 'listo') return base;
|
||||
const result = this.panel(M29)!.result(), total = Number(result.value), buenos = result.categorias?.[M29_BUENO];
|
||||
if (total === 0) return this.sinDato('Sin estudios de EEG en el periodo');
|
||||
return buenos === undefined ? this.sinDato('Categoría no publicada') : { texto: shareNumber(buenos, total) + '%', estado: 'listo' };
|
||||
const malos = this.panel(M29)!.result().categorias?.[M29_MALO];
|
||||
return malos === undefined ? this.sinDato('Categoría no publicada') : { texto: String(malos), estado: 'listo' };
|
||||
}
|
||||
get cargando() { return this.paneles.some(p => p.result().loading); }
|
||||
get conError() { return this.paneles.filter(p => p.result().state === 'Error de consulta'); }
|
||||
|
||||
@@ -331,19 +331,26 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
|
||||
return forkJoin({
|
||||
bundle: this.client.get<Bundle>(`/tea/fhir/Patient/${encodeURIComponent(id)}/$resumen-tea`),
|
||||
metricas: this.metricas(),
|
||||
}).pipe(map(({ bundle, metricas }) => {
|
||||
const all = resources(bundle);
|
||||
const observations = all.filter(r => r.resourceType === 'Observation') as Observation[];
|
||||
const episode = resources(bundle, 'EpisodeOfCare')[0];
|
||||
const relacion = relacionDeRiesgo(resources(bundle, 'RiskAssessment')[0]);
|
||||
return teaPacienteDetalle({
|
||||
simulado: all.length > 0 && all.every(isSimulated),
|
||||
id_seudonimo: id,
|
||||
grupo_edad: grupoEdad(episode && extension(episode, 'grupo-edad')?.valueCoding?.code),
|
||||
ados2: ados2DeObservacion(byCode(observations, 'ados2')),
|
||||
eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas),
|
||||
...(relacion ? { relacion_ados2: relacion } : {}),
|
||||
}, id);
|
||||
}));
|
||||
}).pipe(map(({ bundle, metricas }) => detalleDeBundle(bundle, metricas, id)));
|
||||
}
|
||||
// The summary of an analysis the server did without storing it, read like a stored patient's.
|
||||
override vistaPrevia(bundle: unknown, id = 'vista-previa') {
|
||||
return this.metricas().pipe(map(metricas => detalleDeBundle(bundle as Bundle, metricas, id)));
|
||||
}
|
||||
}
|
||||
|
||||
// A `$resumen-tea` bundle as the patient summary the view draws.
|
||||
function detalleDeBundle(bundle: Bundle, metricas: Metric[], id: string) {
|
||||
const all = resources(bundle);
|
||||
const observations = all.filter(r => r.resourceType === 'Observation') as Observation[];
|
||||
const episode = resources(bundle, 'EpisodeOfCare')[0];
|
||||
const relacion = relacionDeRiesgo(resources(bundle, 'RiskAssessment')[0]);
|
||||
return teaPacienteDetalle({
|
||||
simulado: all.length > 0 && all.every(isSimulated),
|
||||
id_seudonimo: id,
|
||||
grupo_edad: grupoEdad(episode && extension(episode, 'grupo-edad')?.valueCoding?.code),
|
||||
ados2: ados2DeObservacion(byCode(observations, 'ados2')),
|
||||
eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas),
|
||||
...(relacion ? { relacion_ados2: relacion } : {}),
|
||||
}, id);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { map, Observable, throwError } from 'rxjs';
|
||||
import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
|
||||
@@ -244,4 +244,8 @@ export class TeaSeguimientoService {
|
||||
detalle(id: string) {
|
||||
return this.http.get<unknown>(`/tea/seguimiento/${encodeURIComponent(id)}`).pipe(map(v => teaPacienteDetalle(v, id)));
|
||||
}
|
||||
/** The summary of an analysis that was not stored; only the FHIR service reads the server's bundle. */
|
||||
vistaPrevia(_bundle: unknown, _id?: string): Observable<TeaPacienteDetalle> {
|
||||
return throwError(() => new Error('La vista previa necesita el servicio FHIR.'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* Covers `TeaEegApi`'s HTTP mapping: every method hits the contract's exact URL, verb, query and body,
|
||||
* and the multipart uploads send `reportProgress` so the UI can show progress. Fixtures: a real
|
||||
* `HttpClient` answered by `HttpTestingController`; each test flushes one canned response.
|
||||
*/
|
||||
import { HttpEvent, HttpEventType } from '@angular/common/http';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { TeaEegApi } from './tea-eeg.api';
|
||||
import { AnalyzeJob, ClusterStatus, TeaTrainBody } from './tea-eeg.types';
|
||||
|
||||
const STATUS: ClusterStatus = {
|
||||
mode: 'auto', scheduler: 'tcp://equipo:8786', reachable: true, workers: 4, expected_workers: 4,
|
||||
versions_ok: true, version_error: null, dashboard_ok: true, dashboard_url: 'http://equipo:8787/status',
|
||||
reference: { name: 'referencia_2026', edfs: 120 }, latency_ms: 42, error: null,
|
||||
};
|
||||
|
||||
// A finished analysis job, as `GET` answers it.
|
||||
const ANALYZE_JOB: AnalyzeJob = {
|
||||
id: 'a1', iniciado: '2026-11-01T10:00:00+00:00', estado: 'completado', codigo: 0,
|
||||
salida: '2 válidos, 1 no válido', error: '', cluster: null, ids: null,
|
||||
summary: { pending: 0, valid: 2, not_valid: 1, failed: 0 },
|
||||
};
|
||||
|
||||
describe('TeaEegApi', () => {
|
||||
let api: TeaEegApi;
|
||||
let http: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
api = TestBed.inject(TeaEegApi);
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
// Fails if the health check changes route, or sends params when no cluster was picked.
|
||||
it('asks for the cluster health without params, and with them when a choice is given', () => {
|
||||
api.clusterStatus().subscribe((s) => expect(s).toEqual(STATUS));
|
||||
http.expectOne((r) => r.url === '/governance/tea/cluster' && r.params.keys().length === 0).flush(STATUS);
|
||||
|
||||
api.clusterStatus({ mode: 'remote', scheduler: 'tcp://equipo:8786' }).subscribe();
|
||||
const req = http.expectOne((r) => r.url === '/governance/tea/cluster');
|
||||
expect(req.request.params.get('mode')).toBe('remote');
|
||||
expect(req.request.params.get('scheduler')).toBe('tcp://equipo:8786');
|
||||
req.flush(STATUS);
|
||||
});
|
||||
|
||||
// Fails if the cohort list moves, or the file upload stops being multipart on the cohort's route.
|
||||
it('lists reference cohorts and uploads one cohort file with progress events', () => {
|
||||
api.listReferenceCohorts().subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/reference-cohorts').flush([]);
|
||||
|
||||
const types: HttpEventType[] = [];
|
||||
api.uploadReferenceFile('referencia_2026', new File(['x'], 'estudio.edf')).subscribe((e) => types.push(e.type));
|
||||
const req = http.expectOne((r) => r.url === '/governance/tea/reference-cohorts/referencia_2026/files');
|
||||
expect(req.request.method).toBe('POST');
|
||||
expect(req.request.reportProgress).toBe(true);
|
||||
const body = req.request.body as FormData;
|
||||
expect(body.get('name')).toBeNull();
|
||||
expect((body.get('file') as File).name).toBe('estudio.edf');
|
||||
req.event({ type: HttpEventType.UploadProgress, loaded: 2, total: 4 });
|
||||
req.flush({ name: 'referencia_2026', file: 'estudio.edf', size_bytes: 4 });
|
||||
expect(types).toEqual([HttpEventType.Sent, HttpEventType.UploadProgress, HttpEventType.Response]);
|
||||
});
|
||||
|
||||
// Fails if training moves off the existing route, or the optional body stops being sent as-is.
|
||||
it('starts the TEA training on the existing train-jobs route', () => {
|
||||
api.startTeaTraining().subscribe();
|
||||
const empty = http.expectOne((r) => r.url === '/governance/model-versions/tea/eeg/train-jobs');
|
||||
expect(empty.request.method).toBe('POST');
|
||||
expect(empty.request.body).toEqual({});
|
||||
empty.flush({ job: null });
|
||||
|
||||
const body: TeaTrainBody = {
|
||||
reference_name: 'referencia_2026', reference_dir: '/datos/tea/referencia_2026', reference_ages: 'edades.csv',
|
||||
line_hz: 50, promote: false, cluster: { mode: 'remote', scheduler: 'tcp://equipo:8786' },
|
||||
};
|
||||
api.startTeaTraining(body).subscribe();
|
||||
const req = http.expectOne((r) => r.url === '/governance/model-versions/tea/eeg/train-jobs');
|
||||
expect(req.request.body).toEqual(body);
|
||||
req.flush({ job: null });
|
||||
});
|
||||
|
||||
// Fails if the export URL loses its query or the import moves off the baselines route.
|
||||
it('builds the baselines export URL and imports a bundle with progress events', () => {
|
||||
expect(api.baselinesExportUrl()).toBe('/governance/tea/baselines/export?environment=prod');
|
||||
expect(api.baselinesExportUrl('staging', false)).toBe('/governance/tea/baselines/export?environment=staging&production=0');
|
||||
|
||||
const events: HttpEvent<{ sha256: string }>[] = [];
|
||||
api.importBaselines(new File(['zip'], 'baselines.zip')).subscribe((e) => events.push(e));
|
||||
const req = http.expectOne((r) => r.url === '/governance/tea/baselines/import');
|
||||
expect(req.request.method).toBe('POST');
|
||||
expect(req.request.reportProgress).toBe(true);
|
||||
expect(((req.request.body as FormData).get('file') as File).name).toBe('baselines.zip');
|
||||
req.flush({ sha256: 'abc', imported: [] });
|
||||
expect(events.at(-1)?.type).toBe(HttpEventType.Response);
|
||||
});
|
||||
|
||||
// Fails if the analysis jobs change route, or the start/list/get verbs drift from the contract.
|
||||
it('starts, lists and gets analysis jobs on the analyze-jobs routes', () => {
|
||||
api.startAnalyzeJob({ all: true, cluster: { mode: 'sync' } }).subscribe((j) => expect(j).toEqual(ANALYZE_JOB));
|
||||
const started = http.expectOne((r) => r.url === '/governance/tea/eeg/analyze-jobs');
|
||||
expect(started.request.method).toBe('POST');
|
||||
expect(started.request.body).toEqual({ all: true, cluster: { mode: 'sync' } });
|
||||
started.flush(ANALYZE_JOB);
|
||||
|
||||
api.analyzeJobs().subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/eeg/analyze-jobs').flush([ANALYZE_JOB]);
|
||||
|
||||
api.analyzeJob('a1').subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/eeg/analyze-jobs/a1').flush(ANALYZE_JOB);
|
||||
});
|
||||
|
||||
// Fails if the progress route stops being jobs/<kind>/<id>/progress for either kind.
|
||||
it('reads a run progress for training and analysis', () => {
|
||||
api.runProgress('train', 't1').subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/jobs/train/t1/progress').flush(null);
|
||||
|
||||
api.runProgress('analyze', 'a1').subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/jobs/analyze/a1/progress').flush(null);
|
||||
});
|
||||
|
||||
// Fails if the baseline check routes drift, or the curve loses its metric query.
|
||||
it('reads baseline metric names and one metric curve', () => {
|
||||
api.baselineMetrics('tea_nsr', 3).subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/baselines/tea_nsr/3/metrics').flush(['alpha_peak']);
|
||||
|
||||
api.baselineCurve('tea_nsr', 3, 'alpha_peak').subscribe();
|
||||
const req = http.expectOne((r) => r.url === '/governance/tea/baselines/tea_nsr/3/curve');
|
||||
expect(req.request.params.get('metric')).toBe('alpha_peak');
|
||||
req.flush(null);
|
||||
});
|
||||
|
||||
// Fails if the EEG catalog loses its paging, or the metrics/summary routes move.
|
||||
it('lists EEGs paged and reads one EEG metrics and the summary', () => {
|
||||
api.eegList().subscribe();
|
||||
const list = http.expectOne((r) => r.url === '/governance/tea/eeg');
|
||||
expect(list.request.params.get('limit')).toBe('200');
|
||||
expect(list.request.params.get('offset')).toBe('0');
|
||||
list.flush([]);
|
||||
|
||||
api.eegList(50, 100).subscribe();
|
||||
const paged = http.expectOne((r) => r.url === '/governance/tea/eeg');
|
||||
expect(paged.request.params.get('limit')).toBe('50');
|
||||
expect(paged.request.params.get('offset')).toBe('100');
|
||||
paged.flush([]);
|
||||
|
||||
api.eegMetrics(7).subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/eeg/7/metrics').flush(null);
|
||||
|
||||
api.eegSummary().subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/eeg/summary').flush(null);
|
||||
});
|
||||
|
||||
// Fails if the EEG upload stops sending the file under the `file` field, or drops the patient id.
|
||||
it('uploads one EDF with an optional patient id', () => {
|
||||
api.uploadEeg(new File(['x'], 'estudio.edf')).subscribe();
|
||||
const bare = http.expectOne((r) => r.url === '/governance/tea/eeg/upload');
|
||||
expect(bare.request.method).toBe('POST');
|
||||
const form = bare.request.body as FormData;
|
||||
expect((form.get('file') as File).name).toBe('estudio.edf');
|
||||
expect(form.get('patient_id')).toBeNull();
|
||||
bare.flush({ eeg_id: 7, lab_id: null, created: true });
|
||||
|
||||
api.uploadEeg(new File(['x'], 'otro.edf'), 42).subscribe();
|
||||
const withPatient = http.expectOne((r) => r.url === '/governance/tea/eeg/upload');
|
||||
expect((withPatient.request.body as FormData).get('patient_id')).toBe('42');
|
||||
withPatient.flush({ eeg_id: 8, lab_id: 'L-2', created: false });
|
||||
});
|
||||
|
||||
// Fails if the recalculation moves off the existing indicators route, or sends a body without a cluster.
|
||||
it('recalculates the TEA indicators with an optional cluster body', () => {
|
||||
api.recalculateTeaIndicators().subscribe();
|
||||
const bare = http.expectOne((r) => r.url === '/reportes/indicadores/tea/recalcular');
|
||||
expect(bare.request.method).toBe('POST');
|
||||
expect(bare.request.body).toEqual({});
|
||||
bare.flush({ pendiente: true });
|
||||
|
||||
api.recalculateTeaIndicators({ mode: 'local' }).subscribe();
|
||||
const withCluster = http.expectOne((r) => r.url === '/reportes/indicadores/tea/recalcular');
|
||||
expect(withCluster.request.body).toEqual({ cluster: { mode: 'local' } });
|
||||
withCluster.flush({ pendiente: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import { HttpClient, HttpEvent, HttpParams } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import {
|
||||
AnalyzeBody,
|
||||
AnalyzeJob,
|
||||
BaselineCurve,
|
||||
BaselineImport,
|
||||
ClusterChoice,
|
||||
ClusterStatus,
|
||||
EegId,
|
||||
EegListItem,
|
||||
EegMetrics,
|
||||
EegPreview,
|
||||
EegSummary,
|
||||
EegUploadResult,
|
||||
ReferenceCohort,
|
||||
ReferenceFileUpload,
|
||||
RunProgress,
|
||||
TeaTrainBody,
|
||||
TeaTrainJob,
|
||||
} from './tea-eeg.types';
|
||||
|
||||
/** `/governance/tea/*`: the TEA·EEG cluster, reference cohorts, training, baseline bundles, analysis
|
||||
* jobs and the EEG catalog. The multipart uploads report progress events. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class TeaEegApi {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** Effective cluster health after resolving 'auto'; both query params optional. */
|
||||
clusterStatus(choice?: ClusterChoice): Observable<ClusterStatus> {
|
||||
const params = toParams(choice ? { mode: choice.mode, scheduler: choice.scheduler } : {});
|
||||
return this.http.get<ClusterStatus>('/governance/tea/cluster', { params });
|
||||
}
|
||||
|
||||
listReferenceCohorts(): Observable<ReferenceCohort[]> {
|
||||
return this.http.get<ReferenceCohort[]>('/governance/tea/reference-cohorts');
|
||||
}
|
||||
|
||||
/** One `.edf` or the cohort's `edades.csv`; emits upload progress events, then the stored file. */
|
||||
uploadReferenceFile(name: string, file: File): Observable<HttpEvent<ReferenceFileUpload>> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
return this.http.post<ReferenceFileUpload>(`/governance/tea/reference-cohorts/${encodeURIComponent(name)}/files`, form, {
|
||||
reportProgress: true,
|
||||
observe: 'events',
|
||||
});
|
||||
}
|
||||
|
||||
/** Starts the TEA training in the background: 202 with the job, 409 with the running one; the body
|
||||
* overrides the server's `TEA_REFERENCE_*` settings. */
|
||||
startTeaTraining(body: TeaTrainBody = {}): Observable<{ job: TeaTrainJob }> {
|
||||
return this.http.post<{ job: TeaTrainJob }>('/governance/model-versions/tea/eeg/train-jobs', body);
|
||||
}
|
||||
|
||||
/** Where the zip bundle of promoted baselines downloads from; `production=0` excludes them. */
|
||||
baselinesExportUrl(environment = 'prod', production?: boolean): string {
|
||||
let query = `environment=${encodeURIComponent(environment)}`;
|
||||
if (production !== undefined) query += `&production=${production ? 1 : 0}`;
|
||||
return `/governance/tea/baselines/export?${query}`;
|
||||
}
|
||||
|
||||
/** Imports a baseline bundle; emits upload progress events, then what was imported. */
|
||||
importBaselines(file: File): Observable<HttpEvent<BaselineImport>> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
return this.http.post<BaselineImport>('/governance/tea/baselines/import', form, {
|
||||
reportProgress: true,
|
||||
observe: 'events',
|
||||
});
|
||||
}
|
||||
|
||||
/** Starts an EEG analysis: 202 with the job, 409 while one runs. */
|
||||
startAnalyzeJob(body: AnalyzeBody): Observable<AnalyzeJob> {
|
||||
return this.http.post<AnalyzeJob>('/governance/tea/eeg/analyze-jobs', body);
|
||||
}
|
||||
|
||||
/** The analysis jobs, newest first. */
|
||||
analyzeJobs(): Observable<AnalyzeJob[]> {
|
||||
return this.http.get<AnalyzeJob[]>('/governance/tea/eeg/analyze-jobs');
|
||||
}
|
||||
|
||||
analyzeJob(id: string): Observable<AnalyzeJob> {
|
||||
return this.http.get<AnalyzeJob>(`/governance/tea/eeg/analyze-jobs/${encodeURIComponent(id)}`);
|
||||
}
|
||||
|
||||
/** Live progress of a training (`kind: 'train'`) or analysis (`'analyze'`) run; 404 before the first
|
||||
* sample. Non-Dask jobs answer `cluster: null` and `tasks: null`. */
|
||||
runProgress(kind: 'train' | 'analyze', jobId: string): Observable<RunProgress> {
|
||||
return this.http.get<RunProgress>(`/governance/tea/jobs/${kind}/${encodeURIComponent(jobId)}/progress`);
|
||||
}
|
||||
|
||||
/** The metric names a baseline version has a curve for. */
|
||||
baselineMetrics(scenario: string, version: number): Observable<string[]> {
|
||||
return this.http.get<string[]>(`/governance/tea/baselines/${encodeURIComponent(scenario)}/${version}/metrics`);
|
||||
}
|
||||
|
||||
/** One metric's curve across age for a baseline version. */
|
||||
baselineCurve(scenario: string, version: number, metric: string): Observable<BaselineCurve> {
|
||||
return this.http.get<BaselineCurve>(`/governance/tea/baselines/${encodeURIComponent(scenario)}/${version}/curve`, {
|
||||
params: new HttpParams().set('metric', metric),
|
||||
});
|
||||
}
|
||||
|
||||
/** The EEG catalog, paged; feeds the ticked list of the analysis step. */
|
||||
eegList(limit = 200, offset = 0): Observable<EegListItem[]> {
|
||||
return this.http.get<EegListItem[]>('/governance/tea/eeg', { params: toParams({ limit, offset }) });
|
||||
}
|
||||
|
||||
eegMetrics(eegId: EegId): Observable<EegMetrics> {
|
||||
return this.http.get<EegMetrics>(`/governance/tea/eeg/${encodeURIComponent(eegId)}/metrics`);
|
||||
}
|
||||
|
||||
eegSummary(): Observable<EegSummary> {
|
||||
return this.http.get<EegSummary>('/governance/tea/eeg/summary');
|
||||
}
|
||||
|
||||
/** One `.edf` through the existing import pipeline; 400 when MNE cannot open it. */
|
||||
uploadEeg(file: File, patientId?: number): Observable<EegUploadResult> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
if (patientId !== undefined) form.append('patient_id', String(patientId));
|
||||
return this.http.post<EegUploadResult>('/governance/tea/eeg/upload', form);
|
||||
}
|
||||
|
||||
/** Analyses one `.edf` (and its ADOS-2 `.pdf`, if any) in memory; nothing is written to a database. */
|
||||
previewEeg(edf: File, ados2?: File): Observable<EegPreview> {
|
||||
const form = new FormData();
|
||||
form.append('edf', edf);
|
||||
if (ados2) form.append('ados2', ados2);
|
||||
return this.http.post<EegPreview>('/governance/tea/eeg/preview', form);
|
||||
}
|
||||
|
||||
/** Recomputes the TEA indicators on the given cluster; the body is optional. */
|
||||
recalculateTeaIndicators(cluster?: ClusterChoice): Observable<{ pendiente: boolean }> {
|
||||
return this.http.post<{ pendiente: boolean }>('/reportes/indicadores/tea/recalcular', cluster ? { cluster } : {});
|
||||
}
|
||||
}
|
||||
|
||||
function toParams(filters: Record<string, string | number | boolean | undefined>): HttpParams {
|
||||
let params = new HttpParams();
|
||||
for (const [key, value] of Object.entries(filters)) {
|
||||
if (value !== undefined && value !== null && value !== '') params = params.set(key, String(value));
|
||||
}
|
||||
return params;
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
/** Shapes of the `/governance/tea/*` JSON contract: cluster health, reference cohorts, TEA training,
|
||||
* baseline bundles, EEG analysis jobs and the EEG catalog. */
|
||||
import { TrainingJob } from './governance.types';
|
||||
|
||||
export type ClusterMode = 'auto' | 'local' | 'remote' | 'sync';
|
||||
|
||||
/** Where the work runs; `scheduler` is only meaningful for 'remote'. */
|
||||
export interface ClusterChoice {
|
||||
mode: ClusterMode;
|
||||
scheduler?: string;
|
||||
}
|
||||
|
||||
export type JobState = 'en_curso' | 'completado' | 'entrenado_sin_promover' | 'fallido' | 'interrumpido';
|
||||
|
||||
/** Effective cluster health after resolving 'auto'. */
|
||||
export interface ClusterStatus {
|
||||
mode: ClusterMode;
|
||||
scheduler: string | null;
|
||||
reachable: boolean;
|
||||
workers: number | null;
|
||||
expected_workers: number | null;
|
||||
versions_ok: boolean | null;
|
||||
version_error: string | null;
|
||||
dashboard_ok: boolean | null;
|
||||
dashboard_url: string | null;
|
||||
reference: { name: string; edfs: number } | null;
|
||||
latency_ms: number | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/** One reference cohort folder under `TEA_REFERENCE_ROOT`. */
|
||||
export interface ReferenceCohort {
|
||||
name: string;
|
||||
edfs: number;
|
||||
size_bytes: number;
|
||||
has_ages: boolean;
|
||||
path: string;
|
||||
}
|
||||
|
||||
/** The answer to uploading one cohort file (`.edf` or `edades.csv`): 201. */
|
||||
export interface ReferenceFileUpload {
|
||||
name: string;
|
||||
file: string;
|
||||
size_bytes: number;
|
||||
}
|
||||
|
||||
/** Body of the TEA training route; fields override the server's `TEA_REFERENCE_*`. */
|
||||
export interface TeaTrainBody {
|
||||
reference_name?: string;
|
||||
reference_dir?: string;
|
||||
reference_ages?: string;
|
||||
line_hz?: number;
|
||||
promote?: boolean;
|
||||
cluster?: ClusterChoice;
|
||||
}
|
||||
|
||||
/** The training job the existing route answers, with the cluster it ran on. */
|
||||
export interface TeaTrainJob extends TrainingJob {
|
||||
cluster: ClusterChoice | null;
|
||||
}
|
||||
|
||||
/** The answer to importing a baseline bundle. */
|
||||
export interface BaselineImport {
|
||||
sha256: string;
|
||||
imported: { scenario: string; version: number }[];
|
||||
}
|
||||
|
||||
/** Body of an analysis job start. */
|
||||
export interface AnalyzeBody {
|
||||
all?: boolean;
|
||||
limit?: number;
|
||||
ids?: (number | string)[];
|
||||
cluster?: ClusterChoice;
|
||||
}
|
||||
|
||||
/** Counts behind an analysis job, present once it finished. */
|
||||
export interface AnalyzeSummary {
|
||||
pending: number;
|
||||
valid: number;
|
||||
not_valid: number;
|
||||
failed: number;
|
||||
}
|
||||
|
||||
/** An EEG analysis job in the background. */
|
||||
export interface AnalyzeJob {
|
||||
id: string;
|
||||
iniciado: string;
|
||||
estado: JobState;
|
||||
codigo: number | null;
|
||||
salida: string;
|
||||
error: string;
|
||||
cluster: ClusterChoice | null;
|
||||
ids: (number | string)[] | null;
|
||||
summary: AnalyzeSummary | null;
|
||||
}
|
||||
|
||||
/** Live progress of a training or analysis run. */
|
||||
export interface RunProgress {
|
||||
updated_at: string;
|
||||
phase: string;
|
||||
done: number;
|
||||
total: number;
|
||||
elapsed_s: number;
|
||||
eta_s: number | null;
|
||||
tasks: { processing: number; waiting: number; memory: number; erred: number } | null;
|
||||
cluster: {
|
||||
mode: ClusterMode;
|
||||
scheduler: string | null;
|
||||
workers: WorkerSample[];
|
||||
cpu_pct: number;
|
||||
memory_pct: number;
|
||||
} | null;
|
||||
history: { t: number; done: number; cpu_pct: number; memory_pct: number }[];
|
||||
}
|
||||
|
||||
/** One Dask worker sample inside a run's progress. */
|
||||
export interface WorkerSample {
|
||||
name: string;
|
||||
cpu_pct: number;
|
||||
memory_bytes: number;
|
||||
memory_limit: number | null;
|
||||
executing: number;
|
||||
threads: number;
|
||||
}
|
||||
|
||||
/** A stored baseline curve for one metric. */
|
||||
export interface BaselineCurve {
|
||||
scenario: string;
|
||||
version: number;
|
||||
metric: string;
|
||||
edad_meses: number[];
|
||||
p5: number[];
|
||||
p25: number[];
|
||||
mediana: number[];
|
||||
p75: number[];
|
||||
p95: number[];
|
||||
}
|
||||
|
||||
/** One EEG's metric values with their z scores against the baseline. */
|
||||
export interface EegMetrics {
|
||||
eeg_id: EegId;
|
||||
valid: boolean | null;
|
||||
level: string | null;
|
||||
age_months: number | null;
|
||||
metrics: { name: string; value: number; z: number | null; outside: -1 | 0 | 1 | null; model: string | null }[];
|
||||
}
|
||||
|
||||
export type EegId = number | string;
|
||||
|
||||
/** One EEG of the catalog, as listed for the analysis step's ticked list. */
|
||||
export interface EegListItem {
|
||||
id: EegId;
|
||||
lab_id: string | null;
|
||||
patient_id: number | null;
|
||||
study_date: string | null;
|
||||
valid: boolean | null;
|
||||
analysed: boolean;
|
||||
}
|
||||
|
||||
/** The answer to uploading one `.edf`: 201. */
|
||||
export interface EegUploadResult {
|
||||
eeg_id: EegId | null;
|
||||
lab_id: string | null;
|
||||
created: boolean;
|
||||
}
|
||||
|
||||
/** Catalog counts for the result step. */
|
||||
export interface EegSummary {
|
||||
eegs: number;
|
||||
analysed: number;
|
||||
valid: number;
|
||||
not_valid: number;
|
||||
failed: number;
|
||||
metrics: number;
|
||||
metrics_with_z: number;
|
||||
high: number;
|
||||
low: number;
|
||||
fhir_eegs: number;
|
||||
fhir_metrics: number;
|
||||
}
|
||||
|
||||
/** The analysis of one EDF (and its ADOS-2 report) that the server did without storing anything:
|
||||
* a `$resumen-tea`-shaped FHIR bundle and the notices about what could not be read. */
|
||||
export interface EegPreview {
|
||||
bundle: unknown;
|
||||
avisos: string[];
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<h3>Alcance del análisis</h3>
|
||||
<mat-radio-group aria-label="Alcance del análisis" [ngModel]="scope()" (ngModelChange)="scope.set($event)" [disabled]="busy()">
|
||||
<mat-radio-button value="pending">Pendientes</mat-radio-button>
|
||||
<mat-radio-button value="limit">Primeros N</mat-radio-button>
|
||||
<mat-radio-button value="selected">EEGs elegidos</mat-radio-button>
|
||||
</mat-radio-group>
|
||||
@if (scope() === 'limit') {
|
||||
<div class="controls"><label>Cantidad <input type="number" min="1" step="1" [ngModel]="limit()" (ngModelChange)="limit.set($event)" [disabled]="busy()" /></label></div>
|
||||
}
|
||||
@if (scope() === 'selected') {
|
||||
<app-eeg-picker [(selected)]="selected" [revision]="revision()" [disabled]="busy()" />
|
||||
}
|
||||
<div class="controls">
|
||||
<button mat-flat-button type="button" [disabled]="!canAnalyze()" (click)="analyze()">{{ starting() ? 'Iniciando…' : 'Analizar' }}</button>
|
||||
<button mat-stroked-button type="button" [disabled]="busy()" (click)="recalculate()">{{ recalculating() ? 'Solicitando…' : 'Ejecutar ciclo de indicadores' }}</button>
|
||||
</div>
|
||||
@if (actionError()) { <p role="alert">{{ actionError() }}</p> }
|
||||
@if (cycleMessage()) { <p role="status">{{ cycleMessage() }}</p> }
|
||||
@if (loading()) { <p role="status">Cargando análisis…</p> }
|
||||
@if (jobError()) {
|
||||
<p role="alert">{{ jobError() }}</p>
|
||||
<button mat-button type="button" [disabled]="loading()" (click)="refreshJobs()">Volver a consultar</button>
|
||||
} @else if (!loading() && !job()) { <p>Todavía no hay análisis de EEG.</p> }
|
||||
|
||||
@if (job(); as current) {
|
||||
<h3>Último análisis · {{ states[current.estado] }}</h3>
|
||||
<app-run-monitor kind="analyze" [jobId]="current.id" [running]="current.estado === 'en_curso'" />
|
||||
@if (current.summary; as summary) {
|
||||
<dl>
|
||||
<div><dt>Pendientes</dt><dd>{{ summary.pending }}</dd></div>
|
||||
<div><dt>Válidos</dt><dd>{{ summary.valid }}</dd></div>
|
||||
<div><dt>No válidos</dt><dd>{{ summary.not_valid }}</dd></div>
|
||||
<div><dt>Fallidos</dt><dd>{{ summary.failed }}</dd></div>
|
||||
</dl>
|
||||
}
|
||||
@if (current.error) { <p role="alert">{{ current.error }}</p> }
|
||||
@if (current.salida) {
|
||||
<details><summary>Ver últimas líneas de salida</summary><pre>{{ current.salida }}</pre></details>
|
||||
}
|
||||
}
|
||||
|
||||
<details class="upload">
|
||||
<summary>Subir EDF</summary>
|
||||
<div class="controls">
|
||||
<label>Archivo EDF <input #edf type="file" accept=".edf" [disabled]="uploading()" (change)="chooseFile($event)" /></label>
|
||||
@if (!storeless()) {
|
||||
<label>ID del paciente (opcional) <input type="number" min="0" step="1" [ngModel]="patientId()" (ngModelChange)="patientId.set($event)" [disabled]="uploading()" /></label>
|
||||
}
|
||||
@if (file()) {
|
||||
<label>Informe ADOS-2 (PDF, opcional) <input type="file" accept=".pdf" [disabled]="uploading()" (change)="chooseAdos2($event)" /></label>
|
||||
<mat-checkbox [checked]="storeless()" [disabled]="uploading() || ados2File() !== null" (change)="viewOnly.set($event.checked)">Solo ver resultados, sin guardar en la base de datos</mat-checkbox>
|
||||
}
|
||||
@if (storeless()) {
|
||||
<button mat-flat-button type="button" [disabled]="!canPreview()" (click)="preview()">{{ uploading() ? 'Analizando…' : 'Ver resultados' }}</button>
|
||||
} @else {
|
||||
<button mat-stroked-button type="button" [disabled]="!canUpload()" (click)="upload(edf)">{{ uploading() ? 'Subiendo…' : 'Subir EDF' }}</button>
|
||||
}
|
||||
</div>
|
||||
@if (uploadError()) { <p role="alert">{{ uploadError() }}</p> }
|
||||
@if (uploaded(); as result) {
|
||||
<p role="status">EEG {{ result.eeg_id ?? '—' }} · Laboratorio {{ result.lab_id ?? '—' }} · {{ result.created ? 'Creado' : 'Actualizado' }}</p>
|
||||
}
|
||||
</details>
|
||||
@@ -0,0 +1,4 @@
|
||||
dl { display: flex; flex-wrap: wrap; gap: 1rem; }
|
||||
dd { margin: 0; font-weight: 600; }
|
||||
pre { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 16rem; overflow: auto; }
|
||||
.upload { border-top: 1px solid var(--mat-sys-outline-variant); margin-block-start: 1rem; padding-block: .75rem; }
|
||||
@@ -0,0 +1,194 @@
|
||||
/** Pins analysis, conflict recovery and EDF uploads against mocked HTTP jobs and catalog rows. */
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { of } from 'rxjs';
|
||||
import { TeaPacienteDetalle, TeaSeguimientoService } from '../../../features/indicadores/tea-seguimiento.service';
|
||||
import { AnalyzeJob } from '../../api/tea-eeg.types';
|
||||
import { AnalyzeStepComponent } from './analyze-step';
|
||||
|
||||
const jobs = '/governance/tea/eeg/analyze-jobs';
|
||||
const progress = '/governance/tea/jobs/analyze/a1/progress';
|
||||
const upload = '/governance/tea/eeg/upload';
|
||||
const preview = '/governance/tea/eeg/preview';
|
||||
|
||||
// A running job discovered on conflict or returned by a successful start.
|
||||
const running: AnalyzeJob = {
|
||||
id: 'a1', iniciado: '2026-11-23T00:00:00Z', estado: 'en_curso', codigo: null,
|
||||
salida: '', error: '', cluster: null, ids: null, summary: null,
|
||||
};
|
||||
|
||||
describe('AnalyzeStepComponent', () => {
|
||||
let http: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
/** Creates the step with a remote choice and an empty analysis history. */
|
||||
function create() {
|
||||
const fixture = TestBed.createComponent(AnalyzeStepComponent);
|
||||
fixture.componentRef.setInput('choice', { mode: 'remote', scheduler: 'tcp://equipo:8786' });
|
||||
fixture.detectChanges();
|
||||
http.expectOne(jobs).flush([]);
|
||||
return fixture;
|
||||
}
|
||||
|
||||
/** Fails if the limit or cluster is omitted, polling stops early, or final results are hidden. */
|
||||
it('starts a bounded run and displays its final summary and tail', () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
step.scope.set('limit');
|
||||
step.limit.set(5);
|
||||
step.analyze();
|
||||
const request = http.expectOne(jobs);
|
||||
expect(request.request.body).toEqual({ limit: 5, cluster: { mode: 'remote', scheduler: 'tcp://equipo:8786' } });
|
||||
request.flush(running);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(progress).flush(null, { status: 404, statusText: 'Not Found' });
|
||||
vi.advanceTimersByTime(2000);
|
||||
const runningProgress = http.expectOne(progress);
|
||||
http.expectOne(`${jobs}/a1`).flush({
|
||||
...running, estado: 'completado', codigo: 0, salida: 'EEG 14 procesado',
|
||||
summary: { pending: 1, valid: 2, not_valid: 1, failed: 1 },
|
||||
});
|
||||
fixture.detectChanges();
|
||||
expect(runningProgress.cancelled).toBe(true);
|
||||
http.expectOne(progress).flush(null, { status: 404, statusText: 'Not Found' });
|
||||
expect(fixture.nativeElement.textContent).toContain('EEG 14 procesado');
|
||||
expect(fixture.nativeElement.querySelector('dd').textContent).toBe('1');
|
||||
vi.advanceTimersByTime(2000);
|
||||
http.expectNone(`${jobs}/a1`);
|
||||
fixture.destroy();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
/** Fails if pending scope requests a full rerun, a conflict hides the active job, or an unknown EEG is silent. */
|
||||
it('recovers the active job on conflict and explains unknown EEGs', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
step.analyze();
|
||||
const missing = http.expectOne(jobs);
|
||||
expect(missing.request.body).toEqual({ cluster: { mode: 'remote', scheduler: 'tcp://equipo:8786' } });
|
||||
missing.flush(null, { status: 404, statusText: 'Not Found' });
|
||||
expect(step.actionError()).toContain('No se encontró');
|
||||
|
||||
step.analyze();
|
||||
http.expectOne(jobs).flush(null, { status: 409, statusText: 'Conflict' });
|
||||
http.expectOne(jobs).flush([running]);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(progress).flush(null, { status: 404, statusText: 'Not Found' });
|
||||
expect(fixture.nativeElement.textContent).toContain('Ya hay un análisis de EEG en curso.');
|
||||
expect(step.canAnalyze()).toBe(false);
|
||||
});
|
||||
|
||||
/** Fails if an invalid EDF gets selected, or a successful upload fails to tick its catalog row. */
|
||||
it('keeps a failed EDF retryable and ticks the successfully uploaded EEG', async () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
const input: HTMLInputElement = fixture.nativeElement.querySelector('input[type=file]');
|
||||
step.file.set(new File(['edf'], 'estudio.edf'));
|
||||
step.patientId.set(42);
|
||||
step.upload(input);
|
||||
const failed = http.expectOne(upload);
|
||||
expect(failed.request.body.get('patient_id')).toBe('42');
|
||||
failed.flush({ error: 'EDF inválido' }, { status: 400, statusText: 'Bad Request' });
|
||||
expect(step.uploadError()).toBe('EDF inválido');
|
||||
expect(step.selected()).toEqual([]);
|
||||
expect(step.canUpload()).toBe(true);
|
||||
|
||||
step.upload(input);
|
||||
http.expectOne(upload).flush({ eeg_id: '8', lab_id: 'LAB-8', created: true });
|
||||
fixture.detectChanges();
|
||||
http.expectOne((req) => req.url === '/governance/tea/eeg').flush([
|
||||
{ id: 8, lab_id: 'LAB-8', patient_id: 42, study_date: null, valid: null, analysed: false },
|
||||
]);
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('input[type=checkbox]').checked).toBe(true);
|
||||
expect(fixture.nativeElement.textContent).toContain('Creado');
|
||||
});
|
||||
|
||||
/** Fails if the analysis by selection stops sending UUID ids, which real EEGs carry, as text. */
|
||||
it('analyses chosen EEGs by their UUID ids', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
const uuid = 'ed257fbd-61d5-4c9c-bb72-00c4ec550961';
|
||||
step.scope.set('selected');
|
||||
step.selected.set([uuid]);
|
||||
expect(step.canAnalyze()).toBe(true);
|
||||
step.analyze();
|
||||
const request = http.expectOne('/governance/tea/eeg/analyze-jobs');
|
||||
expect(request.request.body.ids).toEqual([uuid]);
|
||||
request.flush({ id: 'j1', estado: 'en_curso', ids: [uuid], cluster: null, summary: null, salida: '', error: '', codigo: null, iniciado: '' });
|
||||
});
|
||||
|
||||
/** Fails if the TEA indicator cycle loses the selected cluster. */
|
||||
it('requests the indicator cycle on the selected cluster', () => {
|
||||
const fixture = create();
|
||||
fixture.componentInstance.recalculate();
|
||||
const request = http.expectOne('/reportes/indicadores/tea/recalcular');
|
||||
expect(request.request.body).toEqual({ cluster: { mode: 'remote', scheduler: 'tcp://equipo:8786' } });
|
||||
request.flush({ pendiente: true });
|
||||
expect(fixture.componentInstance.cycleMessage()).toContain('Pendiente');
|
||||
});
|
||||
|
||||
const edf = () => new File(['x'], 'estudio.edf');
|
||||
const choose = (step: AnalyzeStepComponent, file: File | null, ados2: File | null = null) => {
|
||||
step.chooseFile({ target: { files: { item: () => file } } } as unknown as Event);
|
||||
if (ados2) step.chooseAdos2({ target: { files: { item: () => ados2 } } } as unknown as Event);
|
||||
};
|
||||
|
||||
/** Fails if choosing an ADOS-2 report still offers a stored upload, or if the report is sent with the wrong field. */
|
||||
it('sends an EDF and its ADOS-2 report only to the preview and opens the record', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
const detalle = { id_seudonimo: 'vista-previa' };
|
||||
vi.spyOn(TestBed.inject(TeaSeguimientoService), 'vistaPrevia').mockReturnValue(of(detalle as unknown as TeaPacienteDetalle));
|
||||
const open = vi.spyOn(TestBed.inject(MatDialog), 'open').mockReturnValue(undefined as never);
|
||||
choose(step, edf(), new File(['p'], 'ados2.pdf'));
|
||||
expect(step.storeless()).toBe(true);
|
||||
step.preview();
|
||||
const request = http.expectOne(preview);
|
||||
expect((request.request.body as FormData).get('edf')).toBeInstanceOf(File);
|
||||
expect(((request.request.body as FormData).get('ados2') as File).name).toBe('ados2.pdf');
|
||||
request.flush({ bundle: { resourceType: 'Bundle' }, avisos: ['aviso'] });
|
||||
expect(open.mock.calls[0][1]?.data).toEqual({ detalle, avisos: ['aviso'], archivo: 'estudio.edf' });
|
||||
http.expectNone(upload);
|
||||
expect(step.uploaded()).toBeNull();
|
||||
});
|
||||
|
||||
/** Fails if the stored upload stops being the default for a lone EDF, or the view-only box does not switch the button. */
|
||||
it('keeps the stored upload unless the EDF is for viewing only', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
choose(step, edf());
|
||||
expect(step.storeless()).toBe(false);
|
||||
step.viewOnly.set(true);
|
||||
expect(step.storeless()).toBe(true);
|
||||
expect(step.canPreview()).toBe(true);
|
||||
choose(step, null);
|
||||
expect(step.viewOnly()).toBe(false);
|
||||
});
|
||||
|
||||
/** Fails if a non-PDF report can be sent, or a server refusal is not shown. */
|
||||
it('rejects a report that is not a PDF and shows the preview error', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
choose(step, edf(), new File(['p'], 'ados2.txt'));
|
||||
expect(step.canPreview()).toBe(false);
|
||||
expect(step.uploadError()).toBe('Elige el informe ADOS-2 en PDF.');
|
||||
choose(step, edf(), new File(['p'], 'ados2.pdf'));
|
||||
step.preview();
|
||||
http.expectOne(preview).flush({ error: 'EDF ilegible' }, { status: 400, statusText: 'Bad Request' });
|
||||
expect(step.uploadError()).toBe('EDF ilegible');
|
||||
expect(step.uploading()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
import { Component, DestroyRef, OnInit, computed, effect, inject, input, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { MatRadioModule } from '@angular/material/radio';
|
||||
import { finalize, exhaustMap, catchError, EMPTY, map, switchMap, timer } from 'rxjs';
|
||||
import { apiErrorMessage } from '../../../connect/api/api.types';
|
||||
import { TeaEegApi } from '../../api/tea-eeg.api';
|
||||
import { AnalyzeBody, AnalyzeJob, ClusterChoice, EegId, EegUploadResult, JobState } from '../../api/tea-eeg.types';
|
||||
import { TeaSeguimientoService } from '../../../features/indicadores/tea-seguimiento.service';
|
||||
import { EegPicker } from '../eeg-picker/eeg-picker';
|
||||
import { EegPreviewData, EegPreviewDialog } from '../eeg-preview-dialog/eeg-preview-dialog';
|
||||
import { RunMonitorComponent } from '../run-monitor/run-monitor';
|
||||
|
||||
@Component({
|
||||
selector: 'app-analyze-step',
|
||||
imports: [EegPicker, FormsModule, MatButtonModule, MatCheckboxModule, MatRadioModule, RunMonitorComponent],
|
||||
templateUrl: './analyze-step.html',
|
||||
styleUrls: ['../eeg-step.scss', './analyze-step.scss'],
|
||||
})
|
||||
export class AnalyzeStepComponent implements OnInit {
|
||||
private readonly api = inject(TeaEegApi);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly dialog = inject(MatDialog);
|
||||
private readonly tea = inject(TeaSeguimientoService);
|
||||
readonly choice = input<ClusterChoice>({ mode: 'auto' });
|
||||
readonly scope = signal<'pending' | 'limit' | 'selected'>('pending');
|
||||
readonly limit = signal<number | null>(10);
|
||||
readonly selected = signal<EegId[]>([]);
|
||||
readonly revision = signal(0);
|
||||
readonly jobs = signal<AnalyzeJob[]>([]);
|
||||
readonly job = computed(() => this.jobs().find((job) => job.estado === 'en_curso') ?? this.jobs()[0]);
|
||||
private readonly runningId = computed(() => this.job()?.estado === 'en_curso' ? this.job()?.id : undefined);
|
||||
readonly loading = signal(false);
|
||||
readonly starting = signal(false);
|
||||
readonly recalculating = signal(false);
|
||||
readonly jobError = signal('');
|
||||
readonly actionError = signal('');
|
||||
readonly cycleMessage = signal('');
|
||||
readonly busy = computed(() => this.loading() || this.starting() || this.recalculating() || !!this.runningId());
|
||||
readonly canAnalyze = computed(() => !this.busy() && (
|
||||
this.scope() === 'pending' ||
|
||||
(this.scope() === 'selected' ? this.selected().length > 0 : positiveInteger(this.limit()))
|
||||
));
|
||||
readonly file = signal<File | null>(null);
|
||||
readonly patientId = signal<number | null>(null);
|
||||
readonly uploading = signal(false);
|
||||
readonly uploadError = signal('');
|
||||
readonly uploaded = signal<EegUploadResult | null>(null);
|
||||
readonly canUpload = computed(() => !this.uploading() && /\.edf$/i.test(this.file()?.name ?? '') &&
|
||||
(this.patientId() === null || (Number.isSafeInteger(this.patientId()) && this.patientId()! >= 0)));
|
||||
readonly ados2File = signal<File | null>(null);
|
||||
readonly viewOnly = signal(false);
|
||||
/** An ADOS-2 report is never stored (there is no patient to attach it to), so it always means a view-only analysis. */
|
||||
readonly storeless = computed(() => this.viewOnly() || this.ados2File() !== null);
|
||||
readonly canPreview = computed(() => !this.uploading() && /\.edf$/i.test(this.file()?.name ?? '') &&
|
||||
(this.ados2File() === null || /\.pdf$/i.test(this.ados2File()!.name)));
|
||||
readonly states: Record<JobState, string> = {
|
||||
en_curso: 'En curso', completado: 'Completado', entrenado_sin_promover: 'Completado',
|
||||
fallido: 'Falló', interrumpido: 'Interrumpido',
|
||||
};
|
||||
|
||||
constructor() {
|
||||
effect((cleanup) => {
|
||||
const id = this.runningId();
|
||||
if (!id) return;
|
||||
const polling = timer(2000, 2000).pipe(exhaustMap(() => this.api.analyzeJob(id).pipe(
|
||||
catchError((error) => {
|
||||
this.jobError.set(apiErrorMessage(error, error.status === 404
|
||||
? 'No se encontró el trabajo de análisis.' : 'No se pudo consultar el trabajo de análisis.'));
|
||||
if (error.status === 404) this.jobs.update((jobs) => jobs.filter((job) => job.id !== id));
|
||||
return EMPTY;
|
||||
}),
|
||||
))).subscribe((job) => {
|
||||
this.jobError.set('');
|
||||
this.storeJob(job);
|
||||
if (job.estado !== 'en_curso') this.revision.update((value) => value + 1);
|
||||
});
|
||||
cleanup(() => polling.unsubscribe());
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.refreshJobs();
|
||||
}
|
||||
|
||||
refreshJobs(): void {
|
||||
if (this.loading()) return;
|
||||
this.loading.set(true);
|
||||
this.jobError.set('');
|
||||
this.api.analyzeJobs().pipe(
|
||||
takeUntilDestroyed(this.destroyRef), finalize(() => this.loading.set(false)),
|
||||
).subscribe({
|
||||
next: (jobs) => this.jobs.set(jobs),
|
||||
error: (error) => this.jobError.set(apiErrorMessage(error, 'No se pudieron cargar los análisis.')),
|
||||
});
|
||||
}
|
||||
|
||||
analyze(): void {
|
||||
if (!this.canAnalyze()) return;
|
||||
const body: AnalyzeBody = { cluster: this.choice() };
|
||||
if (this.scope() === 'limit') body.limit = this.limit()!;
|
||||
if (this.scope() === 'selected') body.ids = this.selected();
|
||||
this.starting.set(true);
|
||||
this.actionError.set('');
|
||||
this.api.startAnalyzeJob(body).pipe(
|
||||
takeUntilDestroyed(this.destroyRef), finalize(() => this.starting.set(false)),
|
||||
).subscribe({
|
||||
next: (job) => this.storeJob(job),
|
||||
error: (error) => {
|
||||
const message = error.status === 409 ? 'Ya hay un análisis de EEG en curso.'
|
||||
: error.status === 404 ? 'No se encontró uno de los EEGs elegidos.' : 'No se pudo iniciar el análisis.';
|
||||
this.actionError.set(apiErrorMessage(error, message));
|
||||
if (error.status === 409) this.refreshJobs();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
recalculate(): void {
|
||||
if (this.busy()) return;
|
||||
this.recalculating.set(true);
|
||||
this.actionError.set('');
|
||||
this.cycleMessage.set('');
|
||||
this.api.recalculateTeaIndicators(this.choice()).pipe(
|
||||
takeUntilDestroyed(this.destroyRef), finalize(() => this.recalculating.set(false)),
|
||||
).subscribe({
|
||||
next: ({ pendiente }) => this.cycleMessage.set(pendiente ? 'Ciclo de indicadores solicitado. Pendiente de actualización.' : 'Solicitud de indicadores recibida.'),
|
||||
error: (error) => this.actionError.set(apiErrorMessage(error, 'No se pudo ejecutar el ciclo de indicadores.')),
|
||||
});
|
||||
}
|
||||
|
||||
chooseFile(event: Event): void {
|
||||
this.file.set((event.target as HTMLInputElement).files?.item(0) ?? null);
|
||||
this.uploaded.set(null);
|
||||
this.uploadError.set('');
|
||||
if (this.file() && !/\.edf$/i.test(this.file()!.name)) this.uploadError.set('Elige un archivo .edf.');
|
||||
if (!this.file()) { this.ados2File.set(null); this.viewOnly.set(false); }
|
||||
}
|
||||
|
||||
chooseAdos2(event: Event): void {
|
||||
const file = (event.target as HTMLInputElement).files?.item(0) ?? null;
|
||||
this.ados2File.set(file);
|
||||
this.uploadError.set(file && !/\.pdf$/i.test(file.name) ? 'Elige el informe ADOS-2 en PDF.' : '');
|
||||
}
|
||||
|
||||
/** Analyses the chosen EDF (and the ADOS-2 report) without storing anything and opens the record. */
|
||||
preview(): void {
|
||||
const file = this.file();
|
||||
if (!file || !this.canPreview()) return;
|
||||
this.uploading.set(true);
|
||||
this.uploadError.set('');
|
||||
this.api.previewEeg(file, this.ados2File() ?? undefined).pipe(
|
||||
switchMap((result) => this.tea.vistaPrevia(result.bundle).pipe(map((detalle) => ({ detalle, avisos: result.avisos })))),
|
||||
takeUntilDestroyed(this.destroyRef), finalize(() => this.uploading.set(false)),
|
||||
).subscribe({
|
||||
next: ({ detalle, avisos }) => {
|
||||
const data: EegPreviewData = { detalle, avisos, archivo: file.name };
|
||||
this.dialog.open(EegPreviewDialog, { data, maxWidth: '96vw', width: '1100px' });
|
||||
},
|
||||
error: (error) => this.uploadError.set(apiErrorMessage(error, 'No se pudo analizar el EDF.')),
|
||||
});
|
||||
}
|
||||
|
||||
upload(fileInput: HTMLInputElement): void {
|
||||
const file = this.file();
|
||||
if (!file || !this.canUpload()) return;
|
||||
this.uploading.set(true);
|
||||
this.uploadError.set('');
|
||||
this.uploaded.set(null);
|
||||
this.api.uploadEeg(file, this.patientId() ?? undefined).pipe(
|
||||
takeUntilDestroyed(this.destroyRef), finalize(() => this.uploading.set(false)),
|
||||
).subscribe({
|
||||
next: (result) => {
|
||||
this.uploaded.set(result);
|
||||
// The catalog lists canonical numeric keys as numbers and any other key (a UUID) as text.
|
||||
const rawId = result.eeg_id;
|
||||
const id = typeof rawId === 'string' && /^\d+$/.test(rawId) && String(Number(rawId)) === rawId
|
||||
? Number(rawId) : rawId;
|
||||
if (id !== null) this.selected.update((ids) => ids.includes(id) ? ids : [...ids, id]);
|
||||
this.scope.set('selected');
|
||||
this.revision.update((value) => value + 1);
|
||||
this.file.set(null);
|
||||
fileInput.value = '';
|
||||
},
|
||||
error: (error) => this.uploadError.set(apiErrorMessage(error, 'No se pudo subir el EDF.')),
|
||||
});
|
||||
}
|
||||
|
||||
private storeJob(job: AnalyzeJob): void {
|
||||
this.jobs.update((jobs) => [job, ...jobs.filter((item) => item.id !== job.id)]);
|
||||
}
|
||||
}
|
||||
|
||||
function positiveInteger(value: number | null): boolean {
|
||||
return value !== null && Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<div class="controls">
|
||||
<label>Escenario
|
||||
<select [ngModel]="scenario()" (ngModelChange)="chooseScenario($event)" [disabled]="!scenarios().length">
|
||||
<option value="">Elige un escenario</option>
|
||||
@for (item of scenarios(); track item) { <option [value]="item">{{ item }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
<label>Versión
|
||||
<select [ngModel]="version()" (ngModelChange)="chooseVersion($event)" [disabled]="!versionOptions().length">
|
||||
<option [ngValue]="null">Elige una versión</option>
|
||||
@for (item of versionOptions(); track item) { <option [ngValue]="item">{{ item }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
<label>Métrica
|
||||
<select [ngModel]="metric()" (ngModelChange)="metric.set($event)" [disabled]="!metrics.hasValue() || !metrics.value().length">
|
||||
<option value="">Elige una métrica</option>
|
||||
@if (metrics.hasValue()) {
|
||||
@for (item of metrics.value(); track item) { <option [value]="item">{{ item }}</option> }
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
<span tabindex="0" matTooltip="Próximamente"><button mat-stroked-button disabled>Probar en notebook</button></span>
|
||||
</div>
|
||||
@if (versions.isLoading() || metrics.isLoading() || curve.isLoading()) { <p role="status">Cargando línea base…</p> }
|
||||
@if (versions.error()) {
|
||||
<p role="alert">No se pudieron cargar las versiones.</p><button mat-button (click)="versions.reload()">Reintentar</button>
|
||||
} @else if (versions.hasValue() && !scenarios().length) { <p>No hay versiones de escenarios EEG.</p> }
|
||||
@if (metrics.error()) {
|
||||
<p role="alert">No se pudieron cargar las métricas de la línea base.</p><button mat-button (click)="metrics.reload()">Reintentar</button>
|
||||
} @else if (metrics.hasValue() && !metrics.value().length) { <p>Esta versión no tiene métricas con curvas.</p> }
|
||||
@if (curve.error()) {
|
||||
<p role="alert">No se pudo cargar la curva.</p><button mat-button (click)="curve.reload()">Reintentar</button>
|
||||
} @else if (curve.hasValue() && !figure()) { <p>La curva no tiene datos.</p> }
|
||||
|
||||
@if (figure(); as chart) {
|
||||
<app-plotly-chart [figure]="chart" [showNotes]="false" label="Curva por edad con mediana, bandas P5–P95 y P25–P75 y EEGs elegidos" />
|
||||
@if (curve.hasValue()) {
|
||||
@let data = curve.value();
|
||||
<details>
|
||||
<summary>Ver valores de la curva</summary>
|
||||
<div class="table-scroll">
|
||||
<table aria-label="Valores de la línea base">
|
||||
<thead><tr><th>Edad (meses)</th><th>P5</th><th>P25</th><th>Mediana</th><th>P75</th><th>P95</th></tr></thead>
|
||||
<tbody>
|
||||
@for (age of data.edad_meses; track $index) {
|
||||
<tr><td>{{ age }}</td><td>{{ data.p5[$index] }}</td><td>{{ data.p25[$index] }}</td>
|
||||
<td>{{ data.mediana[$index] }}</td><td>{{ data.p75[$index] }}</td><td>{{ data.p95[$index] }}</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
<h3>EEGs para comparar</h3>
|
||||
<app-eeg-picker [(selected)]="selected" />
|
||||
@if (eegMetrics.isLoading()) { <p role="status">Cargando métricas de los EEGs…</p> }
|
||||
@else if (eegMetrics.error()) {
|
||||
<p role="alert">No se pudieron cargar las métricas de los EEGs elegidos.</p>
|
||||
<button mat-button (click)="eegMetrics.reload()">Reintentar</button>
|
||||
} @else if (selected().length && metric() && !points().length) { <p>No hay EEGs elegidos con edad y valor para esta métrica.</p> }
|
||||
@if (points().length) {
|
||||
<details>
|
||||
<summary>Ver valores de los EEGs elegidos</summary>
|
||||
<div class="table-scroll">
|
||||
<table aria-label="Valores de los EEGs">
|
||||
<thead><tr><th>EEG</th><th>Edad (meses)</th><th>Valor</th><th>Clasificación</th></tr></thead>
|
||||
<tbody>
|
||||
@for (point of points(); track $index) {
|
||||
<tr><td>{{ point.id }}</td><td>{{ point.age }}</td><td>{{ point.value }}</td><td>{{ point.label }}</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
app-plotly-chart { --plot-height: 400px; --plot-min-width: 360px; }
|
||||
details { margin-block: .5rem; }
|
||||
@@ -0,0 +1,77 @@
|
||||
/** Pins version filtering, percentile curves and EEG overlays with mocked HTTP responses. */
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime';
|
||||
import { BaselineCheckComponent } from './baseline-check';
|
||||
|
||||
const baseline = '/governance/tea/baselines/eeg-posterior-rhythm/3';
|
||||
|
||||
describe('BaselineCheckComponent', () => {
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [
|
||||
provideHttpClient(), provideHttpClientTesting(),
|
||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve({ react: vi.fn(), purge: vi.fn() }) },
|
||||
] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
/** Sets up an EEG version, an unrelated TEA version and an empty catalog page. */
|
||||
async function create() {
|
||||
const fixture = TestBed.createComponent(BaselineCheckComponent);
|
||||
fixture.detectChanges();
|
||||
const versions = http.expectOne((req) => req.url === '/governance/model-versions');
|
||||
expect(versions.request.params.get('domain')).toBe('tea');
|
||||
versions.flush({ model_versions: [
|
||||
{ version: '3', tags: { scenario: 'eeg-posterior-rhythm' } },
|
||||
{ version: '9', tags: { scenario: 'riesgo-tea' } },
|
||||
] });
|
||||
http.expectOne((req) => req.url === '/governance/tea/eeg').flush([]);
|
||||
await fixture.whenStable();
|
||||
const step = fixture.componentInstance;
|
||||
expect(step.scenarios()).toEqual(['eeg-posterior-rhythm']);
|
||||
step.chooseScenario('eeg-posterior-rhythm');
|
||||
step.chooseVersion(3);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(`${baseline}/metrics`).flush(['peak']);
|
||||
await fixture.whenStable();
|
||||
step.metric.set('peak');
|
||||
return fixture;
|
||||
}
|
||||
|
||||
/** Fails if the two percentile bands, medians or labeled high/low/inside points are lost. */
|
||||
it('draws the age curve and classifies the selected EEG values', async () => {
|
||||
const fixture = await create();
|
||||
const step = fixture.componentInstance;
|
||||
step.selected.set([8]);
|
||||
fixture.detectChanges();
|
||||
const curve = http.expectOne((req) => req.url === `${baseline}/curve`);
|
||||
expect(curve.request.params.get('metric')).toBe('peak');
|
||||
curve.flush({ edad_meses: [24, 36], p5: [1, 2], p25: [2, 3], mediana: [3, 4], metric: 'peak', p75: [4, 5], p95: [5, 6] });
|
||||
http.expectOne('/governance/tea/eeg/8/metrics').flush({ eeg_id: 8, age_months: 30, metrics: [
|
||||
{ name: 'peak', value: 0.5, outside: -1 },
|
||||
{ name: 'peak', value: 3, outside: 0 },
|
||||
{ name: 'peak', value: 8, outside: 1 },
|
||||
{ name: 'other', value: 7, outside: 1 },
|
||||
] });
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
const traces = step.figure()?.data;
|
||||
expect(traces?.map((trace) => trace['name'])).toEqual(['P5–P95', 'P25–P75', 'Mediana', 'Bajo', 'Dentro', 'Alto']);
|
||||
expect(traces?.[5]).toMatchObject({ x: [30], y: [8], marker: { symbol: 'triangle-up' } });
|
||||
expect(fixture.nativeElement.textContent).toContain('Ver valores de la curva');
|
||||
});
|
||||
|
||||
/** Fails if a missing curve appears empty without surfacing the HTTP error and retry control. */
|
||||
it('shows a retry when a curve is unavailable', async () => {
|
||||
const fixture = await create();
|
||||
fixture.detectChanges();
|
||||
http.expectOne((req) => req.url === `${baseline}/curve`).flush(null, { status: 404, statusText: 'Not Found' });
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('No se pudo cargar la curva.');
|
||||
expect(fixture.nativeElement.textContent).toContain('Reintentar');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Component, ElementRef, computed, inject, model, signal } from '@angular/core';
|
||||
import { rxResource } from '@angular/core/rxjs-interop';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { forkJoin } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../shared/plotly/plotly-chart';
|
||||
import { GovernanceApi } from '../../api/governance.api';
|
||||
import { TeaEegApi } from '../../api/tea-eeg.api';
|
||||
import { EegId, EegMetrics } from '../../api/tea-eeg.types';
|
||||
import { EegPicker } from '../eeg-picker/eeg-picker';
|
||||
import { baselineFigure, overlayPoints } from './baseline-figure';
|
||||
|
||||
@Component({
|
||||
selector: 'app-baseline-check',
|
||||
imports: [EegPicker, FormsModule, MatButtonModule, MatTooltipModule, PlotlyChart],
|
||||
templateUrl: './baseline-check.html',
|
||||
styleUrls: ['../eeg-step.scss', './baseline-check.scss'],
|
||||
})
|
||||
export class BaselineCheckComponent {
|
||||
private readonly api = inject(TeaEegApi);
|
||||
private readonly governance = inject(GovernanceApi);
|
||||
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
readonly scenario = signal('');
|
||||
readonly version = signal<number | null>(null);
|
||||
readonly metric = signal('');
|
||||
readonly selected = model<EegId[]>([]);
|
||||
readonly versions = rxResource({
|
||||
stream: () => this.governance.listModelVersions({ domain: 'tea' }),
|
||||
});
|
||||
readonly eegVersions = computed(() => this.versions.hasValue()
|
||||
? this.versions.value().model_versions.filter((version) => version.tags.scenario?.startsWith('eeg-')) : []);
|
||||
readonly scenarios = computed(() => [...new Set(this.eegVersions().map((version) => version.tags.scenario!))].sort());
|
||||
readonly versionOptions = computed(() => [...new Set(this.eegVersions()
|
||||
.filter((version) => version.tags.scenario === this.scenario())
|
||||
.map((version) => Number(version.version)).filter((version) => Number.isSafeInteger(version) && version > 0))]
|
||||
.sort((a, b) => b - a));
|
||||
readonly metrics = rxResource({
|
||||
params: () => {
|
||||
const version = this.version();
|
||||
return version === null ? undefined : { scenario: this.scenario(), version };
|
||||
},
|
||||
stream: ({ params }) => this.api.baselineMetrics(params.scenario, params.version),
|
||||
});
|
||||
readonly curve = rxResource({
|
||||
params: () => {
|
||||
const version = this.version();
|
||||
const metric = this.metric();
|
||||
return version === null || !metric ? undefined : { scenario: this.scenario(), version, metric };
|
||||
},
|
||||
stream: ({ params }) => this.api.baselineCurve(params.scenario, params.version, params.metric),
|
||||
});
|
||||
readonly eegMetrics = rxResource({
|
||||
params: () => this.selected().length && this.metric() ? this.selected() : undefined,
|
||||
stream: ({ params }) => forkJoin(params.map((id) => this.api.eegMetrics(id))),
|
||||
defaultValue: [] as EegMetrics[],
|
||||
});
|
||||
readonly points = computed(() => overlayPoints(this.eegMetrics.hasValue() ? this.eegMetrics.value() : [], this.metric()));
|
||||
readonly figure = computed(() => {
|
||||
if (!this.curve.hasValue() || !this.curve.value().edad_meses.length) return null;
|
||||
const style = getComputedStyle(this.host.nativeElement);
|
||||
return baselineFigure(this.curve.value(), this.points(), (token) => style.getPropertyValue(`--eeg-${token}`).trim(), style.color);
|
||||
});
|
||||
|
||||
chooseScenario(scenario: string): void {
|
||||
this.scenario.set(scenario);
|
||||
this.chooseVersion(null);
|
||||
}
|
||||
|
||||
chooseVersion(version: number | null): void {
|
||||
this.version.set(version);
|
||||
this.metric.set('');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { PlotlyFigure } from '../../../features/indicadores/indicadores.models';
|
||||
import { BaselineCurve, EegMetrics } from '../../api/tea-eeg.types';
|
||||
|
||||
const OUTSIDE = [
|
||||
{ flag: -1, label: 'Bajo', color: 'blue', symbol: 'triangle-down' },
|
||||
{ flag: 0, label: 'Dentro', color: 'purple', symbol: 'circle' },
|
||||
{ flag: 1, label: 'Alto', color: 'vermilion', symbol: 'triangle-up' },
|
||||
{ flag: null, label: 'Sin clasificación', color: 'axis', symbol: 'diamond-open' },
|
||||
] as const;
|
||||
|
||||
export function overlayPoints(eegs: EegMetrics[], metric: string) {
|
||||
return eegs.flatMap((eeg) => eeg.age_months === null ? [] : eeg.metrics
|
||||
.filter((item) => item.name === metric && Number.isFinite(item.value))
|
||||
.map((item) => ({
|
||||
id: eeg.eeg_id,
|
||||
age: eeg.age_months!,
|
||||
value: item.value,
|
||||
outside: item.outside,
|
||||
label: OUTSIDE.find((group) => group.flag === item.outside)?.label,
|
||||
})));
|
||||
}
|
||||
|
||||
export function baselineFigure(
|
||||
curve: BaselineCurve, points: ReturnType<typeof overlayPoints>, color: (token: string) => string, ink: string,
|
||||
): PlotlyFigure {
|
||||
const x = curve.edad_meses;
|
||||
const band = (low: number[], high: number[], name: string, token: string) => ({
|
||||
type: 'scatter', mode: 'lines', name, x: [...x, ...[...x].reverse()], y: [...high, ...[...low].reverse()],
|
||||
fill: 'toself', fillcolor: color(token), line: { width: 0 }, hoverinfo: 'skip',
|
||||
});
|
||||
return {
|
||||
data: [
|
||||
band(curve.p5, curve.p95, 'P5–P95', 'band-outer'),
|
||||
band(curve.p25, curve.p75, 'P25–P75', 'band-inner'),
|
||||
{ type: 'scatter', mode: 'lines', name: 'Mediana', x, y: curve.mediana, line: { color: color('blue'), width: 2 } },
|
||||
...OUTSIDE.flatMap(({ flag, label, color: token, symbol }) => {
|
||||
const group = points.filter((point) => point.outside === flag);
|
||||
return group.length ? [{
|
||||
type: 'scatter', mode: 'markers', name: label,
|
||||
x: group.map((point) => point.age), y: group.map((point) => point.value),
|
||||
text: group.map((point) => `EEG ${point.id}`), marker: { color: token === 'axis' ? ink : color(token), symbol, size: 10 },
|
||||
}] : [];
|
||||
}),
|
||||
],
|
||||
layout: {
|
||||
autosize: true, height: 400, margin: { l: 65, r: 20, t: 20, b: 100 },
|
||||
paper_bgcolor: 'transparent', plot_bgcolor: 'transparent', font: { color: ink },
|
||||
xaxis: { title: { text: 'Edad (meses)' }, showgrid: false, zeroline: false },
|
||||
yaxis: { title: { text: curve.metric }, showgrid: false, zeroline: false },
|
||||
legend: { orientation: 'h', y: -.22 },
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<section class="health">
|
||||
<div class="health__toolbar">
|
||||
<h2 class="health__title">Estado del clúster</h2>
|
||||
<span class="health__spacer"></span>
|
||||
<span class="health__latency">
|
||||
@if (latencyMs() != null) {
|
||||
Latencia: {{ latencyMs() }} ms
|
||||
} @else {
|
||||
Latencia: sin datos
|
||||
}
|
||||
</span>
|
||||
<button mat-button type="button" (click)="refresh()" [disabled]="loading()">
|
||||
<mat-icon aria-hidden="true">refresh</mat-icon>Verificar
|
||||
</button>
|
||||
<button mat-button type="button" color="primary" class="health__dashboard" [disabled]="!dashboardEnabled()" [matTooltip]="dashboardTooltip()" (click)="openDashboard()">
|
||||
<mat-icon aria-hidden="true">open_in_new</mat-icon>Abrir dashboard de Dask
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@if (loadError(); as error) {
|
||||
<p class="health__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
|
||||
}
|
||||
|
||||
<ul class="health__rows">
|
||||
@for (row of rows(); track row.key) {
|
||||
<li class="health__row" [ngClass]="'health__row--' + row.state">
|
||||
<span class="health__check">
|
||||
<mat-icon aria-hidden="true">{{ iconFor(row.state) }}</mat-icon>{{ estados[row.state] }}
|
||||
</span>
|
||||
<span class="health__label">{{ row.label }}</span>
|
||||
<span class="health__detail">{{ row.detail }}</span>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
</section>
|
||||
@@ -0,0 +1,102 @@
|
||||
.health {
|
||||
border: 1px solid var(--mat-sys-outline-variant);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3);
|
||||
}
|
||||
|
||||
.health__toolbar {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.health__title {
|
||||
font: var(--mat-sys-title-small);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.health__spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.health__latency {
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
font: var(--mat-sys-body-small);
|
||||
}
|
||||
|
||||
.health__alert {
|
||||
align-items: center;
|
||||
background: var(--mat-sys-error-container);
|
||||
color: var(--mat-sys-on-error-container);
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
}
|
||||
|
||||
.health__rows {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.health__row {
|
||||
align-items: center;
|
||||
border-left: 3px solid var(--mat-sys-outline);
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-1) var(--space-2);
|
||||
}
|
||||
|
||||
.health__check {
|
||||
align-items: center;
|
||||
display: inline-flex;
|
||||
font: var(--mat-sys-label-medium);
|
||||
gap: var(--space-1);
|
||||
min-width: 96px;
|
||||
}
|
||||
|
||||
.health__row--ok {
|
||||
border-left-color: var(--mat-sys-primary);
|
||||
}
|
||||
|
||||
.health__row--ok .health__check {
|
||||
color: var(--mat-sys-primary);
|
||||
}
|
||||
|
||||
.health__row--warn {
|
||||
border-left-color: #9a6a00;
|
||||
}
|
||||
|
||||
.health__row--warn .health__check {
|
||||
color: #9a6a00;
|
||||
}
|
||||
|
||||
.health__row--fail {
|
||||
border-left-color: var(--mat-sys-error);
|
||||
}
|
||||
|
||||
.health__row--fail .health__check {
|
||||
color: var(--mat-sys-error);
|
||||
}
|
||||
|
||||
.health__row--unknown .health__check {
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
}
|
||||
|
||||
.health__label {
|
||||
font: var(--mat-sys-body-medium);
|
||||
min-width: 160px;
|
||||
}
|
||||
|
||||
.health__detail {
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
font: var(--mat-sys-body-small);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* Covers the cluster health card's reading of `ClusterStatus`: one labelled row per check with green /
|
||||
* amber / red states, the dashboard button gating and its tooltip, the manual re-check, re-checking on
|
||||
* a cluster change, and the 30 s polling that skips a hidden page. Fixtures: canned `ClusterStatus`
|
||||
* answers through `HttpTestingController`.
|
||||
*/
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { MatTooltip } from '@angular/material/tooltip';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { ClusterChoice, ClusterStatus } from '../../api/tea-eeg.types';
|
||||
import { ClusterHealthCard } from './cluster-health-card';
|
||||
|
||||
const CLUSTER_URL = '/governance/tea/cluster';
|
||||
|
||||
// Base answer: everything unchecked; tests override what they pin down.
|
||||
function status(partial: Partial<ClusterStatus>): ClusterStatus {
|
||||
return {
|
||||
mode: 'auto', scheduler: null, reachable: false, workers: null, expected_workers: null,
|
||||
versions_ok: null, version_error: null, dashboard_ok: null, dashboard_url: null,
|
||||
reference: null, latency_ms: null, error: null, ...partial,
|
||||
};
|
||||
}
|
||||
|
||||
const OK = status({
|
||||
mode: 'remote', scheduler: 'tcp://equipo:8786', reachable: true, workers: 4, expected_workers: 4,
|
||||
versions_ok: true, dashboard_ok: true, dashboard_url: 'http://equipo:8787/status',
|
||||
reference: { name: 'referencia_2026', edfs: 120 }, latency_ms: 42,
|
||||
});
|
||||
|
||||
describe('ClusterHealthCard', () => {
|
||||
let http: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
function expectCluster() {
|
||||
return http.expectOne((r) => r.url === CLUSTER_URL);
|
||||
}
|
||||
|
||||
function create(choice: ClusterChoice = { mode: 'auto' }): ComponentFixture<ClusterHealthCard> {
|
||||
const fixture = TestBed.createComponent(ClusterHealthCard);
|
||||
fixture.componentRef.setInput('choice', choice);
|
||||
fixture.detectChanges();
|
||||
expectCluster().flush(OK);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
function rows(fixture: ComponentFixture<ClusterHealthCard>): { state: string; text: string }[] {
|
||||
const states = ['ok', 'warn', 'fail', 'unknown'];
|
||||
return Array.from<HTMLElement>(fixture.nativeElement.querySelectorAll('.health__row')).map((el) => ({
|
||||
state: states.find((s) => el.classList.contains(`health__row--${s}`)) ?? 'none',
|
||||
// The icon's ligature would glue onto the label, so text nodes are read apart from it.
|
||||
text: ['.health__check', '.health__label', '.health__detail']
|
||||
.map((sel) =>
|
||||
Array.from(el.querySelector(sel)!.childNodes)
|
||||
.filter((node) => node.nodeType === Node.TEXT_NODE)
|
||||
.map((node) => node.textContent ?? '')
|
||||
.join('')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim(),
|
||||
)
|
||||
.join(' '),
|
||||
}));
|
||||
}
|
||||
|
||||
function dashboardTooltip(fixture: ComponentFixture<ClusterHealthCard>): MatTooltip {
|
||||
return fixture.debugElement.query(By.css('.health__dashboard'))!.injector.get(MatTooltip);
|
||||
}
|
||||
|
||||
function dashboardButton(fixture: ComponentFixture<ClusterHealthCard>): HTMLButtonElement {
|
||||
return Array.from<HTMLButtonElement>(fixture.nativeElement.querySelectorAll('button')).find((b) =>
|
||||
b.textContent?.includes('Abrir dashboard de Dask'),
|
||||
)!;
|
||||
}
|
||||
|
||||
// Fails if an unreachable scheduler stops failing the scheduler row while the other checks go
|
||||
// unknown instead of pretending a result.
|
||||
it('shows an unreachable cluster as a failed scheduler and unchecked rows', () => {
|
||||
const fixture = TestBed.createComponent(ClusterHealthCard);
|
||||
fixture.detectChanges();
|
||||
expectCluster().flush(status({ reachable: false, error: 'Conexión rechazada' }));
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(rows(fixture)).toEqual([
|
||||
{ state: 'fail', text: 'Error Scheduler Conexión rechazada' },
|
||||
{ state: 'unknown', text: 'Sin datos Trabajadores Sin datos' },
|
||||
{ state: 'unknown', text: 'Sin datos Versiones Sin datos' },
|
||||
{ state: 'unknown', text: 'Sin datos Dashboard No aplica en este modo' },
|
||||
{ state: 'unknown', text: 'Sin datos Volumen de referencia No verificado' },
|
||||
]);
|
||||
expect(fixture.nativeElement.textContent).toContain('Latencia: sin datos');
|
||||
});
|
||||
|
||||
// Fails if a version mismatch stops failing the versions row with the server's message, or a short
|
||||
// worker count stops being a warning.
|
||||
it('flags a version mismatch and a short worker count, and keeps the rest green', () => {
|
||||
const fixture = create();
|
||||
const mismatch = status({
|
||||
mode: 'remote', scheduler: 'tcp://equipo:8786', reachable: true, workers: 3, expected_workers: 4,
|
||||
versions_ok: false, version_error: 'cliente 2026.9 vs trabajadores 2026.8',
|
||||
dashboard_ok: true, dashboard_url: 'http://equipo:8787/status',
|
||||
reference: { name: 'referencia_2026', edfs: 120 }, latency_ms: 42,
|
||||
});
|
||||
fixture.componentInstance.status.set(mismatch);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(rows(fixture)).toEqual([
|
||||
{ state: 'ok', text: 'Correcto Scheduler tcp://equipo:8786' },
|
||||
{ state: 'warn', text: 'Aviso Trabajadores 3 de 4 esperados' },
|
||||
{ state: 'fail', text: 'Error Versiones cliente 2026.9 vs trabajadores 2026.8' },
|
||||
{ state: 'ok', text: 'Correcto Dashboard http://equipo:8787/status' },
|
||||
{ state: 'ok', text: 'Correcto Volumen de referencia referencia_2026 · 120 EDF' },
|
||||
]);
|
||||
expect(fixture.nativeElement.textContent).toContain('Latencia: 42 ms');
|
||||
});
|
||||
|
||||
// Fails if every check is not green on a healthy cluster, or the latency line disappears.
|
||||
it('shows a healthy cluster all green with its latency', () => {
|
||||
const fixture = create();
|
||||
expect(rows(fixture).every((r) => r.state === 'ok')).toBe(true);
|
||||
expect(fixture.nativeElement.textContent).toContain('Latencia: 42 ms');
|
||||
});
|
||||
|
||||
// Fails if the dashboard button opens while the dashboard doesn't answer, or loses its why-tooltip.
|
||||
it('opens the dashboard only when it answers, with a tooltip that says why otherwise', () => {
|
||||
const fixture = create();
|
||||
const button = dashboardButton(fixture);
|
||||
expect(button.disabled).toBe(false);
|
||||
expect(dashboardTooltip(fixture).message).toContain('pestaña nueva');
|
||||
|
||||
fixture.componentInstance.status.set(status({ reachable: true, mode: 'local', dashboard_ok: null }));
|
||||
fixture.detectChanges();
|
||||
expect(dashboardButton(fixture).disabled).toBe(true);
|
||||
expect(dashboardTooltip(fixture).message).toContain('no está disponible');
|
||||
|
||||
fixture.componentInstance.status.set(status({
|
||||
reachable: true, mode: 'remote', scheduler: 'tcp://equipo:8786', dashboard_ok: false,
|
||||
}));
|
||||
fixture.detectChanges();
|
||||
expect(dashboardButton(fixture).disabled).toBe(true);
|
||||
expect(dashboardTooltip(fixture).message).toContain('no responde');
|
||||
});
|
||||
|
||||
// Fails if the Verificar button stops asking for a fresh status, or the answer doesn't replace the rows.
|
||||
it('re-checks on demand with the Verificar button', () => {
|
||||
const fixture = create();
|
||||
const button = Array.from<HTMLButtonElement>(fixture.nativeElement.querySelectorAll('button')).find((b) =>
|
||||
b.textContent?.includes('Verificar'),
|
||||
)!;
|
||||
button.click();
|
||||
expectCluster().flush(status({ reachable: false, error: 'Se cayó el scheduler' }));
|
||||
fixture.detectChanges();
|
||||
expect(rows(fixture)[0]).toEqual({ state: 'fail', text: 'Error Scheduler Se cayó el scheduler' });
|
||||
});
|
||||
|
||||
// Fails if changing the picked cluster stops triggering a new check with the new params.
|
||||
it('re-checks with the params when the picked cluster changes', () => {
|
||||
const fixture = create({ mode: 'auto' });
|
||||
http.expectNone(() => true);
|
||||
|
||||
fixture.componentRef.setInput('choice', { mode: 'remote', scheduler: 'tcp://equipo:8786' });
|
||||
fixture.detectChanges();
|
||||
const req = expectCluster();
|
||||
expect(req.request.params.get('mode')).toBe('remote');
|
||||
expect(req.request.params.get('scheduler')).toBe('tcp://equipo:8786');
|
||||
req.flush(OK);
|
||||
});
|
||||
|
||||
// Fails if the 30 s polling is dropped, or stops skipping while the page is hidden.
|
||||
it('re-checks every 30 s while visible and stays quiet while hidden', () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const fixture = create();
|
||||
vi.advanceTimersByTime(30000);
|
||||
expectCluster().flush(OK);
|
||||
|
||||
const descriptor = Object.getOwnPropertyDescriptor(Document.prototype, 'hidden');
|
||||
Object.defineProperty(document, 'hidden', { configurable: true, value: true });
|
||||
vi.advanceTimersByTime(30000);
|
||||
http.expectNone(() => true);
|
||||
Object.defineProperty(document, 'hidden', descriptor ?? { configurable: true, value: false });
|
||||
fixture.destroy();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import { NgClass } from '@angular/common';
|
||||
import { Component, DestroyRef, effect, inject, input, signal, computed } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { timer } from 'rxjs';
|
||||
import { apiErrorMessage } from '../../../connect/api/api.types';
|
||||
import { TeaEegApi } from '../../api/tea-eeg.api';
|
||||
import { ClusterChoice, ClusterStatus } from '../../api/tea-eeg.types';
|
||||
|
||||
/** Milliseconds between health checks while the page is visible. */
|
||||
export const REFRESCO_MS = 30000;
|
||||
|
||||
export type CheckState = 'ok' | 'warn' | 'fail' | 'unknown';
|
||||
|
||||
/** Text label per state, so the row never relies on colour alone. */
|
||||
export const ESTADO_ETIQUETA: Record<CheckState, string> = {
|
||||
ok: 'Correcto',
|
||||
warn: 'Aviso',
|
||||
fail: 'Error',
|
||||
unknown: 'Sin datos',
|
||||
};
|
||||
|
||||
const ICONOS: Record<CheckState, string> = {
|
||||
ok: 'check_circle',
|
||||
warn: 'warning',
|
||||
fail: 'error',
|
||||
unknown: 'help',
|
||||
};
|
||||
|
||||
/** One row of the health card: a check, its state and a text detail. */
|
||||
export interface HealthCheckRow {
|
||||
key: 'scheduler' | 'workers' | 'versions' | 'dashboard' | 'reference';
|
||||
label: string;
|
||||
state: CheckState;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The picked cluster's health: scheduler reachability, worker count against the expected one, version
|
||||
* match, dashboard and the reference volume seen from a worker. Re-checked on demand and every 30 s
|
||||
* while the page is visible; the dashboard opens in its own tab only when it answers.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cluster-health-card',
|
||||
imports: [MatButtonModule, MatIconModule, MatTooltipModule, NgClass],
|
||||
templateUrl: './cluster-health-card.html',
|
||||
styleUrl: './cluster-health-card.scss',
|
||||
})
|
||||
export class ClusterHealthCard {
|
||||
private readonly api = inject(TeaEegApi);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
/** The cluster to check; changing it re-checks. */
|
||||
readonly choice = input<ClusterChoice>({ mode: 'auto' });
|
||||
readonly status = signal<ClusterStatus | null>(null);
|
||||
readonly loadError = signal<string | null>(null);
|
||||
readonly loading = signal(false);
|
||||
|
||||
readonly rows = computed<HealthCheckRow[]>(() => {
|
||||
const s = this.status();
|
||||
if (!s) return [];
|
||||
return [schedulerRow(s), workersRow(s), versionsRow(s), dashboardRow(s), referenceRow(s)];
|
||||
});
|
||||
/** Enabled only when the dashboard answers; the tooltip says why otherwise. */
|
||||
readonly dashboardEnabled = computed(() => !!clusterDashboardUrl(this.status()));
|
||||
readonly latencyMs = computed(() => this.status()?.latency_ms ?? null);
|
||||
readonly dashboardTooltip = computed(() => {
|
||||
const s = this.status();
|
||||
if (s?.dashboard_ok === true) return 'Abrir el dashboard de Dask en una pestaña nueva';
|
||||
if (s?.dashboard_ok === false) return 'El dashboard no responde; no se puede abrir';
|
||||
return 'El dashboard no está disponible en este modo';
|
||||
});
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
this.choice();
|
||||
this.refresh();
|
||||
});
|
||||
timer(REFRESCO_MS, REFRESCO_MS)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(() => {
|
||||
if (!document.hidden) this.refresh();
|
||||
});
|
||||
}
|
||||
|
||||
refresh(): void {
|
||||
this.loading.set(true);
|
||||
this.api.clusterStatus(this.choice()).subscribe({
|
||||
next: (status) => {
|
||||
this.loading.set(false);
|
||||
this.status.set(status);
|
||||
this.loadError.set(null);
|
||||
},
|
||||
error: (error) => {
|
||||
this.loading.set(false);
|
||||
this.loadError.set(apiErrorMessage(error, 'No se pudo consultar el estado del clúster.'));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openDashboard(): void {
|
||||
const url = clusterDashboardUrl(this.status());
|
||||
if (!url) return;
|
||||
window.open(url, '_blank', 'noopener');
|
||||
}
|
||||
|
||||
iconFor(state: CheckState): string {
|
||||
return ICONOS[state];
|
||||
}
|
||||
|
||||
protected readonly estados = ESTADO_ETIQUETA;
|
||||
}
|
||||
|
||||
export function clusterDashboardUrl(status: ClusterStatus | null): string | null {
|
||||
return status?.dashboard_ok === true ? status.dashboard_url : null;
|
||||
}
|
||||
|
||||
function schedulerRow(s: ClusterStatus): HealthCheckRow {
|
||||
if (!s.reachable) {
|
||||
return { key: 'scheduler', label: 'Scheduler', state: 'fail', detail: s.error ?? 'No responde' };
|
||||
}
|
||||
return { key: 'scheduler', label: 'Scheduler', state: 'ok', detail: s.scheduler ?? 'Clúster local' };
|
||||
}
|
||||
|
||||
function workersRow(s: ClusterStatus): HealthCheckRow {
|
||||
if (s.workers === null) return { key: 'workers', label: 'Trabajadores', state: 'unknown', detail: 'Sin datos' };
|
||||
if (s.expected_workers === null) {
|
||||
return { key: 'workers', label: 'Trabajadores', state: 'ok', detail: `${s.workers}` };
|
||||
}
|
||||
if (s.workers >= s.expected_workers) {
|
||||
return { key: 'workers', label: 'Trabajadores', state: 'ok', detail: `${s.workers} de ${s.expected_workers}` };
|
||||
}
|
||||
return { key: 'workers', label: 'Trabajadores', state: 'warn', detail: `${s.workers} de ${s.expected_workers} esperados` };
|
||||
}
|
||||
|
||||
function versionsRow(s: ClusterStatus): HealthCheckRow {
|
||||
if (s.versions_ok === null) return { key: 'versions', label: 'Versiones', state: 'unknown', detail: 'Sin datos' };
|
||||
if (s.versions_ok) return { key: 'versions', label: 'Versiones', state: 'ok', detail: 'Cliente y trabajadores coinciden' };
|
||||
return { key: 'versions', label: 'Versiones', state: 'fail', detail: s.version_error ?? 'No coinciden' };
|
||||
}
|
||||
|
||||
function dashboardRow(s: ClusterStatus): HealthCheckRow {
|
||||
if (s.dashboard_ok === null) return { key: 'dashboard', label: 'Dashboard', state: 'unknown', detail: 'No aplica en este modo' };
|
||||
if (s.dashboard_ok) return { key: 'dashboard', label: 'Dashboard', state: 'ok', detail: s.dashboard_url ?? 'Disponible' };
|
||||
return { key: 'dashboard', label: 'Dashboard', state: 'fail', detail: 'No responde' };
|
||||
}
|
||||
|
||||
function referenceRow(s: ClusterStatus): HealthCheckRow {
|
||||
if (!s.reference) return { key: 'reference', label: 'Volumen de referencia', state: 'unknown', detail: 'No verificado' };
|
||||
return { key: 'reference', label: 'Volumen de referencia', state: 'ok', detail: `${s.reference.name} · ${s.reference.edfs} EDF` };
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<div class="cluster-selector">
|
||||
<mat-button-toggle-group hideSingleSelectionIndicator [value]="choice().mode" (change)="setMode($event.value)" aria-label="Modo de clúster">
|
||||
@for (modo of modos; track modo[0]) {
|
||||
<mat-button-toggle [value]="modo[0]">{{ modo[1] }}</mat-button-toggle>
|
||||
}
|
||||
</mat-button-toggle-group>
|
||||
@if (choice().mode === 'remote') {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="cluster-selector__scheduler">
|
||||
<mat-label>Dirección del scheduler</mat-label>
|
||||
<input matInput [formControl]="scheduler" placeholder="tcp://equipo:8786" />
|
||||
</mat-form-field>
|
||||
}
|
||||
</div>
|
||||
@@ -0,0 +1,10 @@
|
||||
.cluster-selector {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.cluster-selector__scheduler {
|
||||
min-width: 280px;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Covers the cluster selector's model: the toggle picks the mode, choosing remote exposes a scheduler
|
||||
* field whose text joins the choice, and leaving remote drops the scheduler again. The component does
|
||||
* no HTTP, so fixtures are only the rendered component.
|
||||
*/
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { ClusterSelector } from './cluster-selector';
|
||||
|
||||
describe('ClusterSelector', () => {
|
||||
function create() {
|
||||
TestBed.configureTestingModule({ imports: [ClusterSelector] });
|
||||
const fixture = TestBed.createComponent(ClusterSelector);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
// Fails if the initial mode stops being 'auto', or the scheduler field shows before remote is picked.
|
||||
it('starts on auto with the scheduler field hidden', () => {
|
||||
const fixture = create();
|
||||
expect(fixture.componentInstance.choice()).toEqual({ mode: 'auto' });
|
||||
expect(fixture.nativeElement.querySelector('.cluster-selector__scheduler')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).toContain('Remoto');
|
||||
});
|
||||
|
||||
// Fails if picking remote stops asking for the scheduler, or its text stops joining the choice.
|
||||
it('adds the scheduler address to the choice only while remote is selected', () => {
|
||||
const fixture = create();
|
||||
const selector = fixture.componentInstance;
|
||||
|
||||
selector.setMode('remote');
|
||||
fixture.detectChanges();
|
||||
expect(selector.choice()).toEqual({ mode: 'remote' });
|
||||
expect(fixture.nativeElement.querySelector('.cluster-selector__scheduler')).not.toBeNull();
|
||||
|
||||
selector.scheduler.setValue('tcp://equipo:8786');
|
||||
expect(selector.choice()).toEqual({ mode: 'remote', scheduler: 'tcp://equipo:8786' });
|
||||
|
||||
selector.setMode('local');
|
||||
fixture.detectChanges();
|
||||
expect(selector.choice()).toEqual({ mode: 'local' });
|
||||
expect(fixture.nativeElement.querySelector('.cluster-selector__scheduler')).toBeNull();
|
||||
});
|
||||
|
||||
// Fails if the typed address is lost on a round trip, or an empty one is sent as an empty string.
|
||||
it('keeps the typed address across modes and drops it when empty', () => {
|
||||
const fixture = create();
|
||||
const selector = fixture.componentInstance;
|
||||
|
||||
selector.setMode('remote');
|
||||
selector.scheduler.setValue('tcp://equipo:8786');
|
||||
selector.setMode('sync');
|
||||
selector.setMode('remote');
|
||||
expect(selector.choice()).toEqual({ mode: 'remote', scheduler: 'tcp://equipo:8786' });
|
||||
|
||||
selector.scheduler.setValue(' ');
|
||||
expect(selector.choice()).toEqual({ mode: 'remote' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Component, DestroyRef, inject, model } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormControl, ReactiveFormsModule } from '@angular/forms';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { ClusterChoice, ClusterMode } from '../../api/tea-eeg.types';
|
||||
|
||||
export const MODO_ETIQUETA: Record<ClusterMode, string> = {
|
||||
auto: 'Auto',
|
||||
local: 'Local',
|
||||
remote: 'Remoto',
|
||||
sync: 'Sync',
|
||||
};
|
||||
|
||||
/** Where the TEA·EEG work runs. Remote asks for the scheduler address; the address is kept while
|
||||
* another mode is selected so switching back doesn't lose it. */
|
||||
@Component({
|
||||
selector: 'app-cluster-selector',
|
||||
imports: [MatButtonToggleModule, MatFormFieldModule, MatInputModule, ReactiveFormsModule],
|
||||
templateUrl: './cluster-selector.html',
|
||||
styleUrl: './cluster-selector.scss',
|
||||
})
|
||||
export class ClusterSelector {
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
/** The picked mode and, for 'remote', the scheduler address. */
|
||||
readonly choice = model<ClusterChoice>({ mode: 'auto' });
|
||||
readonly modos = (Object.entries(MODO_ETIQUETA) as [ClusterMode, string][]);
|
||||
readonly scheduler = new FormControl('', { nonNullable: true });
|
||||
|
||||
constructor() {
|
||||
this.scheduler.valueChanges.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((value) => this.applyScheduler(value));
|
||||
}
|
||||
|
||||
setMode(mode: ClusterMode): void {
|
||||
this.choice.set(mode === 'remote' ? { mode, scheduler: this.scheduler.value.trim() || undefined } : { mode });
|
||||
}
|
||||
|
||||
private applyScheduler(value: string): void {
|
||||
if (this.choice().mode !== 'remote') return;
|
||||
this.choice.set({ mode: 'remote', scheduler: value.trim() || undefined });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/** Pins paging and retained EEG choices with mocked catalog pages and a failed request. */
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { EegPicker } from './eeg-picker';
|
||||
|
||||
describe('EegPicker', () => {
|
||||
/** Fails if a page exceeds 50 rows, a new page loses selections, or a failed page cannot be retried. */
|
||||
it('keeps checked EEGs through paging and offers retry on failure', async () => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
const fixture = TestBed.createComponent(EegPicker);
|
||||
fixture.detectChanges();
|
||||
const first = http.expectOne('/governance/tea/eeg?limit=50&offset=0');
|
||||
// A full first page permits forward navigation.
|
||||
first.flush(Array.from({ length: 50 }, (_, id) => ({
|
||||
id, lab_id: 'LAB-' + id, study_date: null, patient_id: null, valid: null, analysed: false,
|
||||
})));
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
fixture.nativeElement.querySelector('input').click();
|
||||
const next = Array.from(fixture.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>)
|
||||
.find((button) => button.textContent?.includes('Siguiente'))!;
|
||||
next.click();
|
||||
fixture.detectChanges();
|
||||
http.expectOne('/governance/tea/eeg?limit=50&offset=50').flush(null, { status: 500, statusText: 'Server Error' });
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
expect(fixture.componentInstance.selected()).toEqual([0]);
|
||||
expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('No se pudieron cargar los EEGs.');
|
||||
fixture.nativeElement.querySelector('button').click();
|
||||
fixture.detectChanges();
|
||||
http.expectOne('/governance/tea/eeg?limit=50&offset=50').flush([]);
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay EEGs en esta página.');
|
||||
http.verify();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { DatePipe } from '@angular/common';
|
||||
import { Component, inject, input, linkedSignal, model } from '@angular/core';
|
||||
import { rxResource } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { EegId } from '../../api/tea-eeg.types';
|
||||
import { TeaEegApi } from '../../api/tea-eeg.api';
|
||||
|
||||
@Component({
|
||||
selector: 'app-eeg-picker',
|
||||
imports: [DatePipe, MatButtonModule],
|
||||
styleUrl: '../eeg-step.scss',
|
||||
template: `
|
||||
@if (page.isLoading()) { <p role="status">Cargando EEGs…</p> }
|
||||
@else if (page.error()) {
|
||||
<p role="alert">No se pudieron cargar los EEGs.</p>
|
||||
<button mat-button type="button" (click)="page.reload()">Reintentar</button>
|
||||
} @else if (!page.value()?.length) { <p>No hay EEGs en esta página.</p> }
|
||||
@if (page.hasValue() && page.value().length) {
|
||||
<div class="table-scroll">
|
||||
<table aria-label="Selección de EEGs">
|
||||
<thead><tr><th>Elegir</th><th>ID de laboratorio</th><th>Paciente</th><th>Fecha</th><th>Válido</th><th>Analizado</th></tr></thead>
|
||||
<tbody>
|
||||
@for (eeg of page.value(); track eeg.id) {
|
||||
<tr>
|
||||
<td><input type="checkbox" [attr.aria-label]="'Elegir EEG ' + eeg.id" [checked]="selected().includes(eeg.id)"
|
||||
[disabled]="disabled() || page.isLoading()" (change)="select(eeg.id, $event)" /></td>
|
||||
<td>{{ eeg.lab_id ?? '—' }}</td><td>{{ eeg.patient_id ?? '—' }}</td>
|
||||
<td>{{ (eeg.study_date | date: 'mediumDate') ?? '—' }}</td>
|
||||
<td>{{ eeg.valid === null ? '—' : eeg.valid ? 'Sí' : 'No' }}</td><td>{{ eeg.analysed ? 'Sí' : 'No' }}</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
<div class="controls">
|
||||
<button mat-button type="button" [disabled]="disabled() || page.isLoading() || !index()" (click)="index.update(value => value - 1)">Anterior</button>
|
||||
<span>Página {{ index() + 1 }} · {{ selected().length }} elegidos</span>
|
||||
<button mat-button type="button" [disabled]="disabled() || page.isLoading() || !page.hasValue() || page.value().length < pageSize"
|
||||
(click)="index.update(value => value + 1)">Siguiente</button>
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class EegPicker {
|
||||
private readonly api = inject(TeaEegApi);
|
||||
readonly selected = model<EegId[]>([]);
|
||||
readonly disabled = input(false);
|
||||
readonly revision = input(0);
|
||||
readonly pageSize = 50;
|
||||
readonly index = linkedSignal({ source: this.revision, computation: () => 0 });
|
||||
readonly page = rxResource({
|
||||
params: () => ({ offset: this.index() * this.pageSize, revision: this.revision() }),
|
||||
stream: ({ params }) => this.api.eegList(this.pageSize, params.offset),
|
||||
});
|
||||
|
||||
select(id: EegId, event: Event): void {
|
||||
const checked = (event.target as HTMLInputElement).checked;
|
||||
this.selected.update((ids) => checked ? [...ids, id] : ids.filter((item) => item !== id));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<h2 mat-dialog-title>Resultados del EEG · {{ data.archivo }}</h2>
|
||||
<mat-dialog-content>
|
||||
<div class="imprimible">
|
||||
<p class="aviso-no-guardado" role="note">Análisis hecho al momento. No se guardó en la base de datos.</p>
|
||||
@for (aviso of data.avisos; track aviso) { <p class="aviso" role="status">{{ aviso }}</p> }
|
||||
<app-tea-paciente-resumen [detalleInicial]="data.detalle" modo="resumen" />
|
||||
</div>
|
||||
</mat-dialog-content>
|
||||
<mat-dialog-actions align="end">
|
||||
<button mat-stroked-button type="button" (click)="savePdf()">Guardar como PDF</button>
|
||||
<button mat-flat-button type="button" mat-dialog-close>Cerrar</button>
|
||||
</mat-dialog-actions>
|
||||
@@ -0,0 +1,3 @@
|
||||
mat-dialog-content { min-width: min(960px, 86vw); }
|
||||
.aviso-no-guardado { margin: 0 0 var(--issste-space-3, 12px); font-style: italic; color: var(--issste-text-secondary, #555); }
|
||||
.aviso { margin: 0 0 var(--issste-space-2, 8px); padding: 8px 12px; border-left: 4px solid var(--issste-accent, #1678ad); background: var(--issste-background, #f5f5f5); }
|
||||
@@ -0,0 +1,49 @@
|
||||
/** Pins the preview dialog: it shows the unsaved notice and the server's notices, and prints only itself.
|
||||
* Fixtures: a minimal summary without ADOS-2 or EEG, so the shared record view renders its empty states. */
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
|
||||
import { EegPreviewDialog, PRINT_CLASS } from './eeg-preview-dialog';
|
||||
|
||||
function create() {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideHttpClient(), provideHttpClientTesting(), {
|
||||
provide: MAT_DIALOG_DATA,
|
||||
useValue: { archivo: 'estudio.edf', avisos: ['No se pudo leer el ADOS-2 del PDF.'],
|
||||
detalle: { simulado: true, id_seudonimo: 'vista-previa', grupo_edad: '', ados2: null, eeg: null } },
|
||||
}],
|
||||
});
|
||||
const fixture = TestBed.createComponent(EegPreviewDialog);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
describe('EegPreviewDialog', () => {
|
||||
/** Fails if the dialog stops saying the analysis was not stored, hides a server notice, or asks the server for the record. */
|
||||
it('says nothing was saved and lists the notices without requesting a patient', () => {
|
||||
const text = create().nativeElement.textContent as string;
|
||||
expect(text).toContain('estudio.edf');
|
||||
expect(text).toContain('No se guardó en la base de datos');
|
||||
expect(text).toContain('No se pudo leer el ADOS-2 del PDF.');
|
||||
expect(text).toContain('Sin evaluación ADOS-2 registrada.');
|
||||
});
|
||||
|
||||
/** Fails if printing leaves the page marked after it ends, or never marks it, which would print the whole app. */
|
||||
it('marks the page for printing and clears it afterwards', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const fixture = create();
|
||||
const view = TestBed.inject(DOCUMENT).defaultView!;
|
||||
const print = vi.spyOn(view, 'print').mockImplementation(() => undefined);
|
||||
const pending = fixture.componentInstance.savePdf();
|
||||
expect(TestBed.inject(DOCUMENT).body.classList.contains(PRINT_CLASS)).toBe(true);
|
||||
await vi.advanceTimersByTimeAsync(600);
|
||||
await pending;
|
||||
expect(print).toHaveBeenCalledOnce();
|
||||
view.dispatchEvent(new Event('afterprint'));
|
||||
expect(TestBed.inject(DOCUMENT).body.classList.contains(PRINT_CLASS)).toBe(false);
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
|
||||
import { TeaPacienteResumen } from '../../../features/indicadores/tea-paciente-resumen';
|
||||
import { TeaPacienteDetalle } from '../../../features/indicadores/tea-seguimiento.service';
|
||||
|
||||
/** What the dialog shows: the analysis of one EDF and the notices about what could not be read. */
|
||||
export interface EegPreviewData {
|
||||
detalle: TeaPacienteDetalle;
|
||||
avisos: string[];
|
||||
archivo: string;
|
||||
}
|
||||
|
||||
/** Body class that the print styles use to show only this dialog on paper. */
|
||||
export const PRINT_CLASS = 'imprime-vista-previa';
|
||||
|
||||
/**
|
||||
* The record of an analysis that was not stored, laid out as a patient's record in Seguimiento, with a button
|
||||
* that opens the browser's print dialog (Guardar como PDF).
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-eeg-preview-dialog',
|
||||
imports: [MatButtonModule, MatDialogModule, TeaPacienteResumen],
|
||||
templateUrl: './eeg-preview-dialog.html',
|
||||
styleUrl: './eeg-preview-dialog.scss',
|
||||
})
|
||||
export class EegPreviewDialog {
|
||||
readonly data = inject<EegPreviewData>(MAT_DIALOG_DATA);
|
||||
private readonly document = inject(DOCUMENT);
|
||||
|
||||
/** Charts redraw to the page width on the next frames, so printing waits for them. */
|
||||
async savePdf(): Promise<void> {
|
||||
const view = this.document.defaultView;
|
||||
if (!view) return;
|
||||
const body = this.document.body;
|
||||
body.classList.add(PRINT_CLASS);
|
||||
const done = () => body.classList.remove(PRINT_CLASS);
|
||||
view.addEventListener('afterprint', done, { once: true });
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
view.print();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
:host { display: block; padding-block: .75rem; min-width: 0; }
|
||||
.controls { display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; margin-block: .75rem; }
|
||||
.controls label { display: flex; flex-wrap: wrap; align-items: center; gap: .35rem; }
|
||||
select, input { font: inherit; color: inherit; background: var(--mat-sys-surface); }
|
||||
[role="alert"] { color: var(--mat-sys-error); }
|
||||
table { border-collapse: collapse; width: 100%; text-align: start; }
|
||||
th, td { padding: .4rem; border-bottom: 1px solid var(--mat-sys-outline-variant); text-align: start; }
|
||||
.table-scroll { overflow-x: auto; }
|
||||
@@ -27,5 +27,12 @@
|
||||
<app-risk-batches-panel></app-risk-batches-panel>
|
||||
</div>
|
||||
</mat-tab>
|
||||
@if (puedeVerTea()) {
|
||||
<mat-tab label="TEA · EEG">
|
||||
<div class="governance__panel">
|
||||
<app-tea-eeg-panel></app-tea-eeg-panel>
|
||||
</div>
|
||||
</mat-tab>
|
||||
}
|
||||
</mat-tab-group>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Covers the governance page's fifth tab: the "TEA · EEG" wizard shows for accounts that reach the TEA
|
||||
* domain and is absent for the rest. Fixtures: stubs of the panels' APIs (no HTTP happens) and an
|
||||
* `AuthService` double whose `puedeVer` answers per domain; the wizard's own health check answers
|
||||
* immediately.
|
||||
*/
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { of } from 'rxjs';
|
||||
import { AuthService } from '../../../auth/auth.service';
|
||||
import { GovernanceApi } from '../../api/governance.api';
|
||||
import { RiskBatchesApi } from '../../api/risk-batches.api';
|
||||
import { TeaEegApi } from '../../api/tea-eeg.api';
|
||||
import { ClusterStatus } from '../../api/tea-eeg.types';
|
||||
import { GovernancePage } from './governance-page';
|
||||
|
||||
// A healthy cluster, for the wizard's first check when the tab renders.
|
||||
const STATUS: ClusterStatus = {
|
||||
mode: 'auto', scheduler: null, reachable: true, workers: null, expected_workers: null,
|
||||
versions_ok: null, version_error: null, dashboard_ok: null, dashboard_url: null,
|
||||
reference: null, latency_ms: null, error: null,
|
||||
};
|
||||
|
||||
describe('GovernancePage TEA · EEG tab', () => {
|
||||
function mount(puedeVerTea: boolean) {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [GovernancePage],
|
||||
providers: [
|
||||
{
|
||||
provide: AuthService,
|
||||
useValue: { puedeVer: (dominio: string) => (dominio === 'tea' ? puedeVerTea : true) },
|
||||
},
|
||||
{
|
||||
provide: GovernanceApi,
|
||||
useValue: {
|
||||
listModelVersions: () => of({ model_versions: [] }),
|
||||
trainableScenarios: () => of({ scenarios: [] }),
|
||||
trainingJobs: () => of({ jobs: [] }),
|
||||
listExperiments: () => of({ experiments: [] }),
|
||||
listOcrJobs: () => of({ jobs: [] }),
|
||||
checks: () => of({ ready: true, checks: [] }),
|
||||
},
|
||||
},
|
||||
{ provide: RiskBatchesApi, useValue: { listPending: () => of([]) } },
|
||||
{
|
||||
provide: TeaEegApi,
|
||||
useValue: {
|
||||
clusterStatus: () => of(STATUS),
|
||||
listReferenceCohorts: () => of([]),
|
||||
baselinesExportUrl: () => '/governance/tea/baselines/export?environment=prod',
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
const fixture = TestBed.createComponent(GovernancePage);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
function tabLabels(fixture: ReturnType<typeof mount>): string[] {
|
||||
return Array.from<HTMLElement>(fixture.nativeElement.querySelectorAll('.mat-mdc-tab')).map((tab) =>
|
||||
(tab.textContent ?? '').replace(/\s+/g, ' ').trim(),
|
||||
);
|
||||
}
|
||||
|
||||
// Fails if the wizard tab stops rendering for a TEA account, or its stepper loses the nine titles.
|
||||
it('shows the wizard as the fifth tab for an account that reaches TEA', () => {
|
||||
const fixture = mount(true);
|
||||
const labels = tabLabels(fixture);
|
||||
expect(labels).toEqual([
|
||||
'Versiones de modelo', 'Notebooks', 'Revisión de OCR', 'Lotes de riesgo', 'TEA · EEG',
|
||||
]);
|
||||
|
||||
// Tab bodies build on first activation, so open the tab before looking inside.
|
||||
const tab = Array.from<HTMLElement>(fixture.nativeElement.querySelectorAll('.mat-mdc-tab')).find((el) =>
|
||||
(el.textContent ?? '').includes('TEA · EEG'),
|
||||
)!;
|
||||
tab.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
fixture.detectChanges();
|
||||
|
||||
const wizard = fixture.nativeElement.querySelector('app-tea-eeg-panel mat-stepper');
|
||||
expect(wizard).not.toBeNull();
|
||||
const steps = Array.from<HTMLElement>(fixture.nativeElement.querySelectorAll('.mat-step-text-label')).map(
|
||||
(el) => (el.textContent ?? '').trim(),
|
||||
);
|
||||
expect(steps).toEqual([
|
||||
'Clúster', 'Datos de referencia', 'Entrenar', 'Líneas base', 'Reportes',
|
||||
'Promover', 'Verificar línea base', 'Analizar', 'Resultado',
|
||||
]);
|
||||
});
|
||||
|
||||
// Fails if the wizard tab starts showing for accounts the TEA domain is closed to.
|
||||
it('hides the wizard tab for an account that cannot see TEA', () => {
|
||||
const fixture = mount(false);
|
||||
expect(tabLabels(fixture)).toEqual(['Versiones de modelo', 'Notebooks', 'Revisión de OCR', 'Lotes de riesgo']);
|
||||
expect(fixture.nativeElement.querySelector('app-tea-eeg-panel')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,20 +1,28 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { Component, computed, inject } from '@angular/core';
|
||||
import { MatTabsModule } from '@angular/material/tabs';
|
||||
import { MatToolbarModule } from '@angular/material/toolbar';
|
||||
import { AuthService } from '../../../auth/auth.service';
|
||||
import { ExperimentsPanel } from '../experiments-panel/experiments-panel';
|
||||
import { ModelVersionsPanel } from '../model-versions-panel/model-versions-panel';
|
||||
import { OcrReviewPanel } from '../ocr-review-panel/ocr-review-panel';
|
||||
import { RiskBatchesPanel } from '../risk-batches-panel/risk-batches-panel';
|
||||
import { TeaEegPanel } from '../tea-eeg-panel/tea-eeg-panel';
|
||||
|
||||
/**
|
||||
* The "Gobernanza de modelos" page (route `/gobernanza`): model versions,
|
||||
* notebooks run on cohort builds, the OCR review queue and pending risk batches, one tab each. Every tab is a
|
||||
* self-contained panel that loads its own data.
|
||||
* self-contained panel that loads its own data. The TEA · EEG wizard is a fifth tab, only for accounts
|
||||
* that reach the TEA domain.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-governance-page',
|
||||
imports: [ExperimentsPanel, MatTabsModule, MatToolbarModule, ModelVersionsPanel, OcrReviewPanel, RiskBatchesPanel],
|
||||
imports: [ExperimentsPanel, MatTabsModule, MatToolbarModule, ModelVersionsPanel, OcrReviewPanel, RiskBatchesPanel, TeaEegPanel],
|
||||
templateUrl: './governance-page.html',
|
||||
styleUrl: './governance-page.scss',
|
||||
})
|
||||
export class GovernancePage {}
|
||||
export class GovernancePage {
|
||||
private readonly auth = inject(AuthService);
|
||||
|
||||
/** Only accounts that reach the TEA domain get the TEA · EEG wizard. */
|
||||
readonly puedeVerTea = computed(() => this.auth.puedeVer('tea'));
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<section aria-label="Progreso de ejecución">
|
||||
@if (message(); as status) { <p role="status">{{ status }}</p> }
|
||||
@if (sample(); as progress) {
|
||||
<p>
|
||||
<strong>{{ progress.phase }}</strong> · {{ progress.done }}/{{ progress.total }}
|
||||
· Tiempo transcurrido {{ duration(progress.elapsed_s) }} · Tiempo restante {{ eta() }}
|
||||
@if (stale()) { <span class="stale" role="status">sin señal</span> }
|
||||
</p>
|
||||
<mat-progress-bar aria-label="Avance de la ejecución" [mode]="progress.total ? 'determinate' : running() ? 'indeterminate' : 'determinate'"
|
||||
[value]="progress.total ? percent(100 * progress.done / progress.total) : 0" />
|
||||
@if (progress.cluster; as cluster) {
|
||||
<p>Clúster · CPU {{ fixed(cluster.cpu_pct) }} % · RAM {{ fixed(cluster.memory_pct) }} %</p>
|
||||
<div class="workers">
|
||||
@for (worker of cluster.workers; track worker.name) {
|
||||
<div class="worker" tabindex="0" [matTooltip]="workerDetails(worker)">
|
||||
<strong>{{ worker.name }}</strong>
|
||||
<label>CPU {{ fixed(worker.cpu_pct) }} % <meter min="0" max="100" [value]="percent(worker.cpu_pct)"></meter></label>
|
||||
@let usage = ram(worker);
|
||||
@if (usage !== null) {
|
||||
<label>RAM {{ usage.toFixed(1) }} % <meter min="0" max="100" [value]="usage"></meter></label>
|
||||
} @else { <span>RAM {{ worker.memory_bytes }} bytes · sin límite informado</span> }
|
||||
</div>
|
||||
} @empty { <p>Sin trabajadores.</p> }
|
||||
</div>
|
||||
@if (cluster.mode === 'remote') {
|
||||
@if (dashboard(); as url) {
|
||||
<a mat-stroked-button [href]="url" target="_blank" rel="noopener">Abrir dashboard de Dask</a>
|
||||
} @else {
|
||||
<button mat-stroked-button disabled>Abrir dashboard de Dask</button>
|
||||
}
|
||||
}
|
||||
}
|
||||
@if (progress.tasks; as tasks) {
|
||||
<p>Tareas · En proceso {{ tasks.processing }} · En espera {{ tasks.waiting }}
|
||||
· En memoria {{ tasks.memory }} · Con error {{ tasks.erred }}</p>
|
||||
}
|
||||
@if (progress.history.length) {
|
||||
<div class="trends">
|
||||
@for (trend of trends; track trend.key) {
|
||||
<figure>
|
||||
<svg viewBox="0 0 120 32" aria-hidden="true">
|
||||
<polyline [attr.points]="sparkline(progress.history, trend.key, progress.total)" />
|
||||
</svg>
|
||||
<figcaption>{{ trend.label }} · {{ fixed(progress.history[0][trend.key]) }} → {{ fixed(progress.history[progress.history.length - 1][trend.key]) }}</figcaption>
|
||||
</figure>
|
||||
}
|
||||
</div>
|
||||
<details>
|
||||
<summary>Ver historial de mediciones</summary>
|
||||
<table>
|
||||
<thead><tr><th>Tiempo (s)</th><th>CPU (%)</th><th>RAM (%)</th><th>Procesados</th></tr></thead>
|
||||
<tbody>
|
||||
@for (point of progress.history; track $index) {
|
||||
<tr><td>{{ fixed(point.t) }}</td><td>{{ fixed(point.cpu_pct) }}</td><td>{{ fixed(point.memory_pct) }}</td><td>{{ point.done }}</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,11 @@
|
||||
:host { display: block; margin-block: .75rem; }
|
||||
.stale { border: 1px solid currentColor; border-radius: .35rem; padding: .15rem .4rem; }
|
||||
.workers, .trends { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 10rem), 1fr)); gap: .5rem; margin-block: .75rem; }
|
||||
.worker, figure { border: 1px solid var(--mat-sys-outline-variant); border-radius: .4rem; padding: .5rem; margin: 0; }
|
||||
.worker { display: grid; gap: .25rem; min-width: 0; overflow-wrap: anywhere; font-size: .8rem; }
|
||||
meter { display: block; width: 100%; height: .55rem; accent-color: var(--eeg-blue); }
|
||||
meter::-webkit-meter-optimum-value { background: var(--eeg-blue); }
|
||||
meter::-moz-meter-bar { background: var(--eeg-blue); }
|
||||
svg { display: block; width: 100%; max-height: 3.5rem; }
|
||||
polyline { stroke: var(--eeg-blue); stroke-width: 2; stroke-linecap: round; fill: none; }
|
||||
table { border-spacing: .5rem; text-align: end; }
|
||||
@@ -0,0 +1,103 @@
|
||||
/** Pins progress rendering and polling against a mocked HTTP endpoint and clock. */
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { RunProgress } from '../../api/tea-eeg.types';
|
||||
import { RunMonitorComponent } from './run-monitor';
|
||||
|
||||
const url = '/governance/tea/jobs/train/t1/progress';
|
||||
|
||||
describe('RunMonitorComponent', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
});
|
||||
afterEach(() => {
|
||||
TestBed.inject(HttpTestingController).verify();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
/** Fails if a first 404 appears as a failure or a finished job keeps polling after its last read. */
|
||||
it('waits for the first measurement and performs one final read', () => {
|
||||
const fixture = TestBed.createComponent(RunMonitorComponent);
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('kind', 'train');
|
||||
fixture.componentRef.setInput('jobId', 't1');
|
||||
fixture.componentRef.setInput('running', true);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(url).flush(null, { status: 404, statusText: 'Not Found' });
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('Esperando la primera medición');
|
||||
|
||||
vi.advanceTimersByTime(2000);
|
||||
// A remote cluster sample with a concrete estimate and worker counters.
|
||||
const sample: RunProgress = {
|
||||
updated_at: new Date().toISOString(), phase: 'midiendo', done: 4, total: 10,
|
||||
elapsed_s: 40, eta_s: 200, tasks: { processing: 2, waiting: 4, memory: 4, erred: 0 },
|
||||
cluster: {
|
||||
mode: 'remote', scheduler: 'tcp://equipo:8786', cpu_pct: 60, memory_pct: 25,
|
||||
workers: [{ name: 'equipo', cpu_pct: 60, memory_bytes: 1024, memory_limit: 4096, executing: 2, threads: 4 }],
|
||||
},
|
||||
history: [{ t: 0, done: 0, cpu_pct: 0, memory_pct: 0 }, { t: 40, done: 4, cpu_pct: 60, memory_pct: 25 }],
|
||||
};
|
||||
http.expectOne(url).flush(sample);
|
||||
fixture.detectChanges();
|
||||
http.expectOne((req) => req.url === '/governance/tea/cluster').flush({
|
||||
dashboard_ok: true, dashboard_url: 'http://equipo:8787/status',
|
||||
});
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('≈ 3 min 20 s');
|
||||
expect(fixture.nativeElement.querySelectorAll('meter')).toHaveLength(2);
|
||||
expect(fixture.nativeElement.querySelectorAll('polyline')).toHaveLength(3);
|
||||
expect(fixture.nativeElement.querySelector('a').href).toBe('http://equipo:8787/status');
|
||||
|
||||
fixture.componentRef.setInput('running', false);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(url).flush({ ...sample, done: 10 });
|
||||
vi.advanceTimersByTime(6000);
|
||||
http.expectNone(url);
|
||||
fixture.destroy();
|
||||
});
|
||||
|
||||
/** Fails if a sample over 10 seconds old stays fresh, or a null ETA is displayed as zero. */
|
||||
it('marks stale samples during a run and labels a missing ETA', () => {
|
||||
const fixture = TestBed.createComponent(RunMonitorComponent);
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('kind', 'train');
|
||||
fixture.componentRef.setInput('jobId', 't1');
|
||||
fixture.componentRef.setInput('running', true);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(url).flush({
|
||||
updated_at: new Date(Date.now() - 10_000).toISOString(), phase: 'midiendo', done: 0, total: 10,
|
||||
elapsed_s: 1, eta_s: null, tasks: null, cluster: null, history: [],
|
||||
});
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('calculando…');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('sin señal');
|
||||
vi.advanceTimersByTime(1000);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('sin señal');
|
||||
fixture.destroy();
|
||||
});
|
||||
|
||||
/** Fails if the cluster totals show raw floating-point readings instead of at most one decimal. */
|
||||
it('rounds the cluster readings it shows', () => {
|
||||
const fixture = TestBed.createComponent(RunMonitorComponent);
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('kind', 'train');
|
||||
fixture.componentRef.setInput('jobId', 't1');
|
||||
fixture.componentRef.setInput('running', false);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(url).flush({
|
||||
updated_at: new Date().toISOString(), phase: 'midiendo', done: 4, total: 10, elapsed_s: 40, eta_s: 200,
|
||||
tasks: null,
|
||||
cluster: { mode: 'local', scheduler: null, cpu_pct: 99.96666, memory_pct: 11.779874913832721, workers: [] },
|
||||
history: [{ t: 0, done: 0, cpu_pct: 0, memory_pct: 0 }, { t: 40.123456, done: 4, cpu_pct: 99.96666, memory_pct: 11.779874913832721 }],
|
||||
} satisfies RunProgress);
|
||||
fixture.detectChanges();
|
||||
const text = fixture.nativeElement.textContent as string;
|
||||
expect(text).toContain('CPU 100 % · RAM 11.8 %');
|
||||
expect(text).not.toContain('11.7798');
|
||||
expect(text).not.toContain('40.1234');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { Component, computed, effect, inject, input, signal } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { catchError, exhaustMap, of, startWith, timer } from 'rxjs';
|
||||
import { TeaEegApi } from '../../api/tea-eeg.api';
|
||||
import { RunProgress, WorkerSample } from '../../api/tea-eeg.types';
|
||||
import { clusterDashboardUrl } from '../cluster-health-card/cluster-health-card';
|
||||
|
||||
export function formatDuration(seconds: number): string {
|
||||
const whole = Math.max(0, Math.round(seconds));
|
||||
const minutes = Math.floor(whole / 60);
|
||||
return minutes ? `${minutes} min ${whole % 60} s` : `${whole} s`;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-run-monitor',
|
||||
imports: [MatButtonModule, MatProgressBarModule, MatTooltipModule],
|
||||
templateUrl: './run-monitor.html',
|
||||
styleUrl: './run-monitor.scss',
|
||||
})
|
||||
export class RunMonitorComponent {
|
||||
private readonly api = inject(TeaEegApi);
|
||||
readonly kind = input.required<'train' | 'analyze'>();
|
||||
readonly jobId = input.required<string>();
|
||||
readonly running = input(false);
|
||||
readonly sample = signal<RunProgress | null>(null);
|
||||
readonly message = signal('Cargando progreso…');
|
||||
readonly dashboard = signal<string | null>(null);
|
||||
private readonly clock = signal(Date.now());
|
||||
private key = '';
|
||||
readonly stale = computed(() => {
|
||||
const sample = this.sample();
|
||||
return this.running() && sample !== null && this.clock() - Date.parse(sample.updated_at) > 10_000;
|
||||
});
|
||||
readonly eta = computed(() => {
|
||||
const seconds = this.sample()?.eta_s;
|
||||
return seconds == null ? 'calculando…' : `≈ ${formatDuration(seconds)}`;
|
||||
});
|
||||
readonly duration = formatDuration;
|
||||
readonly trends = [
|
||||
{ key: 'cpu_pct', label: 'CPU (%)' },
|
||||
{ key: 'memory_pct', label: 'RAM (%)' },
|
||||
{ key: 'done', label: 'Procesados' },
|
||||
] as const;
|
||||
|
||||
constructor() {
|
||||
effect((cleanup) => {
|
||||
const kind = this.kind();
|
||||
const id = this.jobId();
|
||||
const running = this.running();
|
||||
const key = `${kind}/${id}`;
|
||||
if (this.key !== key) {
|
||||
this.key = key;
|
||||
this.sample.set(null);
|
||||
this.message.set('Cargando progreso…');
|
||||
}
|
||||
const read = () => this.api.runProgress(kind, id).pipe(catchError((error) => {
|
||||
const missing = running ? 'Esperando la primera medición' : 'Sin mediciones disponibles.';
|
||||
this.message.set(error.status === 404 && !this.sample() ? missing : 'No se pudo consultar el progreso.');
|
||||
return of(null);
|
||||
}));
|
||||
this.clock.set(Date.now());
|
||||
const subscription = (running ? timer(2000, 2000).pipe(startWith(0), exhaustMap(read)) : read()).subscribe((sample) => {
|
||||
this.clock.set(Date.now());
|
||||
if (sample) {
|
||||
this.sample.set(sample);
|
||||
this.message.set('');
|
||||
}
|
||||
});
|
||||
const clock = running ? timer(1000, 1000).subscribe(() => this.clock.set(Date.now())) : undefined;
|
||||
cleanup(() => {
|
||||
subscription.unsubscribe();
|
||||
clock?.unsubscribe();
|
||||
});
|
||||
});
|
||||
|
||||
const remote = computed(() => {
|
||||
const cluster = this.sample()?.cluster;
|
||||
return cluster?.mode === 'remote' ? cluster.scheduler ?? '' : null;
|
||||
});
|
||||
effect((cleanup) => {
|
||||
const scheduler = remote();
|
||||
this.dashboard.set(null);
|
||||
if (scheduler === null) return;
|
||||
const request = this.api.clusterStatus({ mode: 'remote', scheduler: scheduler || undefined }).subscribe({
|
||||
next: (status) => this.dashboard.set(clusterDashboardUrl(status)),
|
||||
error: () => this.dashboard.set(null),
|
||||
});
|
||||
cleanup(() => request.unsubscribe());
|
||||
});
|
||||
}
|
||||
|
||||
/** A reading with at most one decimal, for display. */
|
||||
fixed(value: number): number {
|
||||
return Math.round(value * 10) / 10;
|
||||
}
|
||||
|
||||
percent(value: number): number {
|
||||
return Math.max(0, Math.min(100, value));
|
||||
}
|
||||
|
||||
ram(worker: WorkerSample): number | null {
|
||||
return worker.memory_limit ? this.percent(100 * worker.memory_bytes / worker.memory_limit) : null;
|
||||
}
|
||||
|
||||
workerDetails(worker: WorkerSample): string {
|
||||
return `${worker.executing}/${worker.threads} hilos ejecutando · ${worker.memory_bytes} / ${worker.memory_limit ?? 'sin límite'} bytes`;
|
||||
}
|
||||
|
||||
sparkline(history: RunProgress['history'], key: 'cpu_pct' | 'memory_pct' | 'done', total: number): string {
|
||||
const start = history[0]?.t ?? 0;
|
||||
const span = Math.max(1, (history.at(-1)?.t ?? start) - start);
|
||||
const max = Math.max(1, key === 'done' ? total : 100, ...history.map((point) => point[key]));
|
||||
return history.map((point) => `${2 + 116 * (point.t - start) / span},${30 - 28 * point[key] / max}`).join(' ');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<section class="base">
|
||||
<div class="base__block">
|
||||
<h3 class="base__title">Exportar</h3>
|
||||
<div class="base__row">
|
||||
<mat-checkbox [checked]="includeProduction()" (change)="includeProduction.set($event.checked)">
|
||||
Incluir las versiones promovidas a producción
|
||||
</mat-checkbox>
|
||||
<a mat-stroked-button [href]="exportUrl()" download="baselines.zip" (click)="onExportClicked()">
|
||||
<mat-icon aria-hidden="true">download</mat-icon>Exportar
|
||||
</a>
|
||||
</div>
|
||||
@if (exportClicked()) {
|
||||
<p class="base__muted">La huella sha256 del paquete viene en la cabecera <code>X-Baselines-Sha256</code> de la respuesta.</p>
|
||||
<div class="base__row">
|
||||
<button mat-button type="button" (click)="computeHash()" [disabled]="hashing()">
|
||||
<mat-icon aria-hidden="true">fingerprint</mat-icon>
|
||||
{{ hashing() ? 'Calculando…' : 'Calcular huella' }}
|
||||
</button>
|
||||
@if (hash(); as result) {
|
||||
<span class="base__hash">sha256: {{ result.sha256 }}</span>
|
||||
@if (result.matches === true) {
|
||||
<span class="base__ok"><mat-icon aria-hidden="true">check_circle</mat-icon>Coincide con la cabecera</span>
|
||||
}
|
||||
@if (result.matches === false) {
|
||||
<span class="base__warn"><mat-icon aria-hidden="true">warning</mat-icon>No coincide con la cabecera X-Baselines-Sha256</span>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
@if (hashError(); as error) {
|
||||
<p class="base__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="base__block">
|
||||
<h3 class="base__title">Importar</h3>
|
||||
<div class="base__row">
|
||||
<label class="base__file">
|
||||
Paquete baselines.zip
|
||||
<input type="file" accept=".zip" (change)="onImportPicked($event)" [disabled]="importing()" />
|
||||
</label>
|
||||
<button mat-stroked-button type="button" (click)="import()" [disabled]="importing() || !importFile()">
|
||||
<mat-icon aria-hidden="true">upload</mat-icon>Importar
|
||||
</button>
|
||||
</div>
|
||||
@if (importing()) {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Importando"></mat-progress-bar>
|
||||
}
|
||||
@if (importError(); as error) {
|
||||
<p class="base__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
|
||||
}
|
||||
@if (importResult(); as result) {
|
||||
<p class="base__hash">sha256: {{ result.sha256 }}</p>
|
||||
@if (result.imported.length) {
|
||||
<table mat-table [dataSource]="result.imported" class="base__table" aria-label="Líneas base importadas">
|
||||
<ng-container matColumnDef="scenario">
|
||||
<th mat-header-cell *matHeaderCellDef>Escenario</th>
|
||||
<td mat-cell *matCellDef="let row">{{ row.scenario }}</td>
|
||||
</ng-container>
|
||||
<ng-container matColumnDef="version">
|
||||
<th mat-header-cell *matHeaderCellDef>Versión</th>
|
||||
<td mat-cell *matCellDef="let row">{{ row.version }}</td>
|
||||
</ng-container>
|
||||
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
|
||||
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
|
||||
</table>
|
||||
} @else {
|
||||
<p class="base__muted">El paquete no traía líneas base.</p>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
@@ -0,0 +1,81 @@
|
||||
.base {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-4);
|
||||
max-width: 860px;
|
||||
}
|
||||
|
||||
.base__block {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.base__title {
|
||||
font: var(--mat-sys-title-small);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.base__row {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.base__muted {
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
font: var(--mat-sys-body-small);
|
||||
margin: 0;
|
||||
|
||||
code {
|
||||
font-family: monospace;
|
||||
}
|
||||
}
|
||||
|
||||
.base__alert {
|
||||
align-items: center;
|
||||
background: var(--mat-sys-error-container);
|
||||
color: var(--mat-sys-on-error-container);
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
}
|
||||
|
||||
.base__hash {
|
||||
font-family: monospace;
|
||||
margin: 0;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.base__ok {
|
||||
align-items: center;
|
||||
color: var(--mat-sys-primary);
|
||||
display: inline-flex;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.base__warn {
|
||||
align-items: center;
|
||||
color: #9a6a00;
|
||||
display: inline-flex;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.base__file {
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font: var(--mat-sys-body-small);
|
||||
gap: var(--space-1);
|
||||
|
||||
input {
|
||||
color: var(--mat-sys-on-surface);
|
||||
font: var(--mat-sys-body-medium);
|
||||
}
|
||||
}
|
||||
|
||||
.base__table {
|
||||
width: 100%;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Covers the baselines step: the export link points at the contract's URL (with `production=0` when the
|
||||
* production versions are excluded), clicking it offers the hash check whose button downloads the blob and
|
||||
* renders the computed sha256 against `X-Baselines-Sha256`, and the import posts the zip and renders the
|
||||
* sha256 and scenario/version table or the 400/409 message. Fixtures: `HttpTestingController`; the digest
|
||||
* is stubbed so no real hashing runs.
|
||||
*/
|
||||
import { HttpEventType } from '@angular/common/http';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { BaselinesStep } from './baselines-step';
|
||||
|
||||
const EXPORT_URL = '/governance/tea/baselines/export';
|
||||
const IMPORT_URL = '/governance/tea/baselines/import';
|
||||
|
||||
const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
describe('BaselinesStep', () => {
|
||||
let http: HttpTestingController;
|
||||
let fixture: ComponentFixture<BaselinesStep>;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('crypto', {
|
||||
subtle: { digest: vi.fn().mockResolvedValue(new Uint8Array([0xab, 0xcd]).buffer) },
|
||||
});
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
fixture = TestBed.createComponent(BaselinesStep);
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => {
|
||||
http.verify();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
function link(): HTMLAnchorElement {
|
||||
return fixture.nativeElement.querySelector('a[download]');
|
||||
}
|
||||
|
||||
function buttonByText(text: string): HTMLButtonElement {
|
||||
return Array.from<HTMLButtonElement>(fixture.nativeElement.querySelectorAll('button')).find((b) =>
|
||||
b.textContent?.includes(text),
|
||||
)!;
|
||||
}
|
||||
|
||||
// Fails if the export link loses the environment, or the checkbox stops toggling production=0.
|
||||
it('links the export of environment prod, honoring the production checkbox', () => {
|
||||
expect(link().href).toContain(`${EXPORT_URL}?environment=prod`);
|
||||
expect(link().href).not.toContain('production=0');
|
||||
|
||||
fixture.componentInstance.includeProduction.set(false);
|
||||
fixture.detectChanges();
|
||||
expect(link().href).toContain('production=0');
|
||||
});
|
||||
|
||||
// Fails if the note or the hash button stop appearing after the click, if the blob isn't hashed, or if
|
||||
// the header comparison is dropped.
|
||||
it('computes the sha256 of the downloaded blob after the export click', async () => {
|
||||
link().click();
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('X-Baselines-Sha256');
|
||||
|
||||
buttonByText('Calcular huella').click();
|
||||
const req = http.expectOne((r) => r.url.startsWith(EXPORT_URL));
|
||||
expect(req.request.responseType).toBe('blob');
|
||||
req.flush(new Blob(['zip']), { headers: { 'X-Baselines-Sha256': 'abcd' } });
|
||||
await flush();
|
||||
await flush();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.nativeElement.textContent).toContain('sha256: abcd');
|
||||
expect(fixture.nativeElement.textContent).toContain('Coincide con la cabecera');
|
||||
});
|
||||
|
||||
// Fails if the import stops posting the zip under the import route, or the result table loses columns.
|
||||
it('imports the zip and lists the sha256 and the imported scenario/version pairs', () => {
|
||||
const step = fixture.componentInstance;
|
||||
step.importFile.set(new File(['zip'], 'baselines.zip'));
|
||||
step.import();
|
||||
fixture.detectChanges();
|
||||
|
||||
const req = http.expectOne(IMPORT_URL);
|
||||
expect(req.request.method).toBe('POST');
|
||||
expect(((req.request.body as FormData).get('file') as File).name).toBe('baselines.zip');
|
||||
req.event({ type: HttpEventType.UploadProgress, loaded: 1, total: 2 });
|
||||
req.flush({ sha256: 'f0f0', imported: [{ scenario: 'tea-eeg-nsr', version: 3 }, { scenario: 'tea-eeg-alpha', version: 2 }] });
|
||||
fixture.detectChanges();
|
||||
|
||||
const text = fixture.nativeElement.textContent as string;
|
||||
expect(text).toContain('sha256: f0f0');
|
||||
expect(text).toContain('tea-eeg-nsr');
|
||||
expect(text).toContain('tea-eeg-alpha');
|
||||
});
|
||||
|
||||
// Fails if the 400/409 message is replaced by a generic one, or a failed import still shows results.
|
||||
it('shows the server message when the import is rejected', () => {
|
||||
const step = fixture.componentInstance;
|
||||
step.importFile.set(new File(['zip'], 'baselines.zip'));
|
||||
step.import();
|
||||
http.expectOne(IMPORT_URL).flush({ error: 'El paquete ya fue importado' }, { status: 409, statusText: 'Conflict' });
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.nativeElement.textContent).toContain('El paquete ya fue importado');
|
||||
expect(step.importResult()).toBeNull();
|
||||
expect(buttonByText('Importar').disabled).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import { HttpClient, HttpEventType } from '@angular/common/http';
|
||||
import { Component, DestroyRef, computed, inject, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatTableModule } from '@angular/material/table';
|
||||
import { apiErrorMessage } from '../../../../connect/api/api.types';
|
||||
import { TeaEegApi } from '../../../api/tea-eeg.api';
|
||||
import { BaselineImport } from '../../../api/tea-eeg.types';
|
||||
|
||||
/** Hex of a digest, lowercase. */
|
||||
export function sha256Hex(digest: ArrayBuffer): string {
|
||||
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* The baselines step: the promoted baselines download as a zip from the export route (optionally without
|
||||
* the production versions), and the import route reads a bundle back, showing its sha256 and the imported
|
||||
* scenario/version pairs. After exporting, the sha256 can be recomputed from the downloaded bytes and
|
||||
* compared with the response's `X-Baselines-Sha256` header.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-baselines-step',
|
||||
imports: [MatButtonModule, MatCheckboxModule, MatIconModule, MatProgressBarModule, MatTableModule],
|
||||
templateUrl: './baselines-step.html',
|
||||
styleUrl: './baselines-step.scss',
|
||||
})
|
||||
export class BaselinesStep {
|
||||
private readonly tea = inject(TeaEegApi);
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
/** Checked: the zip includes the production versions; unchecked asks for `production=0`. */
|
||||
readonly includeProduction = signal(true);
|
||||
readonly exportUrl = computed(() => this.tea.baselinesExportUrl('prod', this.includeProduction() ? undefined : false));
|
||||
readonly exportClicked = signal(false);
|
||||
readonly hashing = signal(false);
|
||||
readonly hash = signal<{ sha256: string; matches: boolean | null } | null>(null);
|
||||
readonly hashError = signal<string | null>(null);
|
||||
readonly importFile = signal<File | null>(null);
|
||||
readonly importing = signal(false);
|
||||
readonly importResult = signal<BaselineImport | null>(null);
|
||||
readonly importError = signal<string | null>(null);
|
||||
readonly displayedColumns = ['scenario', 'version'];
|
||||
|
||||
onExportClicked(): void {
|
||||
this.exportClicked.set(true);
|
||||
}
|
||||
|
||||
/** Downloads the same zip and hashes it, to compare against the header the export answers with. */
|
||||
computeHash(): void {
|
||||
this.hashing.set(true);
|
||||
this.hashError.set(null);
|
||||
this.http
|
||||
.get(this.exportUrl(), { responseType: 'blob', observe: 'response' })
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: (response) => void this.digest(response.body!, response.headers.get('X-Baselines-Sha256')),
|
||||
error: (error) => {
|
||||
this.hashing.set(false);
|
||||
this.hashError.set(apiErrorMessage(error, 'No se pudo descargar el paquete.'));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async digest(blob: Blob, header: string | null): Promise<void> {
|
||||
try {
|
||||
const digest = await crypto.subtle.digest('SHA-256', await blob.arrayBuffer());
|
||||
this.hash.set({ sha256: sha256Hex(digest), matches: header ? header === sha256Hex(digest) : null });
|
||||
} catch {
|
||||
this.hashError.set('No se pudo calcular la huella en este navegador.');
|
||||
}
|
||||
this.hashing.set(false);
|
||||
}
|
||||
|
||||
onImportPicked(event: Event): void {
|
||||
const input = event.target as HTMLInputElement;
|
||||
this.importFile.set(input.files?.[0] ?? null);
|
||||
this.importResult.set(null);
|
||||
this.importError.set(null);
|
||||
}
|
||||
|
||||
import(): void {
|
||||
const file = this.importFile();
|
||||
if (!file || this.importing()) return;
|
||||
this.importing.set(true);
|
||||
this.importError.set(null);
|
||||
this.importResult.set(null);
|
||||
this.tea
|
||||
.importBaselines(file)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: (event) => {
|
||||
if (event.type === HttpEventType.Response) {
|
||||
this.importing.set(false);
|
||||
this.importResult.set(event.body!);
|
||||
}
|
||||
},
|
||||
error: (error) => {
|
||||
this.importing.set(false);
|
||||
this.importError.set(apiErrorMessage(error, 'No se pudo importar el paquete.'));
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<section class="promote">
|
||||
<div class="promote__toolbar">
|
||||
<h3 class="promote__title">Requisitos y promoción</h3>
|
||||
<span class="promote__spacer"></span>
|
||||
<button mat-flat-button type="button" color="primary" (click)="promoteAll()" [disabled]="promoting() || loading() || !rows().length">
|
||||
<mat-icon aria-hidden="true">rocket_launch</mat-icon>
|
||||
{{ promoting() ? 'Promoviendo…' : 'Promover todas' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@if (loading()) {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando versiones"></mat-progress-bar>
|
||||
}
|
||||
@if (loadError(); as error) {
|
||||
<p class="promote__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
|
||||
}
|
||||
@if (!loading() && !loadError()) {
|
||||
@if (rows().length) {
|
||||
<table mat-table [dataSource]="rows()" class="promote__table" aria-label="Versiones a promover">
|
||||
<ng-container matColumnDef="version">
|
||||
<th mat-header-cell *matHeaderCellDef>Versión</th>
|
||||
<td mat-cell *matCellDef="let row">
|
||||
<span class="promote__label">{{ row.version.name }}:{{ row.version.version }}</span>
|
||||
<app-model-status [status]="row.version.status"></app-model-status>
|
||||
</td>
|
||||
</ng-container>
|
||||
<ng-container matColumnDef="checks">
|
||||
<th mat-header-cell *matHeaderCellDef>Requisitos</th>
|
||||
<td mat-cell *matCellDef="let row">
|
||||
@if (row.checksError) {
|
||||
<span class="promote__fail"><mat-icon aria-hidden="true">error</mat-icon>{{ row.checksError }}</span>
|
||||
} @else if (row.checks === null) {
|
||||
<span class="promote__muted">Cargando requisitos…</span>
|
||||
} @else if (!row.checks.length) {
|
||||
<span class="promote__muted">Sin requisitos registrados.</span>
|
||||
} @else {
|
||||
<ul class="promote__checks">
|
||||
@for (check of row.checks; track check.code) {
|
||||
<li [class.promote__fail]="!check.passed">
|
||||
<mat-icon aria-hidden="true">{{ check.passed ? 'check_circle' : 'cancel' }}</mat-icon>
|
||||
<span>{{ check.requirement }}</span>
|
||||
@if (check.detail) {
|
||||
<span class="promote__detail">{{ check.detail }}</span>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
@if (row.status === 'failed') {
|
||||
@if (row.failing?.length) {
|
||||
<ul class="promote__checks">
|
||||
@for (check of row.failing; track check.code) {
|
||||
<li class="promote__fail">
|
||||
<mat-icon aria-hidden="true">error</mat-icon>
|
||||
<span>No pasó: {{ check.requirement }}</span>
|
||||
@if (check.detail) {
|
||||
<span class="promote__detail">{{ check.detail }}</span>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
} @else {
|
||||
<p class="promote__fail"><mat-icon aria-hidden="true">error</mat-icon>{{ row.error }}</p>
|
||||
}
|
||||
}
|
||||
</td>
|
||||
</ng-container>
|
||||
<ng-container matColumnDef="status">
|
||||
<th mat-header-cell *matHeaderCellDef>Estado</th>
|
||||
<td mat-cell *matCellDef="let row">
|
||||
@if (row.status === 'promoting') {
|
||||
<span class="promote__muted"><mat-progress-bar mode="indeterminate" class="promote__bar"></mat-progress-bar>Promoviendo…</span>
|
||||
} @else if (row.status === 'promoted') {
|
||||
<span class="promote__ok"><mat-icon aria-hidden="true">check_circle</mat-icon>Promovida</span>
|
||||
} @else if (row.status === 'failed') {
|
||||
<span class="promote__fail"><mat-icon aria-hidden="true">error</mat-icon>Falló</span>
|
||||
} @else {
|
||||
<span class="promote__muted">Pendiente</span>
|
||||
}
|
||||
</td>
|
||||
</ng-container>
|
||||
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
|
||||
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
|
||||
</table>
|
||||
} @else {
|
||||
<p class="promote__muted">No hay versiones eeg-* candidatas.</p>
|
||||
}
|
||||
}
|
||||
@if (summary(); as line) {
|
||||
<p class="promote__muted" role="status">{{ line }}</p>
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,95 @@
|
||||
.promote {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
max-width: 960px;
|
||||
}
|
||||
|
||||
.promote__toolbar {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.promote__title {
|
||||
font: var(--mat-sys-title-small);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.promote__spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.promote__alert {
|
||||
align-items: center;
|
||||
background: var(--mat-sys-error-container);
|
||||
color: var(--mat-sys-on-error-container);
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
}
|
||||
|
||||
.promote__muted {
|
||||
align-items: center;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
display: inline-flex;
|
||||
gap: var(--space-1);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.promote__table {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.promote__label {
|
||||
font-family: monospace;
|
||||
margin-right: var(--space-2);
|
||||
}
|
||||
|
||||
.promote__checks {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
list-style: none;
|
||||
margin: 0 0 var(--space-1);
|
||||
padding: 0;
|
||||
|
||||
li {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1);
|
||||
font: var(--mat-sys-body-small);
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
font-size: 16px;
|
||||
height: 16px;
|
||||
width: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.promote__ok {
|
||||
align-items: center;
|
||||
color: var(--mat-sys-primary);
|
||||
display: inline-flex;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.promote__fail {
|
||||
align-items: center;
|
||||
color: var(--mat-sys-error);
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.promote__detail {
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
}
|
||||
|
||||
.promote__bar {
|
||||
width: 120px;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Covers the promotion step: the candidate table loads each version's promotion checks, "Promover todas"
|
||||
* POSTs one promotion at a time with the button disabled while it runs, a 409 shows that version's
|
||||
* failing checks, and a closing line sums up the outcome. Fixtures: canned `ModelVersion[]` and checks
|
||||
* answers plus promote requests through `HttpTestingController`.
|
||||
*/
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { ModelVersion, PromotionCheck } from '../../../api/governance.types';
|
||||
import { PromoteStep } from './promote-step';
|
||||
|
||||
const VERSIONS_URL = '/governance/model-versions';
|
||||
|
||||
function version(scenario: string, v: string): ModelVersion {
|
||||
return {
|
||||
name: `tea-${scenario}`, version: v, run_id: 'r1',
|
||||
tags: { domain: 'tea', scenario }, metrics: {}, created_at: '2026-11-09T00:00:00+00:00', status: 'candidata',
|
||||
};
|
||||
}
|
||||
|
||||
const CHECKS: PromotionCheck[] = [
|
||||
{ code: 'MLD-01', requirement: 'Informes de validación', passed: true, detail: '' },
|
||||
{ code: 'MLD-02', requirement: 'Huella de la cohorte', passed: false, detail: 'falta el armado' },
|
||||
];
|
||||
|
||||
describe('PromoteStep', () => {
|
||||
let http: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
function create(): ComponentFixture<PromoteStep> {
|
||||
const fixture = TestBed.createComponent(PromoteStep);
|
||||
fixture.detectChanges();
|
||||
http.expectOne((r) => r.url === VERSIONS_URL).flush({ model_versions: [version('eeg-alpha', '2'), version('eeg-nsr', '3')] });
|
||||
http.expectOne((r) => r.url === '/governance/model-versions/tea/eeg-alpha/2/checks').flush({ ready: false, checks: CHECKS });
|
||||
http.expectOne((r) => r.url === '/governance/model-versions/tea/eeg-nsr/3/checks').flush({ ready: true, checks: [] });
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
// Fails if the checks stop rendering per version, or the failing one loses its detail.
|
||||
it('lists every candidate with its promotion checks', () => {
|
||||
const fixture = create();
|
||||
const rows = fixture.componentInstance.rows();
|
||||
expect(rows.map((r) => r.key)).toEqual(['eeg-alpha:2', 'eeg-nsr:3']);
|
||||
expect(rows[0].checks).toEqual(CHECKS);
|
||||
|
||||
const text = fixture.nativeElement.textContent as string;
|
||||
expect(text).toContain('Informes de validación');
|
||||
expect(text).toContain('Huella de la cohorte');
|
||||
expect(text).toContain('falta el armado');
|
||||
});
|
||||
|
||||
// Fails if promotions stop being sequential, the button stays enabled mid-run, or a 409's failing
|
||||
// checks are not shown.
|
||||
it('promotes one version at a time, disabling the button, and surfaces a 409 checks', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
const button = Array.from<HTMLButtonElement>(fixture.nativeElement.querySelectorAll('button')).find((b) =>
|
||||
b.textContent?.includes('Promover todas'),
|
||||
)!;
|
||||
step.promoteAll();
|
||||
fixture.detectChanges();
|
||||
expect(button.disabled).toBe(true);
|
||||
|
||||
const first = http.expectOne('/governance/model-versions/tea/eeg-alpha/2/promote');
|
||||
http.expectNone('/governance/model-versions/tea/eeg-nsr/3/promote');
|
||||
first.flush({});
|
||||
expect(step.rows()[0].status).toBe('promoted');
|
||||
|
||||
http.expectOne('/governance/model-versions/tea/eeg-nsr/3/promote').flush(
|
||||
{ checks: CHECKS },
|
||||
{ status: 409, statusText: 'Conflict' },
|
||||
);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(step.rows()[1].status).toBe('failed');
|
||||
expect(step.rows()[1].failing).toEqual([CHECKS[1]]);
|
||||
expect(button.disabled).toBe(false);
|
||||
const text = fixture.nativeElement.textContent as string;
|
||||
expect(text).toContain('No pasó: Huella de la cohorte');
|
||||
expect(text).toContain('Promovidas 1 de 2; 1 fallaron.');
|
||||
});
|
||||
|
||||
// Fails if a non-409 failure hides its message, or the summary claims everything was promoted.
|
||||
it('shows the error of a failed promotion without checks', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
step.promoteAll();
|
||||
http.expectOne('/governance/model-versions/tea/eeg-alpha/2/promote').flush({ error: 'MLflow no responde' }, { status: 503, statusText: 'Service Unavailable' });
|
||||
http.expectOne('/governance/model-versions/tea/eeg-nsr/3/promote').flush({});
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(step.rows()[0]).toMatchObject({ status: 'failed', error: 'MLflow no responde', failing: null });
|
||||
const text = fixture.nativeElement.textContent as string;
|
||||
expect(text).toContain('MLflow no responde');
|
||||
expect(text).toContain('Promovidas 1 de 2; 1 fallaron.');
|
||||
});
|
||||
|
||||
// Fails if the step keeps the list it read when the page opened, so versions imported or trained in an earlier
|
||||
// step never show up for promotion until the page is reloaded.
|
||||
it('lists the versions again when the step becomes active', () => {
|
||||
const fixture = create();
|
||||
fixture.componentRef.setInput('active', true);
|
||||
fixture.detectChanges();
|
||||
http.expectOne((r) => r.url === VERSIONS_URL).flush({ model_versions: [version('eeg-alpha', '2'), version('eeg-nsr', '3'), version('eeg-theta', '1')] });
|
||||
for (const scenario of ['eeg-alpha/2', 'eeg-nsr/3', 'eeg-theta/1']) {
|
||||
http.expectOne((r) => r.url === `/governance/model-versions/tea/${scenario}/checks`).flush({ ready: true, checks: [] });
|
||||
}
|
||||
fixture.detectChanges();
|
||||
expect(fixture.componentInstance.rows()).toHaveLength(3);
|
||||
fixture.destroy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import { Component, DestroyRef, OnInit, effect, inject, input, signal, untracked } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatTableModule } from '@angular/material/table';
|
||||
import { finalize } from 'rxjs';
|
||||
import { apiErrorMessage } from '../../../../connect/api/api.types';
|
||||
import { GovernanceApi } from '../../../api/governance.api';
|
||||
import { ModelVersion, PromotionCheck } from '../../../api/governance.types';
|
||||
import { ModelStatusChip } from '../../model-status-chip/model-status-chip';
|
||||
import { teaCandidates, versionKey } from '../tea-candidates';
|
||||
|
||||
/** One candidate version with its promotion checks and how its promotion went. */
|
||||
export interface PromoteRow {
|
||||
key: string;
|
||||
version: ModelVersion;
|
||||
checks: PromotionCheck[] | null;
|
||||
checksError: string | null;
|
||||
status: 'pending' | 'promoting' | 'promoted' | 'failed';
|
||||
failing: PromotionCheck[] | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The promotion step: the current eeg-* candidates with the checklist each must pass, and a button that
|
||||
* promotes them one request at a time. A 409 answers with the failing checks of that version, which are
|
||||
* shown next to it; a closing line sums up how many were promoted.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-promote-step',
|
||||
imports: [MatButtonModule, MatIconModule, MatProgressBarModule, MatTableModule, ModelStatusChip],
|
||||
templateUrl: './promote-step.html',
|
||||
styleUrl: './promote-step.scss',
|
||||
})
|
||||
export class PromoteStep implements OnInit {
|
||||
private readonly api = inject(GovernanceApi);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
readonly rows = signal<PromoteRow[]>([]);
|
||||
readonly loading = signal(false);
|
||||
readonly loadError = signal<string | null>(null);
|
||||
readonly promoting = signal(false);
|
||||
readonly summary = signal<string | null>(null);
|
||||
readonly displayedColumns = ['version', 'checks', 'status'];
|
||||
|
||||
/** True while the step is the one on screen: each time it turns true the versions are listed again. */
|
||||
readonly active = input(false);
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
if (this.active() && !untracked(() => this.promoting())) untracked(() => this.load());
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.load();
|
||||
}
|
||||
|
||||
private load(): void {
|
||||
this.loading.set(true);
|
||||
this.api
|
||||
.listModelVersions({ domain: 'tea' })
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: ({ model_versions }) => {
|
||||
this.loading.set(false);
|
||||
const rows = teaCandidates(model_versions).map((v) => ({
|
||||
key: versionKey(v),
|
||||
version: v,
|
||||
checks: null,
|
||||
checksError: null,
|
||||
status: 'pending' as const,
|
||||
failing: null,
|
||||
error: null,
|
||||
}));
|
||||
this.rows.set(rows);
|
||||
rows.forEach((row) => this.loadChecks(row.key));
|
||||
},
|
||||
error: (error) => {
|
||||
this.loading.set(false);
|
||||
this.loadError.set(apiErrorMessage(error, 'No se pudieron cargar las versiones.'));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private loadChecks(key: string): void {
|
||||
const row = this.rows().find((r) => r.key === key)!;
|
||||
this.api
|
||||
.checks('tea', row.version.tags.scenario!, row.version.version)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: ({ checks }) => this.patch(key, { checks }),
|
||||
error: (error) => this.patch(key, { checksError: apiErrorMessage(error, 'No se pudieron cargar los requisitos.') }),
|
||||
});
|
||||
}
|
||||
|
||||
/** Promotes every row, one request at a time; a failure doesn't stop the rest. */
|
||||
promoteAll(): void {
|
||||
if (this.promoting() || !this.rows().length) return;
|
||||
this.promoting.set(true);
|
||||
this.summary.set(null);
|
||||
this.promoteNext(0);
|
||||
}
|
||||
|
||||
private promoteNext(index: number): void {
|
||||
const rows = this.rows();
|
||||
if (index >= rows.length) {
|
||||
this.promoting.set(false);
|
||||
const promoted = rows.filter((r) => r.status === 'promoted').length;
|
||||
this.summary.set(
|
||||
promoted === rows.length
|
||||
? `Promovidas ${promoted} de ${rows.length}.`
|
||||
: `Promovidas ${promoted} de ${rows.length}; ${rows.length - promoted} fallaron.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const row = rows[index];
|
||||
this.patch(row.key, { status: 'promoting' });
|
||||
this.api
|
||||
.promoteModelVersion('tea', row.version.tags.scenario!, row.version.version)
|
||||
.pipe(
|
||||
takeUntilDestroyed(this.destroyRef),
|
||||
finalize(() => this.promoteNext(index + 1)),
|
||||
)
|
||||
.subscribe({
|
||||
next: () => this.patch(row.key, { status: 'promoted' }),
|
||||
error: (error) =>
|
||||
this.patch(row.key, {
|
||||
status: 'failed',
|
||||
error: apiErrorMessage(error, 'No se pudo promover la versión.'),
|
||||
failing: failingChecks(error),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
private patch(key: string, partial: Partial<PromoteRow>): void {
|
||||
this.rows.set(this.rows().map((r) => (r.key === key ? { ...r, ...partial } : r)));
|
||||
}
|
||||
}
|
||||
|
||||
/** The checks a 409 answers with, limited to the ones that didn't pass. */
|
||||
function failingChecks(error: unknown): PromotionCheck[] | null {
|
||||
const checks = (error as { error?: { checks?: PromotionCheck[] } })?.error?.checks;
|
||||
return checks ? checks.filter((check) => !check.passed) : null;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<section class="ref">
|
||||
<h3 class="ref__title">Cohortes en el volumen de referencia</h3>
|
||||
@if (loading()) {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando cohortes"></mat-progress-bar>
|
||||
}
|
||||
@if (loadError(); as error) {
|
||||
<p class="ref__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
|
||||
}
|
||||
|
||||
@if (!loading() && !loadError()) {
|
||||
@if (cohorts().length) {
|
||||
<table mat-table [dataSource]="cohorts()" class="ref__table" aria-label="Cohortes de referencia">
|
||||
<ng-container matColumnDef="name">
|
||||
<th mat-header-cell *matHeaderCellDef>Nombre</th>
|
||||
<td mat-cell *matCellDef="let c">{{ c.name }}</td>
|
||||
</ng-container>
|
||||
<ng-container matColumnDef="edfs">
|
||||
<th mat-header-cell *matHeaderCellDef>EDF</th>
|
||||
<td mat-cell *matCellDef="let c">{{ c.edfs | number }}</td>
|
||||
</ng-container>
|
||||
<ng-container matColumnDef="size">
|
||||
<th mat-header-cell *matHeaderCellDef>Tamaño</th>
|
||||
<td mat-cell *matCellDef="let c">{{ tamano(c.size_bytes) }}</td>
|
||||
</ng-container>
|
||||
<ng-container matColumnDef="ages">
|
||||
<th mat-header-cell *matHeaderCellDef>Edades</th>
|
||||
<td mat-cell *matCellDef="let c">{{ c.has_ages ? 'Sí' : 'No' }}</td>
|
||||
</ng-container>
|
||||
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
|
||||
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
|
||||
</table>
|
||||
} @else {
|
||||
<p class="ref__muted">Aún no hay cohortes; sube la primera abajo.</p>
|
||||
}
|
||||
}
|
||||
|
||||
@if (choice().mode === 'remote') {
|
||||
<p class="ref__note"><mat-icon aria-hidden="true">warning</mat-icon>En modo remoto los archivos subidos quedan en este servidor, no en el volumen que ven los trabajadores.</p>
|
||||
}
|
||||
|
||||
<form class="ref__upload" (ngSubmit)="upload()">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Nombre de la cohorte</mat-label>
|
||||
<input matInput [formControl]="name" placeholder="referencia_2026" />
|
||||
@if (name.hasError('pattern') || name.hasError('required')) {
|
||||
<mat-error>1 a 64 caracteres: letras, dígitos, punto, guion o guion bajo.</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
<label class="ref__files">
|
||||
Archivos (.edf o edades.csv)
|
||||
<input type="file" multiple accept=".edf,.csv" (change)="onFilesPicked($event)" [disabled]="uploading() || rootMissing()" />
|
||||
</label>
|
||||
<button mat-stroked-button type="submit" [disabled]="uploading() || name.invalid || !selectedFiles().length || rootMissing()">
|
||||
<mat-icon aria-hidden="true">upload</mat-icon>Subir {{ selectedFiles().length ? '(' + selectedFiles().length + ')' : '' }}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
@if (uploads().length) {
|
||||
<ul class="ref__results">
|
||||
@for (item of uploads(); track item.fileName) {
|
||||
<li [class.ref__result--error]="item.status === 'error'">
|
||||
<mat-icon aria-hidden="true">{{ item.status === 'done' ? 'check_circle' : item.status === 'error' ? 'error' : 'cloud_upload' }}</mat-icon>
|
||||
<span class="ref__file">{{ item.fileName }}</span>
|
||||
@if (item.status === 'uploading') {
|
||||
<mat-progress-bar class="ref__progress" [mode]="item.progress === null ? 'indeterminate' : 'determinate'" [value]="item.progress ?? 0"></mat-progress-bar>
|
||||
}
|
||||
<span class="ref__detail">{{ item.detail }}</span>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,89 @@
|
||||
.ref {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
max-width: 860px;
|
||||
}
|
||||
|
||||
.ref__title {
|
||||
font: var(--mat-sys-title-small);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.ref__alert {
|
||||
align-items: center;
|
||||
background: var(--mat-sys-error-container);
|
||||
color: var(--mat-sys-on-error-container);
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
}
|
||||
|
||||
.ref__muted {
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.ref__table {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.ref__note {
|
||||
align-items: center;
|
||||
background: var(--mat-sys-tertiary-container);
|
||||
color: var(--mat-sys-on-tertiary-container);
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
}
|
||||
|
||||
.ref__upload {
|
||||
align-items: flex-start;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.ref__files {
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font: var(--mat-sys-body-small);
|
||||
gap: var(--space-1);
|
||||
|
||||
input {
|
||||
color: var(--mat-sys-on-surface);
|
||||
font: var(--mat-sys-body-medium);
|
||||
}
|
||||
}
|
||||
|
||||
.ref__results {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
|
||||
li {
|
||||
align-items: center;
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
grid-template-columns: auto minmax(120px, auto) 1fr auto;
|
||||
}
|
||||
}
|
||||
|
||||
.ref__result--error {
|
||||
color: var(--mat-sys-error);
|
||||
}
|
||||
|
||||
.ref__file {
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.ref__detail {
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
font: var(--mat-sys-body-small);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* Covers the reference step: the cohort table renders sizes as MB/GB and ages as Sí/No, files upload one
|
||||
* request at a time with progress and a per-file result, the table reloads when the batch ends, a 503
|
||||
* disables the upload, a bad cohort name blocks it, and a failed file doesn't stop the rest. Fixtures:
|
||||
* canned `ReferenceCohort[]` answers and multipart uploads through `HttpTestingController`.
|
||||
*/
|
||||
import { HttpEventType } from '@angular/common/http';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { ReferenceCohort } from '../../../api/tea-eeg.types';
|
||||
import { ReferenceStep, tamano } from './reference-step';
|
||||
|
||||
const LIST_URL = '/governance/tea/reference-cohorts';
|
||||
const UPLOAD_URL = '/governance/tea/reference-cohorts/referencia_2026/files';
|
||||
|
||||
const COHORTS: ReferenceCohort[] = [
|
||||
{ name: 'referencia_2026', edfs: 120, size_bytes: 2.4e9, has_ages: true, path: '/ref/referencia_2026' },
|
||||
{ name: 'otra', edfs: 3, size_bytes: 5.2e6, has_ages: false, path: '/ref/otra' },
|
||||
];
|
||||
|
||||
describe('ReferenceStep', () => {
|
||||
let http: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
function create(choice = { mode: 'auto' as const }): ComponentFixture<ReferenceStep> {
|
||||
const fixture = TestBed.createComponent(ReferenceStep);
|
||||
fixture.componentRef.setInput('choice', choice);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(LIST_URL).flush(COHORTS);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
function subirButton(fixture: ComponentFixture<ReferenceStep>): HTMLButtonElement {
|
||||
return Array.from<HTMLButtonElement>(fixture.nativeElement.querySelectorAll('button')).find((b) =>
|
||||
b.textContent?.includes('Subir'),
|
||||
)!;
|
||||
}
|
||||
|
||||
// Fails if the columns stop rendering, or sizes and ages lose their units/words.
|
||||
it('lists the cohorts with their size in MB/GB and whether ages are present', () => {
|
||||
const fixture = create();
|
||||
const text = fixture.nativeElement.textContent as string;
|
||||
expect(text).toContain('referencia_2026');
|
||||
expect(text).toContain('120');
|
||||
expect(text).toContain('2.4 GB');
|
||||
expect(text).toContain('5.2 MB');
|
||||
expect(text).toContain('Sí');
|
||||
expect(text).toContain('No');
|
||||
expect(tamano(999e9)).toBe('999.0 GB');
|
||||
});
|
||||
|
||||
// Fails if files stop uploading one at a time, lose their progress/result, or the table doesn't reload.
|
||||
it('uploads the files sequentially with progress and refreshes the table', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
step.name.setValue('referencia_2026');
|
||||
step.selectedFiles.set([new File(['a'], 'a.edf'), new File(['b'], 'b.edf')]);
|
||||
step.upload();
|
||||
fixture.detectChanges();
|
||||
|
||||
const first = http.expectOne(UPLOAD_URL);
|
||||
http.expectNone(() => true);
|
||||
first.event({ type: HttpEventType.UploadProgress, loaded: 50, total: 100 });
|
||||
expect(step.uploads()[0]).toMatchObject({ fileName: 'a.edf', progress: 50, status: 'uploading', detail: '50%' });
|
||||
|
||||
first.flush({ name: 'referencia_2026', file: 'a.edf', size_bytes: 4e6 });
|
||||
expect(step.uploads()[0].status).toBe('done');
|
||||
const second = http.expectOne(UPLOAD_URL);
|
||||
second.flush({ name: 'referencia_2026', file: 'b.edf', size_bytes: 8e6 });
|
||||
|
||||
const reload = http.expectOne(LIST_URL);
|
||||
reload.flush([...COHORTS, { name: 'nueva', edfs: 1, size_bytes: 1e6, has_ages: false, path: '/ref/nueva' }]);
|
||||
fixture.detectChanges();
|
||||
expect(step.uploads().map((u) => u.status)).toEqual(['done', 'done']);
|
||||
expect(step.uploads()[1].detail).toContain('b.edf guardado');
|
||||
expect(step.cohorts().map((c) => c.name)).toEqual(['referencia_2026', 'otra', 'nueva']);
|
||||
expect(step.selectedFiles()).toEqual([]);
|
||||
});
|
||||
|
||||
// Fails if a 503 stops disabling the upload, or the server's message is replaced by a generic one.
|
||||
it('shows the server message and disables the upload when the volume answers 503', () => {
|
||||
const fixture = TestBed.createComponent(ReferenceStep);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(LIST_URL).flush({ error: 'TEA_REFERENCE_ROOT no está configurado' }, { status: 503, statusText: 'Service Unavailable' });
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.nativeElement.textContent).toContain('TEA_REFERENCE_ROOT no está configurado');
|
||||
expect(fixture.componentInstance.rootMissing()).toBe(true);
|
||||
expect(subirButton(fixture).disabled).toBe(true);
|
||||
});
|
||||
|
||||
// Fails if a bad cohort name still uploads, or the pattern loosens beyond the route's.
|
||||
it('blocks the upload until the cohort name matches the route pattern', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
step.name.setValue('nombre inválido');
|
||||
step.selectedFiles.set([new File(['a'], 'a.edf')]);
|
||||
step.upload();
|
||||
http.expectNone(() => true);
|
||||
|
||||
step.name.setValue('referencia_2026');
|
||||
expect(step.name.valid).toBe(true);
|
||||
});
|
||||
|
||||
// Fails if a failed file stops the batch, hides its error, or skips the final reload.
|
||||
it('keeps uploading after a failed file and still refreshes the table', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
step.name.setValue('referencia_2026');
|
||||
step.selectedFiles.set([new File(['a'], 'a.edf'), new File(['b'], 'b.edf')]);
|
||||
step.upload();
|
||||
|
||||
http.expectOne(UPLOAD_URL).flush({ name: 'referencia_2026', file: 'a.edf', size_bytes: 4e6 });
|
||||
http.expectOne(UPLOAD_URL).flush({ error: 'EDF inválido' }, { status: 400, statusText: 'Bad Request' });
|
||||
http.expectOne(LIST_URL).flush(COHORTS);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(step.uploads().map((u) => u.status)).toEqual(['done', 'error']);
|
||||
expect(step.uploads()[1].detail).toBe('EDF inválido');
|
||||
expect(fixture.nativeElement.textContent).toContain('EDF inválido');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { HttpEventType } from '@angular/common/http';
|
||||
import { Component, DestroyRef, OnInit, inject, input, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatTableModule } from '@angular/material/table';
|
||||
import { finalize } from 'rxjs';
|
||||
import { apiErrorMessage } from '../../../../connect/api/api.types';
|
||||
import { TeaEegApi } from '../../../api/tea-eeg.api';
|
||||
import { ClusterChoice, ReferenceCohort } from '../../../api/tea-eeg.types';
|
||||
|
||||
/** Cohort names the volume accepts; mirrors the route's `[A-Za-z0-9._-]{1,64}`. */
|
||||
export const NOMBRE_COHORTE = /^[A-Za-z0-9._-]{1,64}$/;
|
||||
|
||||
export interface UploadItem {
|
||||
fileName: string;
|
||||
progress: number | null;
|
||||
status: 'uploading' | 'done' | 'error';
|
||||
detail: string;
|
||||
}
|
||||
|
||||
/** Human size of a cohort folder. */
|
||||
export function tamano(bytes: number): string {
|
||||
if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;
|
||||
return `${(bytes / 1e6).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference step: the cohorts already on the shared volume with their EDF count, size and whether
|
||||
* ages are present, and the upload of more files. Files go up one request at a time with a progress bar
|
||||
* and a per-file result; the table refreshes when the batch ends. A 503 means `TEA_REFERENCE_ROOT` is
|
||||
* not configured and disables the upload.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-reference-step',
|
||||
imports: [
|
||||
DecimalPipe,
|
||||
MatButtonModule,
|
||||
MatFormFieldModule,
|
||||
MatIconModule,
|
||||
MatInputModule,
|
||||
MatProgressBarModule,
|
||||
MatTableModule,
|
||||
ReactiveFormsModule,
|
||||
],
|
||||
templateUrl: './reference-step.html',
|
||||
styleUrl: './reference-step.scss',
|
||||
})
|
||||
export class ReferenceStep implements OnInit {
|
||||
private readonly api = inject(TeaEegApi);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
/** The picked cluster; 'remote' uploads don't reach the workers' volume. */
|
||||
readonly choice = input<ClusterChoice>({ mode: 'auto' });
|
||||
readonly cohorts = signal<ReferenceCohort[]>([]);
|
||||
readonly loading = signal(false);
|
||||
readonly loadError = signal<string | null>(null);
|
||||
/** The volume isn't configured (503); nothing to list or upload. */
|
||||
readonly rootMissing = signal(false);
|
||||
readonly name = new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.pattern(NOMBRE_COHORTE)] });
|
||||
readonly selectedFiles = signal<File[]>([]);
|
||||
readonly uploads = signal<UploadItem[]>([]);
|
||||
readonly uploading = signal(false);
|
||||
readonly displayedColumns = ['name', 'edfs', 'size', 'ages'];
|
||||
protected readonly tamano = tamano;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.load();
|
||||
}
|
||||
|
||||
load(): void {
|
||||
this.loading.set(true);
|
||||
this.api
|
||||
.listReferenceCohorts()
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: (cohorts) => {
|
||||
this.loading.set(false);
|
||||
this.cohorts.set(cohorts);
|
||||
this.loadError.set(null);
|
||||
},
|
||||
error: (error) => {
|
||||
this.loading.set(false);
|
||||
if (error?.status === 503) this.rootMissing.set(true);
|
||||
this.loadError.set(apiErrorMessage(error, 'No se pudieron cargar las cohortes de referencia.'));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
onFilesPicked(event: Event): void {
|
||||
const input = event.target as HTMLInputElement;
|
||||
this.selectedFiles.set(Array.from(input.files ?? []));
|
||||
}
|
||||
|
||||
upload(): void {
|
||||
if (this.name.invalid || !this.selectedFiles().length || this.rootMissing()) return;
|
||||
const cohort = this.name.value.trim();
|
||||
const items: UploadItem[] = this.selectedFiles().map((file) => ({
|
||||
fileName: file.name,
|
||||
progress: null,
|
||||
status: 'uploading',
|
||||
detail: 'En espera',
|
||||
}));
|
||||
this.uploads.set(items);
|
||||
this.uploading.set(true);
|
||||
this.run(cohort, this.selectedFiles(), items, 0);
|
||||
}
|
||||
|
||||
/** One file after another; the table reloads when the last one settles. */
|
||||
private run(cohort: string, files: File[], items: UploadItem[], index: number): void {
|
||||
if (index >= files.length) {
|
||||
this.uploading.set(false);
|
||||
this.selectedFiles.set([]);
|
||||
this.load();
|
||||
return;
|
||||
}
|
||||
this.api
|
||||
.uploadReferenceFile(cohort, files[index])
|
||||
.pipe(
|
||||
takeUntilDestroyed(this.destroyRef),
|
||||
finalize(() => this.run(cohort, files, items, index + 1)),
|
||||
)
|
||||
.subscribe({
|
||||
next: (event) => {
|
||||
const item = items[index];
|
||||
if (event.type === HttpEventType.UploadProgress) {
|
||||
item.progress = event.total ? Math.round((event.loaded / event.total) * 100) : null;
|
||||
item.detail = item.progress === null ? 'Subiendo…' : `${item.progress}%`;
|
||||
} else if (event.type === HttpEventType.Response && event.body) {
|
||||
item.status = 'done';
|
||||
item.progress = 100;
|
||||
item.detail = `${event.body.file} guardado (${tamano(event.body.size_bytes)})`;
|
||||
}
|
||||
this.uploads.set([...items]);
|
||||
},
|
||||
error: (error) => {
|
||||
if (error?.status === 503) this.rootMissing.set(true);
|
||||
items[index] = {
|
||||
...items[index],
|
||||
status: 'error',
|
||||
detail: apiErrorMessage(error, 'No se pudo subir el archivo.'),
|
||||
};
|
||||
this.uploads.set([...items]);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/** The three validation report fields with the labels the model version dialog shows. */
|
||||
import { ReportField } from '../../api/governance.types';
|
||||
|
||||
export const REPORT_FIELDS: { field: ReportField; label: string }[] = [
|
||||
{ field: 'technical_validation_report_uri', label: 'Pruebas técnicas (MLD-01)' },
|
||||
{ field: 'clinical_validation_report_uri', label: 'Validación clínica (MLD-01b)' },
|
||||
{ field: 'interpretability_report_uri', label: 'Interpretabilidad (MLD-03)' },
|
||||
];
|
||||
|
||||
/** The PATCH body from the form values; empty fields clear the tag. */
|
||||
export function reportsBody(values: Record<ReportField, string>): Partial<Record<ReportField, string | null>> {
|
||||
return {
|
||||
technical_validation_report_uri: values.technical_validation_report_uri.trim() || null,
|
||||
clinical_validation_report_uri: values.clinical_validation_report_uri.trim() || null,
|
||||
interpretability_report_uri: values.interpretability_report_uri.trim() || null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<section class="reports">
|
||||
<h3 class="report__title">Versiones candidatas de TEA</h3>
|
||||
@if (loading()) {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando versiones"></mat-progress-bar>
|
||||
}
|
||||
@if (loadError(); as error) {
|
||||
<p class="report__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
|
||||
}
|
||||
@if (!loading() && !loadError()) {
|
||||
@if (rows().length) {
|
||||
<table mat-table [dataSource]="rows()" class="report__table" aria-label="Versiones candidatas">
|
||||
<ng-container matColumnDef="apply">
|
||||
<th mat-header-cell *matHeaderCellDef>Aplicar</th>
|
||||
<td mat-cell *matCellDef="let row">
|
||||
<mat-checkbox [checked]="row.checked" [disabled]="applying()" (change)="toggle(row)" [aria-label]="'Aplicar a ' + row.label"></mat-checkbox>
|
||||
</td>
|
||||
</ng-container>
|
||||
<ng-container matColumnDef="version">
|
||||
<th mat-header-cell *matHeaderCellDef>Versión</th>
|
||||
<td mat-cell *matCellDef="let row">{{ row.label }}</td>
|
||||
</ng-container>
|
||||
<ng-container matColumnDef="status">
|
||||
<th mat-header-cell *matHeaderCellDef>Estado</th>
|
||||
<td mat-cell *matCellDef="let row">
|
||||
@if (row.status === 'applying') {
|
||||
<span class="report__status"><mat-progress-bar mode="indeterminate" class="report__bar"></mat-progress-bar>Aplicando…</span>
|
||||
} @else if (row.status === 'done') {
|
||||
<span class="report__status report__status--ok"><mat-icon aria-hidden="true">check_circle</mat-icon>Aplicado</span>
|
||||
} @else if (row.status === 'error') {
|
||||
<span class="report__status report__status--fail"><mat-icon aria-hidden="true">error</mat-icon>{{ row.error }}</span>
|
||||
} @else {
|
||||
<span class="report__status report__muted">Pendiente</span>
|
||||
}
|
||||
</td>
|
||||
</ng-container>
|
||||
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
|
||||
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
|
||||
</table>
|
||||
} @else {
|
||||
<p class="report__muted">No hay versiones eeg-* candidatas.</p>
|
||||
}
|
||||
}
|
||||
|
||||
<h3 class="report__title">Reportes de validación</h3>
|
||||
<form class="report__form" [formGroup]="reports" (ngSubmit)="apply()">
|
||||
@for (field of fields; track field.field) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>{{ field.label }}</mat-label>
|
||||
<input matInput [formControlName]="field.field" placeholder="Ruta o URL del reporte" />
|
||||
</mat-form-field>
|
||||
}
|
||||
<button mat-flat-button type="submit" color="primary" [disabled]="applying() || !hasReports() || !rows().some((r) => r.checked)">
|
||||
<mat-icon aria-hidden="true">attach_file</mat-icon>Aplicar a las versiones de TEA
|
||||
</button>
|
||||
</form>
|
||||
@if (result(); as line) {
|
||||
<p class="report__muted" role="status">{{ line }}</p>
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,59 @@
|
||||
.reports {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
max-width: 860px;
|
||||
}
|
||||
|
||||
.report__title {
|
||||
font: var(--mat-sys-title-small);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.report__alert {
|
||||
align-items: center;
|
||||
background: var(--mat-sys-error-container);
|
||||
color: var(--mat-sys-on-error-container);
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
}
|
||||
|
||||
.report__muted {
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.report__table {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.report__status {
|
||||
align-items: center;
|
||||
display: inline-flex;
|
||||
font: var(--mat-sys-body-small);
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.report__status--ok {
|
||||
color: var(--mat-sys-primary);
|
||||
}
|
||||
|
||||
.report__status--fail {
|
||||
color: var(--mat-sys-error);
|
||||
}
|
||||
|
||||
.report__bar {
|
||||
width: 120px;
|
||||
}
|
||||
|
||||
.report__form {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
grid-template-columns: 1fr;
|
||||
|
||||
button {
|
||||
justify-self: start;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user