From b291885b9756084d1165d4f8a71ef49cfb1398e4 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 30 Nov 2026 19:17:46 -0600 Subject: [PATCH] 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-.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--. 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. --- angular.json | 3 + e2e/pages.spec.ts | 191 +++++++++++---------- openapi.json | 8 + playwright.config.ts | 6 +- proxy.e2e.mjs | 1 - src/app/api/models/preview-ados-2.ts | 3 + src/app/gobernanza/bundles.spec.ts | 18 +- src/app/gobernanza/bundles.ts | 18 +- src/app/gobernanza/tea/preview-pdf.spec.ts | 119 +++++++++++++ src/app/gobernanza/tea/preview-pdf.ts | 104 +++++++++++ src/app/gobernanza/tea/preview.ts | 32 +++- src/app/indicadores/follow-up.ts | 10 +- src/app/indicadores/tea-indicators.spec.ts | 9 +- src/app/indicadores/tea-list.ts | 10 +- 14 files changed, 419 insertions(+), 113 deletions(-) create mode 100644 src/app/gobernanza/tea/preview-pdf.spec.ts create mode 100644 src/app/gobernanza/tea/preview-pdf.ts diff --git a/angular.json b/angular.json index 032ce33..63d0a1a 100644 --- a/angular.json +++ b/angular.json @@ -39,6 +39,9 @@ "material-symbols/outlined.css", "src/styles.scss" ], + "define": { + "global": "globalThis" + }, "allowedCommonJsDependencies": [ "plotly.js-cartesian-dist-min" ] diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index 6e54e0a..c475742 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -1,6 +1,6 @@ -import { expect, Page, test } from '@playwright/test'; +import { statSync } from 'node:fs'; +import { expect, Locator, Page, test } from '@playwright/test'; -/** Every page loads from the API with no failed request and no console error. */ function watch(page: Page): string[] { const problems: string[] = []; page.on('console', (m) => m.type() === 'error' && problems.push(`console: ${m.text()}`)); @@ -9,110 +9,123 @@ function watch(page: Page): string[] { return problems; } -test("indicators: the KPIs are the API's MeasureReports, every tab and the patient view load", async ({ +async function downloaded(page: Page, button: Locator, kind: 'pdf' | 'xlsx'): Promise { + const [file] = await Promise.all([page.waitForEvent('download'), button.click()]); + const name = file.suggestedFilename(); + expect(name).toMatch(new RegExp(`^tea-[a-z]+-\\d{4}-\\d{2}-\\d{2}\\.${kind}$`)); + expect(name).not.toMatch(/N-?\d{4}/); + expect(statSync(await file.path()).size).toBeGreaterThan(0); + return name; +} + +test('tea indicators: every tab loads, and the follow-up list exports to Excel', async ({ page, }) => { const problems = watch(page); - const report = page.waitForResponse( - (r) => - r.url().includes('MeasureReport') && - r.url().includes('measure=cacu-eu7') && - !r.url().includes('%2C'), + const listed = page.waitForResponse( + (r) => r.url().includes('/tea/fhir/Measure') && !r.url().includes('MeasureReport'), ); - await page.goto('/indicadores/cacu'); - const eu7 = await (await report).json(); - const count = eu7.entry[0].resource.group[0].population.find( - (p: any) => p.code.coding[0].code === 'initial-population', - ).count; - await expect(page.locator('[data-measure="CACU_EU7"] .kpi-value')).toHaveText(String(count)); - await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible(); + await page.goto('/indicadores/tea'); + const measures = (await (await listed).json()).entry.length; + await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible(); + await expect(page.locator('app-tab-indicadores mat-card[data-measure]').first()).toBeVisible(); await page.getByRole('tab', { name: 'Trazabilidad' }).click(); - await expect(page.locator('app-tab-trazabilidad mat-card')).toHaveCount(14); + await expect(page.getByText('Progresión del proceso diagnóstico')).toBeVisible(); + await expect(page.locator('app-tab-trazabilidad app-plot').first()).toBeVisible(); + + await page.getByRole('tab', { name: 'Seguimiento' }).click(); + const rows = page.locator('app-tab-seguimiento table tbody tr'); + await expect(rows.first().locator('td').first()).toHaveText(/^N-?\d{4}$/); + const name = await downloaded( + page, + page.getByRole('button', { name: 'Exportar a Excel' }), + 'xlsx', + ); + expect(name).toMatch(/^tea-seguimiento-/); + + await page.getByRole('tab', { name: 'Análisis de riesgo' }).click(); + await expect(page.locator('app-tab-riesgos app-tea-list')).toBeVisible(); + await expect(page.getByText('Cargando pacientes…')).toHaveCount(0); await page.getByRole('tab', { name: 'Datos y definiciones' }).click(); - await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(14); + await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(measures); + expect(problems).toEqual([]); +}); - const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?')); - await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); - const bundle = await (await list).json(); - const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource; - const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10); - const rows = page.locator('table.worklist tbody tr'); - await expect(rows).toHaveCount(Math.min(20, bundle.total)); - await expect(rows.first().locator('a').first()).toHaveText(first); - await page.getByRole('button', { name: 'Siguiente' }).click(); - await expect(page.getByText(`21–`)).toBeVisible(); - - await page.getByRole('button', { name: 'Anterior' }).click(); - await rows.first().locator('a').first().click(); - await expect(page.getByText('Historial médico')).toBeVisible(); - await expect(page.getByText('Pruebas y resultados')).toBeVisible(); - await expect( - page.locator('app-paciente table').nth(1).locator('tbody tr').first(), - ).not.toContainText('Sin estudios'); - - await page.goto('/indicadores/cama'); - await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible(); - await page.getByRole('tab', { name: 'Seguimiento' }).click(); - await page.locator('mat-form-field', { hasText: 'Ventana' }).click(); - await page.getByRole('option', { name: '12 meses' }).click(); - const camaRows = page.locator('table.worklist tbody tr'); - await expect(camaRows.first()).toContainText('BI-RADS'); +test('tea patient: the record and the risk page load and export to PDF', async ({ page }) => { + const problems = watch(page); await page.goto('/indicadores/tea'); - await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible(); + await page.getByRole('tab', { name: 'Seguimiento' }).click(); + const first = page.locator('app-tab-seguimiento table tbody tr').first(); + await expect(first.locator('td').first()).toHaveText(/^N-?\d{4}$/); + await first.getByRole('link', { name: 'Expediente' }).click(); + + await expect(page).toHaveURL(/\/indicadores\/tea\/pacientes\/[^/]+$/); + await expect(page.getByRole('heading', { level: 1 })).toBeVisible(); + await expect(page.locator('app-tea-section').first()).toBeVisible(); + const record = await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf'); + expect(record).toMatch(/^tea-seguimiento-/); + + await page.getByRole('link', { name: 'Riesgo' }).click(); + await expect(page.getByRole('heading', { name: 'Análisis de riesgo TEA' })).toBeVisible(); + await expect(page.locator('app-tea-section').first()).toBeVisible(); + expect(await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf')).toMatch( + /^tea-riesgos-/, + ); expect(problems).toEqual([]); }); -test('conectar: open the hospital pipeline, preview a source, run it to success', async ({ +test('tea gobernanza: every section in sync mode, and the preview saved as PDF', async ({ page, }) => { const problems = watch(page); - await page.goto('/conectar'); - await page.getByText('cacu', { exact: true }).click(); - await expect(page.locator('vflow')).toBeVisible(); - await page.getByText('Fuente · Patients').click(); - await expect(page.locator('formly-form')).toBeVisible(); - await page.getByRole('button', { name: 'Vista previa' }).click(); - await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible(); - // A map node shows the site's codes in platform terms (its ConceptMap), editable as rows. - await page.getByText('Mapear · cytology', { exact: true }).click(); - await expect(page.getByText('Códigos del sitio')).toBeVisible(); - await expect - .poll(() => - page - .locator('app-concept-map-editor input') - .evaluateAll((els) => els.map((e) => (e as HTMLInputElement).value)), - ) - .toContain('LIEAG'); - await page.getByRole('button', { name: 'Ejecutar' }).click(); - await expect(page.getByText('SUCCESS')).toBeVisible({ timeout: 10 * 60_000 }); - expect(problems).toEqual([]); -}); + await page.goto('/gobernanza/tea'); + await page.getByLabel('Modo').selectOption('sync'); + await expect(page.getByRole('status').filter({ hasText: 'Disponible' })).toBeVisible(); -test('revision: what the hospital source holds, and a decision through the page', async ({ page }) => { - const problems = watch(page); - await page.goto('/revision'); - await page.getByRole('tab', { name: 'Personas' }).click(); - await page.locator('mat-form-field', { hasText: 'Canalización' }).click(); - await page.getByRole('option', { name: 'site', exact: true }).click(); - await expect(page.getByText(/Posibles pacientes duplicadas \([1-9]/)).toBeVisible(); - await page.getByRole('button', { name: 'Distintas' }).first().click(); - await expect(page.getByText('Decisión registrada.')).toBeVisible(); - expect(problems).toEqual([]); -}); + await page.getByRole('button', { name: 'Entrenar modelos' }).click(); + await expect(page.getByRole('heading', { name: 'Entrenar modelos', level: 3 })).toBeVisible(); + await expect(page.locator('app-governance-training formly-form')).toBeVisible(); -test('gobernanza: a version with its reports, its curves, and promotion refused without validation', async ({ - page, -}) => { - const problems = watch(page); - await page.goto('/gobernanza/cama'); - await expect(page.getByRole('heading', { name: 'survival' })).toBeVisible(); - const version = page.locator('tr', { hasText: 'v1' }); - await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible(); - await version.getByRole('button', { name: 'Ver gráficas' }).click(); - await expect(page.locator('app-plot .plot svg').first()).toBeVisible(); - await version.getByRole('button', { name: 'Promover' }).click(); - await expect(page.getByText('No se promovió')).toContainText('clinical_validation'); + const monitor = page.locator('app-gobernanza > section > section app-run-monitor'); + await page.getByRole('button', { name: 'Analizar EEG' }).click(); + await expect(page.getByRole('heading', { name: 'Análisis de EEG' })).toBeVisible(); + await expect(monitor.getByRole('status')).toHaveText('SUCCESS', { timeout: 10 * 60_000 }); + await page.getByRole('button', { name: 'Calcular riesgos' }).click(); + await expect(page.getByRole('heading', { name: 'Cálculo de riesgos' })).toBeVisible(); + await expect(monitor.getByRole('status')).toHaveText('SUCCESS', { timeout: 10 * 60_000 }); + await page.getByRole('button', { name: 'Promover candidatas' }).click(); + await expect(page.getByText('No hay candidatas que se puedan promover.')).toBeVisible(); + + const studies = page.locator('app-eeg-studies'); + await expect(studies.locator('table.eegs tbody tr').first()).toContainText(/Válido|No válido/); + await studies.locator('table.eegs tbody button:enabled').first().click(); + await expect(studies.getByRole('heading', { name: /^EEG .* meses$/ })).toBeVisible(); + await studies.getByRole('button', { name: 'Analizar', exact: true }).click(); + await expect(studies.locator('app-run-monitor').first().getByRole('status')).toHaveText( + 'SUCCESS', + { timeout: 10 * 60_000 }, + ); + + const preview = page.locator('app-eeg-preview'); + await preview.getByLabel('EDF').setInputFiles(process.env['TEA_EDF']!); + await preview.getByLabel('ADOS-2 (PDF)').setInputFiles(process.env['TEA_ADOS2']!); + await preview.getByLabel('Fecha de nacimiento').fill(process.env['TEA_BIRTH']!); + await preview.getByRole('button', { name: 'Vista previa' }).click(); + const dialog = page.getByRole('dialog', { name: 'Vista previa del estudio' }); + await expect(dialog.getByText('Resultado de la vista previa')).toBeVisible({ + timeout: 10 * 60_000, + }); + await expect(dialog.locator('dt').first()).toHaveText(/^[AB]-\d+ \S/); + expect( + await downloaded(page, dialog.getByRole('button', { name: 'Guardar como PDF' }), 'pdf'), + ).toMatch(/^tea-gobernanza-/); + await dialog.getByRole('button', { name: 'Cerrar' }).click(); + + const bundles = page.locator('app-governance-bundles'); + await bundles.getByLabel('Versiones').selectOption('all'); + await bundles.getByRole('button', { name: 'Exportar bundle' }).click(); + await expect(bundles.getByRole('alert')).toContainText('nothing to export'); expect(problems.filter((p) => !p.includes('409'))).toEqual([]); }); diff --git a/openapi.json b/openapi.json index 41154a7..941b031 100644 --- a/openapi.json +++ b/openapi.json @@ -1273,12 +1273,20 @@ }, "title": "Read", "type": "array" + }, + "titles": { + "additionalProperties": { + "type": "string" + }, + "title": "Titles", + "type": "object" } }, "required": [ "module", "evaluation_date", "items", + "titles", "css", "classification", "read" diff --git a/playwright.config.ts b/playwright.config.ts index 034158b..e37e29d 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -1,8 +1,5 @@ import { defineConfig } from '@playwright/test'; -/** The pages against a running API (API_URL), served by the dev server with the same - * proxy the app uses in production (`/api`). Run by WebApi/tests/test_webapp.py, which - * starts the platform and loads the synthetic hospital first. */ export default defineConfig({ testDir: 'e2e', timeout: 15 * 60_000, @@ -12,10 +9,9 @@ export default defineConfig({ use: { baseURL: 'http://127.0.0.1:4310', viewport: { width: 1440, height: 1000 }, - actionTimeout: 60_000, // a stuck step fails, not the whole run + actionTimeout: 60_000, }, webServer: { - // IPv4 explicitly: `localhost` may resolve to ::1 only (CI containers), where the url below never answers. command: 'npx ng serve --host 127.0.0.1 --port 4310 --proxy-config proxy.e2e.mjs', env: { NG_CLI_ANALYTICS: 'false' }, url: 'http://127.0.0.1:4310', diff --git a/proxy.e2e.mjs b/proxy.e2e.mjs index 4af2c3d..06ba47c 100644 --- a/proxy.e2e.mjs +++ b/proxy.e2e.mjs @@ -1,2 +1 @@ -// `/api` to the API the e2e run started (API_URL). export default { '/api': { target: process.env.API_URL, pathRewrite: { '^/api': '' } } }; diff --git a/src/app/api/models/preview-ados-2.ts b/src/app/api/models/preview-ados-2.ts index 90ff71c..a5c6485 100644 --- a/src/app/api/models/preview-ados-2.ts +++ b/src/app/api/models/preview-ados-2.ts @@ -10,4 +10,7 @@ export interface PreviewAdos2 { }; module: (string | null); read: Array; + titles: { +[key: string]: string; +}; } diff --git a/src/app/gobernanza/bundles.spec.ts b/src/app/gobernanza/bundles.spec.ts index 4b8ce54..b3b84d1 100644 --- a/src/app/gobernanza/bundles.spec.ts +++ b/src/app/gobernanza/bundles.spec.ts @@ -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'); + }); +}); diff --git a/src/app/gobernanza/bundles.ts b/src/app/gobernanza/bundles.ts index b312940..f54ad27 100644 --- a/src/app/gobernanza/bundles.ts +++ b/src/app/gobernanza/bundles.ts @@ -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( return upload(sha256); } +export async function exportErrorText(error: unknown): Promise { + 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); } diff --git a/src/app/gobernanza/tea/preview-pdf.spec.ts b/src/app/gobernanza/tea/preview-pdf.spec.ts new file mode 100644 index 0000000..4842c94 --- /dev/null +++ b/src/app/gobernanza/tea/preview-pdf.spec.ts @@ -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'); + }); +}); diff --git a/src/app/gobernanza/tea/preview-pdf.ts b/src/app/gobernanza/tea/preview-pdf.ts new file mode 100644 index 0000000..0855c8c --- /dev/null +++ b/src/app/gobernanza/tea/preview-pdf.ts @@ -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 { + return downloadPdf(previewPdfName(), previewPdfContent(result)); +} diff --git a/src/app/gobernanza/tea/preview.ts b/src/app/gobernanza/tea/preview.ts index 8d437a8..e174758 100644 --- a/src/app/gobernanza/tea/preview.ts +++ b/src/app/gobernanza/tea/preview.ts @@ -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';

ADOS-2

{{ ados2.classification }} · CSS {{ ados2.css ?? '—' }}

- @for (item of ados2.items | keyvalue; track item.key) { -
{{ item.key }}
+ @for (item of ados2.items | keyvalue: unsorted; track item.key) { +
{{ ados2.titles[item.key] ?? item.key }}
{{ item.value ?? '—' }}
}
@@ -133,7 +134,17 @@ import { RunMonitor, errorText } from '../run-monitor'; } } -
+ @if (pdfError()) { +

{{ pdfError() }}

+ } +
+ @if (result(); as r) { + + } + +
`, @@ -144,6 +155,21 @@ export class EegPreview { protected readonly error = signal(''); protected readonly runId = signal(''); protected readonly result = signal(null); + protected readonly unsorted = () => 0; + protected readonly exporting = signal(false); + protected readonly pdfError = signal(''); + + protected async pdf(result: PreviewResult): Promise { + 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 { if (!edf) return; diff --git a/src/app/indicadores/follow-up.ts b/src/app/indicadores/follow-up.ts index e083bbe..4c47519 100644 --- a/src/app/indicadores/follow-up.ts +++ b/src/app/indicadores/follow-up.ts @@ -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, diff --git a/src/app/indicadores/tea-indicators.spec.ts b/src/app/indicadores/tea-indicators.spec.ts index 09c293f..9d5d593 100644 --- a/src/app/indicadores/tea-indicators.spec.ts +++ b/src/app/indicadores/tea-indicators.spec.ts @@ -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({ diff --git a/src/app/indicadores/tea-list.ts b/src/app/indicadores/tea-list.ts index d1de828..5bd82d5 100644 --- a/src/app/indicadores/tea-list.ts +++ b/src/app/indicadores/tea-list.ts @@ -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 { 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(