From 5061350dd8e7906f5cf58d4e694e0667fb69f934 Mon Sep 17 00:00:00 2001
From: ulises
Date: Mon, 23 Nov 2026 12:26:15 -0600
Subject: [PATCH 1/2] TEA summary: the EEG sentence gives the number of studies
not acceptable for an analysis
---
src/app/features/indicadores/indicadores-kpi.ts | 1 +
.../indicadores/tea-resumen-periodo.spec.ts | 14 +++++++-------
.../features/indicadores/tea-resumen-periodo.ts | 15 ++++++---------
3 files changed, 14 insertions(+), 16 deletions(-)
diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts
index 2ad5cd7..c0ba722 100644
--- a/src/app/features/indicadores/indicadores-kpi.ts
+++ b/src/app/features/indicadores/indicadores-kpi.ts
@@ -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' },
diff --git a/src/app/features/indicadores/tea-resumen-periodo.spec.ts b/src/app/features/indicadores/tea-resumen-periodo.spec.ts
index 1b76dec..3e30c79 100644
--- a/src/app/features/indicadores/tea-resumen-periodo.spec.ts
+++ b/src/app/features/indicadores/tea-resumen-periodo.spec.ts
@@ -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', () => {
diff --git a/src/app/features/indicadores/tea-resumen-periodo.ts b/src/app/features/indicadores/tea-resumen-periodo.ts
index d010482..7876ec6 100644
--- a/src/app/features/indicadores/tea-resumen-periodo.ts
+++ b/src/app/features/indicadores/tea-resumen-periodo.ts
@@ -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 niños con diagnóstico confirmado en este periodo,
presentan estudio de EEG y faltan
por realizarlo.
- De los estudios de EEG,
- tienen buena calidad.
+ estudios de EEG no son aceptables para un análisis.
*tomando la mediana de los tiempos
@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'); }
--
2.53.0
From 98e9b60e831efc2f84bcaacbd53e1d419487469f Mon Sep 17 00:00:00 2001
From: ulises
Date: Mon, 23 Nov 2026 12:26:15 -0600
Subject: [PATCH 2/2] Gobernanza: view the results of one EDF and its ADOS-2
report without storing them, with Guardar como PDF
---
.../fixtures/tea_vista_previa_bundle.json | 835 ++++++++++++++++++
.../indicadores/indicadores-fhir.spec.ts | 15 +
.../indicadores/tea-paciente-resumen.ts | 25 +-
.../indicadores/tea-seguimiento-fhir.ts | 35 +-
.../indicadores/tea-seguimiento.service.ts | 6 +-
src/app/governance/api/tea-eeg.api.ts | 9 +
src/app/governance/api/tea-eeg.types.ts | 7 +
.../components/analyze-step/analyze-step.html | 12 +-
.../analyze-step/analyze-step.spec.ts | 56 ++
.../components/analyze-step/analyze-step.ts | 41 +-
.../eeg-preview-dialog.html | 12 +
.../eeg-preview-dialog.scss | 3 +
.../eeg-preview-dialog.spec.ts | 49 +
.../eeg-preview-dialog/eeg-preview-dialog.ts | 43 +
src/styles.scss | 12 +
15 files changed, 1131 insertions(+), 29 deletions(-)
create mode 100644 src/app/features/indicadores/fixtures/tea_vista_previa_bundle.json
create mode 100644 src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.html
create mode 100644 src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.scss
create mode 100644 src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.spec.ts
create mode 100644 src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.ts
diff --git a/src/app/features/indicadores/fixtures/tea_vista_previa_bundle.json b/src/app/features/indicadores/fixtures/tea_vista_previa_bundle.json
new file mode 100644
index 0000000..9afd4cf
--- /dev/null
+++ b/src/app/features/indicadores/fixtures/tea_vista_previa_bundle.json
@@ -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"
+ }
+ ]
+ }
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/src/app/features/indicadores/indicadores-fhir.spec.ts b/src/app/features/indicadores/indicadores-fhir.spec.ts
index d4e2faa..3e8aed2 100644
--- a/src/app/features/indicadores/indicadores-fhir.spec.ts
+++ b/src/app/features/indicadores/indicadores-fhir.spec.ts
@@ -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);
+ });
});
diff --git a/src/app/features/indicadores/tea-paciente-resumen.ts b/src/app/features/indicadores/tea-paciente-resumen.ts
index 80936dd..1e1ddc8 100644
--- a/src/app/features/indicadores/tea-paciente-resumen.ts
+++ b/src/app/features/indicadores/tea-paciente-resumen.ts
@@ -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'),
});
}
diff --git a/src/app/features/indicadores/tea-seguimiento-fhir.ts b/src/app/features/indicadores/tea-seguimiento-fhir.ts
index b41e26f..d92d012 100644
--- a/src/app/features/indicadores/tea-seguimiento-fhir.ts
+++ b/src/app/features/indicadores/tea-seguimiento-fhir.ts
@@ -331,19 +331,26 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
return forkJoin({
bundle: this.client.get(`/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);
+}
diff --git a/src/app/features/indicadores/tea-seguimiento.service.ts b/src/app/features/indicadores/tea-seguimiento.service.ts
index 74ed6f4..76b46d6 100644
--- a/src/app/features/indicadores/tea-seguimiento.service.ts
+++ b/src/app/features/indicadores/tea-seguimiento.service.ts
@@ -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(`/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 {
+ return throwError(() => new Error('La vista previa necesita el servicio FHIR.'));
+ }
}
diff --git a/src/app/governance/api/tea-eeg.api.ts b/src/app/governance/api/tea-eeg.api.ts
index aafac0f..4924f9b 100644
--- a/src/app/governance/api/tea-eeg.api.ts
+++ b/src/app/governance/api/tea-eeg.api.ts
@@ -11,6 +11,7 @@ import {
EegId,
EegListItem,
EegMetrics,
+ EegPreview,
EegSummary,
EegUploadResult,
ReferenceCohort,
@@ -122,6 +123,14 @@ export class TeaEegApi {
return this.http.post('/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 {
+ const form = new FormData();
+ form.append('edf', edf);
+ if (ados2) form.append('ados2', ados2);
+ return this.http.post('/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 } : {});
diff --git a/src/app/governance/api/tea-eeg.types.ts b/src/app/governance/api/tea-eeg.types.ts
index d61dcab..5bf0d76 100644
--- a/src/app/governance/api/tea-eeg.types.ts
+++ b/src/app/governance/api/tea-eeg.types.ts
@@ -178,3 +178,10 @@ export interface EegSummary {
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[];
+}
diff --git a/src/app/governance/components/analyze-step/analyze-step.html b/src/app/governance/components/analyze-step/analyze-step.html
index 7f6657a..aa306ad 100644
--- a/src/app/governance/components/analyze-step/analyze-step.html
+++ b/src/app/governance/components/analyze-step/analyze-step.html
@@ -43,8 +43,18 @@
Subir EDF
Archivo EDF
+ @if (!storeless()) {
ID del paciente (opcional)
- {{ uploading() ? 'Subiendo…' : 'Subir EDF' }}
+ }
+ @if (file()) {
+ Informe ADOS-2 (PDF, opcional)
+ Solo ver resultados, sin guardar en la base de datos
+ }
+ @if (storeless()) {
+ {{ uploading() ? 'Analizando…' : 'Ver resultados' }}
+ } @else {
+ {{ uploading() ? 'Subiendo…' : 'Subir EDF' }}
+ }
@if (uploadError()) { {{ uploadError() }}
}
@if (uploaded(); as result) {
diff --git a/src/app/governance/components/analyze-step/analyze-step.spec.ts b/src/app/governance/components/analyze-step/analyze-step.spec.ts
index 238c1d1..fe8f72d 100644
--- a/src/app/governance/components/analyze-step/analyze-step.spec.ts
+++ b/src/app/governance/components/analyze-step/analyze-step.spec.ts
@@ -2,12 +2,16 @@
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 = {
@@ -135,4 +139,56 @@ describe('AnalyzeStepComponent', () => {
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);
+ });
});
diff --git a/src/app/governance/components/analyze-step/analyze-step.ts b/src/app/governance/components/analyze-step/analyze-step.ts
index 1341304..9d42d8b 100644
--- a/src/app/governance/components/analyze-step/analyze-step.ts
+++ b/src/app/governance/components/analyze-step/analyze-step.ts
@@ -2,23 +2,29 @@ import { Component, DestroyRef, OnInit, computed, effect, inject, input, signal
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, timer } from 'rxjs';
+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, MatRadioModule, RunMonitorComponent],
+ 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({ mode: 'auto' });
readonly scope = signal<'pending' | 'limit' | 'selected'>('pending');
readonly limit = signal(10);
@@ -45,6 +51,12 @@ export class AnalyzeStepComponent implements OnInit {
readonly uploaded = signal(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(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 = {
en_curso: 'En curso', completado: 'Completado', entrenado_sin_promover: 'Completado',
fallido: 'Falló', interrumpido: 'Interrumpido',
@@ -124,6 +136,31 @@ export class AnalyzeStepComponent implements OnInit {
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 {
diff --git a/src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.html b/src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.html
new file mode 100644
index 0000000..401c7d9
--- /dev/null
+++ b/src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.html
@@ -0,0 +1,12 @@
+Resultados del EEG · {{ data.archivo }}
+
+
+
Análisis hecho al momento. No se guardó en la base de datos.
+ @for (aviso of data.avisos; track aviso) {
{{ aviso }}
}
+
+
+
+
+ Guardar como PDF
+ Cerrar
+
diff --git a/src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.scss b/src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.scss
new file mode 100644
index 0000000..bc754df
--- /dev/null
+++ b/src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.scss
@@ -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); }
diff --git a/src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.spec.ts b/src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.spec.ts
new file mode 100644
index 0000000..4dcee73
--- /dev/null
+++ b/src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.spec.ts
@@ -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(); }
+ });
+});
diff --git a/src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.ts b/src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.ts
new file mode 100644
index 0000000..45baa0e
--- /dev/null
+++ b/src/app/governance/components/eeg-preview-dialog/eeg-preview-dialog.ts
@@ -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(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 {
+ 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();
+ }
+}
diff --git a/src/styles.scss b/src/styles.scss
index 9b6be39..1cb99ad 100644
--- a/src/styles.scss
+++ b/src/styles.scss
@@ -164,3 +164,15 @@ body {
--eeg-band-outer: rgba(22, 120, 173, .18);
--eeg-band-inner: rgba(22, 120, 173, .34);
}
+
+// Guardar como PDF in the EEG preview: only the open dialog is printed, spread over as many pages as it needs.
+@media print {
+ body.imprime-vista-previa > *:not(.cdk-overlay-container) { display: none !important; }
+ body.imprime-vista-previa .cdk-overlay-backdrop, body.imprime-vista-previa mat-dialog-actions { display: none !important; }
+ body.imprime-vista-previa .cdk-overlay-container, body.imprime-vista-previa .cdk-global-overlay-wrapper,
+ body.imprime-vista-previa .cdk-overlay-pane, body.imprime-vista-previa .mat-mdc-dialog-container,
+ body.imprime-vista-previa .mat-mdc-dialog-surface, body.imprime-vista-previa .mat-mdc-dialog-content {
+ position: static !important; display: block !important; width: auto !important; max-width: none !important;
+ height: auto !important; max-height: none !important; overflow: visible !important; transform: none !important; box-shadow: none !important;
+ }
+}
--
2.53.0