Gobernanza: view the results of one EDF and its ADOS-2 report without storing them, with Guardar como PDF

This commit is contained in:
ulises
2026-11-23 12:26:15 -06:00
parent 5061350dd8
commit 98e9b60e83
15 changed files with 1131 additions and 29 deletions
@@ -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"
}
]
}
}
}
]
}
@@ -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);
});
});
@@ -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'),
});
}
@@ -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.'));
}
}
+9
View File
@@ -11,6 +11,7 @@ import {
EegId,
EegListItem,
EegMetrics,
EegPreview,
EegSummary,
EegUploadResult,
ReferenceCohort,
@@ -122,6 +123,14 @@ export class TeaEegApi {
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 } : {});
+7
View File
@@ -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[];
}
@@ -43,8 +43,18 @@
<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>
<button mat-stroked-button type="button" [disabled]="!canUpload()" (click)="upload(edf)">{{ uploading() ? 'Subiendo…' : 'Subir EDF' }}</button>
}
@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) {
@@ -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);
});
});
@@ -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<ClusterChoice>({ mode: 'auto' });
readonly scope = signal<'pending' | 'limit' | 'selected'>('pending');
readonly limit = signal<number | null>(10);
@@ -45,6 +51,12 @@ export class AnalyzeStepComponent implements OnInit {
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',
@@ -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 {
@@ -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();
}
}
+12
View File
@@ -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;
}
}