From 98e9b60e831efc2f84bcaacbd53e1d419487469f Mon Sep 17 00:00:00 2001 From: ulises Date: Mon, 23 Nov 2026 12:26:15 -0600 Subject: [PATCH] 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
+ @if (!storeless()) { - + } + @if (file()) { + + Solo ver resultados, sin guardar en la base de datos + } + @if (storeless()) { + + } @else { + + }
@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 }}

} + +
+
+ + + + 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; + } +}