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:
@@ -39,6 +39,9 @@
|
|||||||
"material-symbols/outlined.css",
|
"material-symbols/outlined.css",
|
||||||
"src/styles.scss"
|
"src/styles.scss"
|
||||||
],
|
],
|
||||||
|
"define": {
|
||||||
|
"global": "globalThis"
|
||||||
|
},
|
||||||
"allowedCommonJsDependencies": [
|
"allowedCommonJsDependencies": [
|
||||||
"plotly.js-cartesian-dist-min"
|
"plotly.js-cartesian-dist-min"
|
||||||
]
|
]
|
||||||
|
|||||||
+102
-89
@@ -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[] {
|
function watch(page: Page): string[] {
|
||||||
const problems: string[] = [];
|
const problems: string[] = [];
|
||||||
page.on('console', (m) => m.type() === 'error' && problems.push(`console: ${m.text()}`));
|
page.on('console', (m) => m.type() === 'error' && problems.push(`console: ${m.text()}`));
|
||||||
@@ -9,110 +9,123 @@ function watch(page: Page): string[] {
|
|||||||
return problems;
|
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<string> {
|
||||||
|
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,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
const problems = watch(page);
|
const problems = watch(page);
|
||||||
const report = page.waitForResponse(
|
const listed = page.waitForResponse(
|
||||||
(r) =>
|
(r) => r.url().includes('/tea/fhir/Measure') && !r.url().includes('MeasureReport'),
|
||||||
r.url().includes('MeasureReport') &&
|
|
||||||
r.url().includes('measure=cacu-eu7') &&
|
|
||||||
!r.url().includes('%2C'),
|
|
||||||
);
|
);
|
||||||
await page.goto('/indicadores/cacu');
|
await page.goto('/indicadores/tea');
|
||||||
const eu7 = await (await report).json();
|
const measures = (await (await listed).json()).entry.length;
|
||||||
const count = eu7.entry[0].resource.group[0].population.find(
|
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
|
||||||
(p: any) => p.code.coding[0].code === 'initial-population',
|
await expect(page.locator('app-tab-indicadores mat-card[data-measure]').first()).toBeVisible();
|
||||||
).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.getByRole('tab', { name: 'Trazabilidad' }).click();
|
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 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?'));
|
test('tea patient: the record and the risk page load and export to PDF', async ({ page }) => {
|
||||||
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
|
const problems = watch(page);
|
||||||
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');
|
|
||||||
await page.goto('/indicadores/tea');
|
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([]);
|
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,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
const problems = watch(page);
|
const problems = watch(page);
|
||||||
await page.goto('/conectar');
|
await page.goto('/gobernanza/tea');
|
||||||
await page.getByText('cacu', { exact: true }).click();
|
await page.getByLabel('Modo').selectOption('sync');
|
||||||
await expect(page.locator('vflow')).toBeVisible();
|
await expect(page.getByRole('status').filter({ hasText: 'Disponible' })).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([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('revision: what the hospital source holds, and a decision through the page', async ({ page }) => {
|
await page.getByRole('button', { name: 'Entrenar modelos' }).click();
|
||||||
const problems = watch(page);
|
await expect(page.getByRole('heading', { name: 'Entrenar modelos', level: 3 })).toBeVisible();
|
||||||
await page.goto('/revision');
|
await expect(page.locator('app-governance-training formly-form')).toBeVisible();
|
||||||
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([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('gobernanza: a version with its reports, its curves, and promotion refused without validation', async ({
|
const monitor = page.locator('app-gobernanza > section > section app-run-monitor');
|
||||||
page,
|
await page.getByRole('button', { name: 'Analizar EEG' }).click();
|
||||||
}) => {
|
await expect(page.getByRole('heading', { name: 'Análisis de EEG' })).toBeVisible();
|
||||||
const problems = watch(page);
|
await expect(monitor.getByRole('status')).toHaveText('SUCCESS', { timeout: 10 * 60_000 });
|
||||||
await page.goto('/gobernanza/cama');
|
await page.getByRole('button', { name: 'Calcular riesgos' }).click();
|
||||||
await expect(page.getByRole('heading', { name: 'survival' })).toBeVisible();
|
await expect(page.getByRole('heading', { name: 'Cálculo de riesgos' })).toBeVisible();
|
||||||
const version = page.locator('tr', { hasText: 'v1' });
|
await expect(monitor.getByRole('status')).toHaveText('SUCCESS', { timeout: 10 * 60_000 });
|
||||||
await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible();
|
await page.getByRole('button', { name: 'Promover candidatas' }).click();
|
||||||
await version.getByRole('button', { name: 'Ver gráficas' }).click();
|
await expect(page.getByText('No hay candidatas que se puedan promover.')).toBeVisible();
|
||||||
await expect(page.locator('app-plot .plot svg').first()).toBeVisible();
|
|
||||||
await version.getByRole('button', { name: 'Promover' }).click();
|
const studies = page.locator('app-eeg-studies');
|
||||||
await expect(page.getByText('No se promovió')).toContainText('clinical_validation');
|
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([]);
|
expect(problems.filter((p) => !p.includes('409'))).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1273,12 +1273,20 @@
|
|||||||
},
|
},
|
||||||
"title": "Read",
|
"title": "Read",
|
||||||
"type": "array"
|
"type": "array"
|
||||||
|
},
|
||||||
|
"titles": {
|
||||||
|
"additionalProperties": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"title": "Titles",
|
||||||
|
"type": "object"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": [
|
||||||
"module",
|
"module",
|
||||||
"evaluation_date",
|
"evaluation_date",
|
||||||
"items",
|
"items",
|
||||||
|
"titles",
|
||||||
"css",
|
"css",
|
||||||
"classification",
|
"classification",
|
||||||
"read"
|
"read"
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
import { defineConfig } from '@playwright/test';
|
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({
|
export default defineConfig({
|
||||||
testDir: 'e2e',
|
testDir: 'e2e',
|
||||||
timeout: 15 * 60_000,
|
timeout: 15 * 60_000,
|
||||||
@@ -12,10 +9,9 @@ export default defineConfig({
|
|||||||
use: {
|
use: {
|
||||||
baseURL: 'http://127.0.0.1:4310',
|
baseURL: 'http://127.0.0.1:4310',
|
||||||
viewport: { width: 1440, height: 1000 },
|
viewport: { width: 1440, height: 1000 },
|
||||||
actionTimeout: 60_000, // a stuck step fails, not the whole run
|
actionTimeout: 60_000,
|
||||||
},
|
},
|
||||||
webServer: {
|
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',
|
command: 'npx ng serve --host 127.0.0.1 --port 4310 --proxy-config proxy.e2e.mjs',
|
||||||
env: { NG_CLI_ANALYTICS: 'false' },
|
env: { NG_CLI_ANALYTICS: 'false' },
|
||||||
url: 'http://127.0.0.1:4310',
|
url: 'http://127.0.0.1:4310',
|
||||||
|
|||||||
@@ -1,2 +1 @@
|
|||||||
// `/api` to the API the e2e run started (API_URL).
|
|
||||||
export default { '/api': { target: process.env.API_URL, pathRewrite: { '^/api': '' } } };
|
export default { '/api': { target: process.env.API_URL, pathRewrite: { '^/api': '' } } };
|
||||||
|
|||||||
@@ -10,4 +10,7 @@ export interface PreviewAdos2 {
|
|||||||
};
|
};
|
||||||
module: (string | null);
|
module: (string | null);
|
||||||
read: Array<string>;
|
read: Array<string>;
|
||||||
|
titles: {
|
||||||
|
[key: string]: string;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { verifiedImport } from './bundles';
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
|
import { exportErrorText, verifiedImport } from './bundles';
|
||||||
|
|
||||||
const hash = 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad';
|
const hash = 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad';
|
||||||
|
|
||||||
@@ -26,3 +27,18 @@ describe('bundle import', () => {
|
|||||||
expect(upload).toHaveBeenCalledExactlyOnceWith(hash);
|
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');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { Component, inject, input, model, output, signal } from '@angular/core';
|
import { Component, inject, input, model, output, signal } from '@angular/core';
|
||||||
import { FormsModule } from '@angular/forms';
|
import { FormsModule } from '@angular/forms';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
@@ -22,6 +23,17 @@ export async function verifiedImport<T>(
|
|||||||
return upload(sha256);
|
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 {
|
export function download(blob: Blob, filename: string): void {
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
const link = document.createElement('a');
|
const link = document.createElement('a');
|
||||||
@@ -92,11 +104,7 @@ export class Bundles {
|
|||||||
this.exportedHash.set(sha256);
|
this.exportedHash.set(sha256);
|
||||||
download(response.body, `${domain}-models-${sha256.slice(0, 12)}.zip`);
|
download(response.body, `${domain}-models-${sha256.slice(0, 12)}.zip`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof Error && 'error' in error && error.error instanceof Blob) {
|
this.message.set(await exportErrorText(error));
|
||||||
this.message.set(await error.error.text());
|
|
||||||
} else {
|
|
||||||
this.message.set(errorText(error));
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
this.exporting.set(false);
|
this.exporting.set(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import { startPreview } from '../../api/fn/preview/start-preview';
|
|||||||
import type { PreviewResult } from '../../api/models/preview-result';
|
import type { PreviewResult } from '../../api/models/preview-result';
|
||||||
import type { Run } from '../../api/models/run';
|
import type { Run } from '../../api/models/run';
|
||||||
import { RunMonitor, errorText } from '../run-monitor';
|
import { RunMonitor, errorText } from '../run-monitor';
|
||||||
|
import { downloadPreviewPdf } from './preview-pdf';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-eeg-preview',
|
selector: 'app-eeg-preview',
|
||||||
@@ -118,8 +119,8 @@ import { RunMonitor, errorText } from '../run-monitor';
|
|||||||
<h4>ADOS-2</h4>
|
<h4>ADOS-2</h4>
|
||||||
<p>{{ ados2.classification }} · CSS {{ ados2.css ?? '—' }}</p>
|
<p>{{ ados2.classification }} · CSS {{ ados2.css ?? '—' }}</p>
|
||||||
<dl>
|
<dl>
|
||||||
@for (item of ados2.items | keyvalue; track item.key) {
|
@for (item of ados2.items | keyvalue: unsorted; track item.key) {
|
||||||
<dt>{{ item.key }}</dt>
|
<dt>{{ ados2.titles[item.key] ?? item.key }}</dt>
|
||||||
<dd>{{ item.value ?? '—' }}</dd>
|
<dd>{{ item.value ?? '—' }}</dd>
|
||||||
}
|
}
|
||||||
</dl>
|
</dl>
|
||||||
@@ -133,7 +134,17 @@ import { RunMonitor, errorText } from '../run-monitor';
|
|||||||
</ul>
|
</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>
|
</dialog>
|
||||||
</section>
|
</section>
|
||||||
`,
|
`,
|
||||||
@@ -144,6 +155,21 @@ export class EegPreview {
|
|||||||
protected readonly error = signal('');
|
protected readonly error = signal('');
|
||||||
protected readonly runId = signal('');
|
protected readonly runId = signal('');
|
||||||
protected readonly result = signal<PreviewResult | null>(null);
|
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> {
|
protected async start(edf?: File, ados2?: File, birth_date?: string): Promise<void> {
|
||||||
if (!edf) return;
|
if (!edf) return;
|
||||||
|
|||||||
@@ -305,9 +305,13 @@ export function teaRows(page: Bundle) {
|
|||||||
return {
|
return {
|
||||||
patient,
|
patient,
|
||||||
name: patient.name?.[0]?.text,
|
name: patient.name?.[0]?.text,
|
||||||
recordNumbers: (patient.identifier ?? [])
|
recordNumbers: [
|
||||||
|
...new Set(
|
||||||
|
(patient.identifier ?? [])
|
||||||
.filter((i) => i.system?.startsWith('urn:isssteleon:') && !!i.value)
|
.filter((i) => i.system?.startsWith('urn:isssteleon:') && !!i.value)
|
||||||
.map((i) => i.value!),
|
.map((i) => i.value!),
|
||||||
|
),
|
||||||
|
],
|
||||||
status,
|
status,
|
||||||
steps: TEA_STEPS.map((step, i) => ({
|
steps: TEA_STEPS.map((step, i) => ({
|
||||||
...step,
|
...step,
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { associationRows, teaParams, teaWorkbook } from './tea-list';
|
|||||||
const measure: Measure = { resourceType: 'Measure', status: 'active' };
|
const measure: Measure = { resourceType: 'Measure', status: 'active' };
|
||||||
const r: Reading = { strata: {}, populations: {}, score: 12, low: 7, high: 18 };
|
const r: Reading = { strata: {}, populations: {}, score: 12, low: 7, high: 18 };
|
||||||
const cssPair = 'spindles|central|CSS';
|
const cssPair = 'spindles|central|CSS';
|
||||||
|
const DAY = new Date('2026-11-30T12:00:00Z');
|
||||||
|
|
||||||
function fixture(): Bundle {
|
function fixture(): Bundle {
|
||||||
const subject = { reference: 'Patient/child' };
|
const subject = { reference: 'Patient/child' };
|
||||||
@@ -233,8 +234,8 @@ describe('TEA indicators', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('builds the follow-up workbook', () => {
|
it('builds the follow-up workbook', () => {
|
||||||
expect(teaWorkbook(teaRows(fixture()), false)).toEqual({
|
expect(teaWorkbook(teaRows(fixture()), false, DAY)).toEqual({
|
||||||
name: 'seguimiento-tea',
|
name: 'tea-seguimiento-2026-11-30',
|
||||||
sheets: [
|
sheets: [
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
name: 'Seguimiento',
|
name: 'Seguimiento',
|
||||||
@@ -247,8 +248,8 @@ describe('TEA indicators', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('builds the risk workbook with children and pair details', () => {
|
it('builds the risk workbook with children and pair details', () => {
|
||||||
expect(teaWorkbook(associationRows(teaRows(fixture())), true)).toEqual({
|
expect(teaWorkbook(associationRows(teaRows(fixture())), true, DAY)).toEqual({
|
||||||
name: 'analisis-de-riesgo-tea',
|
name: 'tea-riesgos-2026-11-30',
|
||||||
sheets: [
|
sheets: [
|
||||||
expect.objectContaining({ name: 'Niños' }),
|
expect.objectContaining({ name: 'Niños' }),
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { RouterLink } from '@angular/router';
|
|||||||
import type { Bundle, Patient } from 'fhir/r4';
|
import type { Bundle, Patient } from 'fhir/r4';
|
||||||
import { debounceTime, distinctUntilChanged, map } from 'rxjs';
|
import { debounceTime, distinctUntilChanged, map } from 'rxjs';
|
||||||
import { allRows } from '../export/fetch-all';
|
import { allRows } from '../export/fetch-all';
|
||||||
|
import { safeName } from '../export/safe-name';
|
||||||
import { downloadXlsx, type Sheet } from '../export/xlsx';
|
import { downloadXlsx, type Sheet } from '../export/xlsx';
|
||||||
import { Fhir, type Params } from '../fhir';
|
import { Fhir, type Params } from '../fhir';
|
||||||
import { TEA_STEPS, teaRows, type TeaRow } from './follow-up';
|
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'] =>
|
const columns = (entries: [string, string][]): Sheet['columns'] =>
|
||||||
entries.map(([key, header]) => ({ key, header }));
|
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][] = [
|
const identity: [string, string][] = [
|
||||||
['id', 'Paciente'],
|
['id', 'Paciente'],
|
||||||
['record', 'Expediente'],
|
['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 }))),
|
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(
|
export function exportTea(
|
||||||
|
|||||||
Reference in New Issue
Block a user