Gobernanza preview saved as PDF; Playwright TEA page tests

- The EEG preview dialog gets "Guardar como PDF": previewPdfContent is a
  pure function (verdict, checks, metrics with scores per electrode and
  zone, ADOS-2 classification/CSS and items by their Core titles,
  warnings), downloadPreviewPdf a thin wrapper over export/pdf; the file
  is tea-gobernanza-<day>.pdf. Unit-tested without mocks.
- e2e/pages.spec.ts now holds only the TEA page tests (the CaCu/CaMa
  cases needed fixtures P7 removed): every indicator tab, the follow-up
  xlsx export, the patient record and risk page with their PDFs, and
  every Gobernanza section in sync mode including the preview PDF. Each
  download is checked for a file and a name without a record number.
- Fixes the page tests found: the TEA xlsx name ('seguimiento-tea') failed
  validateName, so the export always threw; it is now tea-<page>-<day>.
  ng serve crashed on every Plotly page (has-hover reads 'global'): the
  build defines global as globalThis. Record numbers repeated once per
  source identifier; they are deduplicated. A refused bundle export showed
  '{}': the blob error body is now read for the API's detail.
This commit is contained in:
2026-11-30 19:17:46 -06:00
parent b847e04697
commit b291885b97
14 changed files with 419 additions and 113 deletions
+3
View File
@@ -10,4 +10,7 @@ export interface PreviewAdos2 {
};
module: (string | null);
read: Array<string>;
titles: {
[key: string]: string;
};
}
+17 -1
View File
@@ -1,4 +1,5 @@
import { verifiedImport } from './bundles';
import { HttpErrorResponse } from '@angular/common/http';
import { exportErrorText, verifiedImport } from './bundles';
const hash = 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad';
@@ -26,3 +27,18 @@ describe('bundle import', () => {
expect(upload).toHaveBeenCalledExactlyOnceWith(hash);
});
});
describe('bundle export', () => {
const failed = (body: string) =>
new HttpErrorResponse({ status: 409, error: new Blob([body], { type: 'application/json' }) });
it("shows the API's detail from a blob error body", async () => {
await expect(
exportErrorText(failed('{"detail":"nothing to export: no version selected"}')),
).resolves.toBe('nothing to export: no version selected');
});
it('shows a body that is not JSON as it came', async () => {
await expect(exportErrorText(failed('Bad gateway'))).resolves.toBe('Bad gateway');
});
});
+13 -5
View File
@@ -1,3 +1,4 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Component, inject, input, model, output, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
@@ -22,6 +23,17 @@ export async function verifiedImport<T>(
return upload(sha256);
}
export async function exportErrorText(error: unknown): Promise<string> {
if (!(error instanceof HttpErrorResponse && error.error instanceof Blob)) return errorText(error);
const text = await error.error.text();
try {
const detail = JSON.parse(text).detail;
return typeof detail === 'string' ? detail : text;
} catch {
return text;
}
}
export function download(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
@@ -92,11 +104,7 @@ export class Bundles {
this.exportedHash.set(sha256);
download(response.body, `${domain}-models-${sha256.slice(0, 12)}.zip`);
} catch (error) {
if (error instanceof Error && 'error' in error && error.error instanceof Blob) {
this.message.set(await error.error.text());
} else {
this.message.set(errorText(error));
}
this.message.set(await exportErrorText(error));
} finally {
this.exporting.set(false);
}
+119
View File
@@ -0,0 +1,119 @@
import { describe, expect, it } from 'vitest';
import type { PreviewResult } from '../../api/models/preview-result';
import { previewPdfContent, previewPdfName } from './preview-pdf';
const score = { z: 2.1, p5: 1, median: 2, p95: 3, outside: 1 };
const result: PreviewResult = {
eeg: {
valid: true,
level: 'complete',
recorded_on: '2026-01-10',
age_months: 24,
clean_fraction: 0.9,
bad_channels: 0,
channels: 19,
duration_min: 20,
line_noise_db: 3,
sleep: true,
error: null,
checks: [
{ code: 'duration', value: 20, unit: 'min', low: 10, high: null, abnormal: false },
{ code: 'flat', electrode: 'O1', text: 'plano', abnormal: true },
],
metrics: [
{
code: 'posterior_rhythm',
value: 6.5,
model: 'tea.eeg-posterior-rhythm/1',
score,
electrodes: { O1: { value: 6.4, score: null } },
zones: { occipital: { value: 6.6, score } },
},
],
},
ados2: {
module: 'module_1',
evaluation_date: '2026-01-12',
items: { pointing: 2, gestures: null, intonation: null, ignoring: 1 },
titles: { pointing: 'A-7 Señalar', gestures: 'A-8 Gestos' },
css: 7,
classification: 'autism',
read: ['module', 'pointing'],
},
warnings: ['sin curva en producción para spindles_n2'],
};
describe('previewPdfContent', () => {
it('prints the verdict, checks, scored metrics, ADOS-2 items by title and warnings', () => {
expect(previewPdfContent(result)).toEqual([
{ text: 'Vista previa del estudio EEG', fontSize: 18, bold: true },
'complete · Válido',
{ text: 'Comprobaciones', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
{
layout: 'lightHorizontalLines',
table: {
headerRows: 1,
widths: ['*', 'auto', 'auto', 'auto', 'auto'],
body: [
['Comprobación', 'Electrodo', 'Resultado', 'Rango', 'Anormal'],
['duration', '—', '20 min', '10 / —', 'No'],
['flat', 'O1', 'plano', '— / —', 'Sí'],
],
},
},
{ text: 'Métricas', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
{
layout: 'lightHorizontalLines',
table: {
headerRows: 1,
widths: ['*', 'auto', 'auto', 'auto', 'auto'],
body: [
['Métrica', 'Valor', 'z', 'p5 / mediana / p95', 'Fuera de rango'],
['posterior_rhythm', '6.5', '2.1', '1 / 2 / 3', '1'],
['posterior_rhythm · O1', '6.4', '—', '— / — / —', '—'],
['posterior_rhythm · occipital', '6.6', '2.1', '1 / 2 / 3', '1'],
],
},
},
{ text: 'ADOS-2', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
'autism · CSS 7',
{
layout: 'lightHorizontalLines',
table: {
headerRows: 1,
widths: ['*', 'auto'],
body: [
['Ítem', 'Puntuación'],
['A-7 Señalar', '2'],
['A-8 Gestos', '—'],
['ignoring', '1'],
],
},
},
{ text: 'Advertencias', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
{ ul: ['sin curva en producción para spindles_n2'] },
]);
});
it('marks an invalid study with its error and no ADOS-2 or warnings', () => {
const content = previewPdfContent({
eeg: { ...result.eeg, valid: false, error: 'sin canales', checks: [], metrics: [] },
ados2: null,
warnings: [],
});
expect(content).toEqual([
{ text: 'Vista previa del estudio EEG', fontSize: 18, bold: true },
'complete · No válido',
'sin canales',
{ text: 'Comprobaciones', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
'—',
{ text: 'Métricas', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
'—',
]);
});
it('names the file by domain, page and day only', () => {
expect(previewPdfName(new Date('2026-11-30T12:00:00Z'))).toBe('tea-gobernanza-2026-11-30');
});
});
+104
View File
@@ -0,0 +1,104 @@
import { downloadPdf, type PdfContent } from '../../export/pdf';
import { safeName } from '../../export/safe-name';
import type { PreviewResult } from '../../api/models/preview-result';
import type { Score } from '../../api/models/score';
function shown(value: unknown): string {
return value == null || value === '' ? '—' : String(value);
}
function yesNo(value: unknown): string {
return value === true ? 'Sí' : value === false ? 'No' : '—';
}
function verdict(valid: boolean | null): string {
return valid === true ? 'Válido' : valid === false ? 'No válido' : '—';
}
function scoreCells(score: Score | null): string[] {
return [
shown(score?.z),
`${shown(score?.p5)} / ${shown(score?.median)} / ${shown(score?.p95)}`,
shown(score?.outside),
];
}
function table(headers: string[], rows: string[][]): PdfContent {
if (!rows.length) return '—';
return {
layout: 'lightHorizontalLines',
table: {
headerRows: 1,
widths: ['*', ...headers.slice(1).map(() => 'auto' as const)],
body: [headers, ...rows],
},
};
}
function heading(text: string): PdfContent {
return { text, bold: true, fontSize: 14, margin: [0, 12, 0, 5] };
}
export function previewPdfName(day = new Date()): string {
return safeName(['tea', 'gobernanza', day.toISOString().slice(0, 10)]);
}
export function previewPdfContent(result: PreviewResult): PdfContent[] {
const { eeg, ados2, warnings } = result;
const content: PdfContent[] = [
{ text: 'Vista previa del estudio EEG', fontSize: 18, bold: true },
`${eeg.level} · ${verdict(eeg.valid)}`,
];
if (eeg.error) content.push(eeg.error);
content.push(
heading('Comprobaciones'),
table(
['Comprobación', 'Electrodo', 'Resultado', 'Rango', 'Anormal'],
eeg.checks.map((check) => [
shown(check['code']),
shown(check['electrode']),
`${shown(check['value'] ?? check['text'])}${check['unit'] ? ' ' + check['unit'] : ''}`,
`${shown(check['low'])} / ${shown(check['high'])}`,
yesNo(check['abnormal']),
]),
),
);
content.push(
heading('Métricas'),
table(
['Métrica', 'Valor', 'z', 'p5 / mediana / p95', 'Fuera de rango'],
eeg.metrics.flatMap((metric) => [
[metric.code, shown(metric.value), ...scoreCells(metric.score)],
...[...Object.entries(metric.electrodes), ...Object.entries(metric.zones)].map(
([site, value]) => [
`${metric.code} · ${site}`,
shown(value.value),
...scoreCells(value.score),
],
),
]),
),
);
if (ados2) {
content.push(
heading('ADOS-2'),
`${shown(ados2.classification)} · CSS ${shown(ados2.css)}`,
table(
['Ítem', 'Puntuación'],
Object.entries(ados2.items)
.filter(([field, value]) => field in ados2.titles || value != null)
.map(([field, value]) => [ados2.titles[field] ?? field, shown(value)]),
),
);
}
if (warnings.length) content.push(heading('Advertencias'), { ul: [...warnings] });
return content;
}
export function downloadPreviewPdf(result: PreviewResult): Promise<void> {
return downloadPdf(previewPdfName(), previewPdfContent(result));
}
+29 -3
View File
@@ -8,6 +8,7 @@ import { startPreview } from '../../api/fn/preview/start-preview';
import type { PreviewResult } from '../../api/models/preview-result';
import type { Run } from '../../api/models/run';
import { RunMonitor, errorText } from '../run-monitor';
import { downloadPreviewPdf } from './preview-pdf';
@Component({
selector: 'app-eeg-preview',
@@ -118,8 +119,8 @@ import { RunMonitor, errorText } from '../run-monitor';
<h4>ADOS-2</h4>
<p>{{ ados2.classification }} · CSS {{ ados2.css ?? '—' }}</p>
<dl>
@for (item of ados2.items | keyvalue; track item.key) {
<dt>{{ item.key }}</dt>
@for (item of ados2.items | keyvalue: unsorted; track item.key) {
<dt>{{ ados2.titles[item.key] ?? item.key }}</dt>
<dd>{{ item.value ?? '—' }}</dd>
}
</dl>
@@ -133,7 +134,17 @@ import { RunMonitor, errorText } from '../run-monitor';
</ul>
}
}
<form method="dialog"><button mat-stroked-button>Cerrar</button></form>
@if (pdfError()) {
<p role="alert">{{ pdfError() }}</p>
}
<form method="dialog">
@if (result(); as r) {
<button mat-stroked-button type="button" [disabled]="exporting()" (click)="pdf(r)">
Guardar como PDF
</button>
}
<button mat-stroked-button>Cerrar</button>
</form>
</dialog>
</section>
`,
@@ -144,6 +155,21 @@ export class EegPreview {
protected readonly error = signal('');
protected readonly runId = signal('');
protected readonly result = signal<PreviewResult | null>(null);
protected readonly unsorted = () => 0;
protected readonly exporting = signal(false);
protected readonly pdfError = signal('');
protected async pdf(result: PreviewResult): Promise<void> {
this.exporting.set(true);
this.pdfError.set('');
try {
await downloadPreviewPdf(result);
} catch (error) {
this.pdfError.set(errorText(error));
} finally {
this.exporting.set(false);
}
}
protected async start(edf?: File, ados2?: File, birth_date?: string): Promise<void> {
if (!edf) return;
+7 -3
View File
@@ -305,9 +305,13 @@ export function teaRows(page: Bundle) {
return {
patient,
name: patient.name?.[0]?.text,
recordNumbers: (patient.identifier ?? [])
.filter((i) => i.system?.startsWith('urn:isssteleon:') && !!i.value)
.map((i) => i.value!),
recordNumbers: [
...new Set(
(patient.identifier ?? [])
.filter((i) => i.system?.startsWith('urn:isssteleon:') && !!i.value)
.map((i) => i.value!),
),
],
status,
steps: TEA_STEPS.map((step, i) => ({
...step,
+5 -4
View File
@@ -14,6 +14,7 @@ import { associationRows, teaParams, teaWorkbook } from './tea-list';
const measure: Measure = { resourceType: 'Measure', status: 'active' };
const r: Reading = { strata: {}, populations: {}, score: 12, low: 7, high: 18 };
const cssPair = 'spindles|central|CSS';
const DAY = new Date('2026-11-30T12:00:00Z');
function fixture(): Bundle {
const subject = { reference: 'Patient/child' };
@@ -233,8 +234,8 @@ describe('TEA indicators', () => {
});
it('builds the follow-up workbook', () => {
expect(teaWorkbook(teaRows(fixture()), false)).toEqual({
name: 'seguimiento-tea',
expect(teaWorkbook(teaRows(fixture()), false, DAY)).toEqual({
name: 'tea-seguimiento-2026-11-30',
sheets: [
expect.objectContaining({
name: 'Seguimiento',
@@ -247,8 +248,8 @@ describe('TEA indicators', () => {
});
it('builds the risk workbook with children and pair details', () => {
expect(teaWorkbook(associationRows(teaRows(fixture())), true)).toEqual({
name: 'analisis-de-riesgo-tea',
expect(teaWorkbook(associationRows(teaRows(fixture())), true, DAY)).toEqual({
name: 'tea-riesgos-2026-11-30',
sheets: [
expect.objectContaining({ name: 'Niños' }),
expect.objectContaining({
+8 -2
View File
@@ -6,6 +6,7 @@ import { RouterLink } from '@angular/router';
import type { Bundle, Patient } from 'fhir/r4';
import { debounceTime, distinctUntilChanged, map } from 'rxjs';
import { allRows } from '../export/fetch-all';
import { safeName } from '../export/safe-name';
import { downloadXlsx, type Sheet } from '../export/xlsx';
import { Fhir, type Params } from '../fhir';
import { TEA_STEPS, teaRows, type TeaRow } from './follow-up';
@@ -140,7 +141,11 @@ function parameters(page?: Bundle): Record<string, string> {
const columns = (entries: [string, string][]): Sheet['columns'] =>
entries.map(([key, header]) => ({ key, header }));
export function teaWorkbook(rows: TeaRow[], risk: boolean): { name: string; sheets: Sheet[] } {
export function teaWorkbook(
rows: TeaRow[],
risk: boolean,
day = new Date(),
): { name: string; sheets: Sheet[] } {
const identity: [string, string][] = [
['id', 'Paciente'],
['record', 'Expediente'],
@@ -194,7 +199,8 @@ export function teaWorkbook(rows: TeaRow[], risk: boolean): { name: string; shee
rows: rows.flatMap((row) => row.pairs.map((pair) => ({ id: row.patient.id, ...pair }))),
});
}
return { name: risk ? 'analisis-de-riesgo-tea' : 'seguimiento-tea', sheets };
const page = risk ? 'riesgos' : 'seguimiento';
return { name: safeName(['tea', page, day.toISOString().slice(0, 10)]), sheets };
}
export function exportTea(