TEA patient pages: the record and the risk analysis page
Keep the TEA record branch inside Paciente and lazy-load the risk route. Separate FHIR adaptation, figures, shared section rendering, and PDF content under paciente. Use the existing section cards, tables, and buttons, with flexible summary fields and scrollable detail tables. Read the Patient by _id with Observation, DiagnosticReport, and RiskAssessment reverse includes. Group neurology observations by encounter, use aggregate ADOS-2 evaluations, and use the lab-record observation for EEG dates without reports. Order the timeline and exams newest first and use the RiskAssessment headline flag for pair order. Render absent fields and empty tables with an em dash. Use a normalized 10–20 layout and a 41-by-41 inverse-distance weighted contour clipped to the head outline, with symmetric z colors and electrode labels. Keep the head outline and markers when no site has a score. Request each aggregate champion's version once per record load, draw the median and p5–p95 band with banded(), and place the observed value at the EEG's age. Omit unavailable bands and count-rate bands. Use the RiskAssessment's EEG for z and pair status, falling back to the newest EEG with z scores for the bars when needed. Use site outside flags for the forest filter, aggregate scores for global and posterior-rhythm pairs, and show the unit-OR line and available CI bounds. Select the headline pair by default. The current RiskAssessment carries no logistic coefficients, so the view shows patient and reference points at the served z and at zero. Keep the optional logistic figure input independent of the FHIR mapping. Link to Seguimiento with the agreed query parameter. Share section data with the PDF and include snapshots of the rendered figures. Use the existing safe seguimiento and riesgos filename tokens with the UTC date. Format values for es-MX and size categorical charts to their row count. Add Vitest coverage for the head map, norm and point, forest filtering, z band, probability fallback, ADOS-2 rows, PDF content, included data, and the domain branch. Static TypeScript and Angular template checks passed with a temporary PDF type shim. The Angular build, Vitest runtime and Playwright run on the test machines.
This commit is contained in:
@@ -0,0 +1,247 @@
|
||||
import { Component, input } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import type { Observation } from 'fhir/r4';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { EXT, Fhir } from '../fhir';
|
||||
import { Paciente } from './paciente';
|
||||
import { loadTeaPatient, Metric, Pair } from './tea-data';
|
||||
import { ageNorm, forest, headMap, probabilityCurve, zBars } from './tea-figures';
|
||||
import { TeaRecord, TeaSection } from './tea-patient';
|
||||
import { recordSections, teaPdfContent, teaPdfName } from './tea-sections';
|
||||
|
||||
|
||||
const metric: Metric = {
|
||||
key: 'spindles_n2',
|
||||
title: 'Husos N2',
|
||||
value: 1.7,
|
||||
unit: undefined,
|
||||
model: 'tea.eeg-spindles-n2/1',
|
||||
z: 0.3,
|
||||
outside: 0,
|
||||
sites: [
|
||||
{ kind: 'zone', name: 'central', z: 2.4, outside: 1 },
|
||||
{ kind: 'electrode', name: 'O1', z: -1.2, outside: 0 },
|
||||
],
|
||||
};
|
||||
|
||||
const pair: Pair = {
|
||||
key: 'spindles|central|CSS',
|
||||
title: 'Husos N2 · Central · CSS',
|
||||
headline: true,
|
||||
altered: true,
|
||||
z: 2.4,
|
||||
odds: 3,
|
||||
low: 1.2,
|
||||
high: 4.5,
|
||||
probability: 0.7,
|
||||
reference: 0.2,
|
||||
};
|
||||
|
||||
const ados: Observation = {
|
||||
resourceType: 'Observation',
|
||||
id: 'ados2-child-2025-11-22',
|
||||
status: 'final',
|
||||
code: { coding: [{ code: 'ados2' }] },
|
||||
effectiveDateTime: '2025-11-22',
|
||||
valueInteger: 0,
|
||||
component: [
|
||||
{ code: { coding: [{ code: 'ados2.module' }] }, valueCodeableConcept: { text: 'Módulo 1' } },
|
||||
...Array.from({ length: 21 }, (_, i) => ({
|
||||
code: { coding: [{ code: `ados2.item${i}` }], text: `Ítem ${i + 1}` },
|
||||
valueQuantity: i === 0 ? { value: 0 } : undefined,
|
||||
})),
|
||||
{
|
||||
code: { coding: [{ code: 'ados2.intonation' }], text: 'Entonación' },
|
||||
valueQuantity: { value: 2 },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const record = {
|
||||
patient: {
|
||||
resourceType: 'Patient' as const,
|
||||
id: 'child',
|
||||
name: [{ text: 'Paciente de prueba' }],
|
||||
},
|
||||
timeline: [['2025-11-22', 'ADOS-2', '—']],
|
||||
ados: [ados],
|
||||
studies: [],
|
||||
riskStudy: undefined,
|
||||
pairs: [pair],
|
||||
};
|
||||
|
||||
describe('Figuras del paciente TEA', () => {
|
||||
it('interpola los sitios puntuados y dibuja los electrodos y el contorno', () => {
|
||||
const figure = headMap(metric.sites);
|
||||
expect(figure.data[0]).toMatchObject({ type: 'contour' });
|
||||
const grid = (figure.data[0] as { z?: unknown }).z as (number | null)[][];
|
||||
expect(grid[20][20]).toBeCloseTo(2.4);
|
||||
expect(grid[0][0]).toBeNull();
|
||||
expect(figure.data[1]).toMatchObject({
|
||||
mode: 'text+markers',
|
||||
text: expect.arrayContaining(['O1', 'Cz']),
|
||||
});
|
||||
expect(figure.layout?.shapes?.[0]).toMatchObject({ type: 'circle' });
|
||||
});
|
||||
|
||||
it('dibuja los centiles del campeón y el valor observado a la edad del paciente', () => {
|
||||
const figure = ageNorm(
|
||||
[
|
||||
{ age_months: 20, p5: 0, median: 1, p95: 2 },
|
||||
{ age_months: 21, p5: 0.2, median: 1.2, p95: 2.2 },
|
||||
],
|
||||
metric,
|
||||
20.5,
|
||||
);
|
||||
expect(figure.data[0]).toMatchObject({ fill: 'toself', y: [2, 2.2, 0.2, 0] });
|
||||
expect(figure.data[2]).toMatchObject({ mode: 'markers', x: [20.5], y: [1.7] });
|
||||
});
|
||||
|
||||
it('usa escala logarítmica y conserva solo zonas alteradas al activar el filtro', () => {
|
||||
const pairs = [pair, { ...pair, title: 'Zona normal', altered: false, odds: 2 }];
|
||||
expect(forest(pairs, false).data[0].x).toEqual([3, 2]);
|
||||
const filtered = forest(pairs, true);
|
||||
expect(filtered.layout?.xaxis?.type).toBe('log');
|
||||
expect(filtered.data[0]).toMatchObject({
|
||||
x: [3],
|
||||
error_x: { array: [1.5], arrayminus: [1.8] },
|
||||
});
|
||||
});
|
||||
|
||||
it('marca la banda de z entre −2 y 2', () => {
|
||||
const figure = zBars({
|
||||
id: 'eeg-1',
|
||||
date: '2025-11-22',
|
||||
age: 20.5,
|
||||
checks: [],
|
||||
summary: [],
|
||||
metrics: [metric],
|
||||
});
|
||||
expect(figure.data[0]).toMatchObject({
|
||||
x: [0.3, 2.4],
|
||||
y: ['Husos N2 · Global', 'Husos N2 · Central'],
|
||||
});
|
||||
expect(figure.layout?.shapes?.[0]).toMatchObject({ type: 'rect', x0: -2, x1: 2 });
|
||||
});
|
||||
|
||||
it('dibuja solo los puntos de paciente y referencia cuando faltan parámetros', () => {
|
||||
expect(probabilityCurve(pair).data).toMatchObject([
|
||||
{ mode: 'markers', x: [2.4], y: [70] },
|
||||
{ mode: 'markers', x: [0], y: [20] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Expediente TEA', () => {
|
||||
it('muestra los 22 ítems del ADOS-2 y sus dominios sin incluir el módulo', async () => {
|
||||
const fixture = TestBed.createComponent(TeaSection);
|
||||
fixture.componentRef.setInput(
|
||||
'section',
|
||||
recordSections(record, new Map()).find((section) => section.title === 'ADOS-2'),
|
||||
);
|
||||
await fixture.whenStable();
|
||||
const rows = fixture.nativeElement.querySelectorAll('tbody tr');
|
||||
expect(rows).toHaveLength(22);
|
||||
expect(rows[0].textContent).toContain('SA');
|
||||
expect(rows[0].cells[2].textContent.trim()).toBe('0');
|
||||
expect(rows[21].textContent).toContain('RRB');
|
||||
});
|
||||
|
||||
it('exporta las secciones, tablas y figuras con un nombre sin identificador', async () => {
|
||||
const table = recordSections(record, new Map());
|
||||
const sections = [
|
||||
...table,
|
||||
{
|
||||
title: 'Normas',
|
||||
blocks: [{ chart: { title: 'Mapa', figure: headMap(metric.sites) } }],
|
||||
},
|
||||
];
|
||||
const filename = teaPdfName('seguimiento');
|
||||
const content = teaPdfContent('Expediente TEA', sections, ['data:image/png;base64,YQ==']);
|
||||
expect(filename).toMatch(/^tea-seguimiento-\d{4}-\d{2}-\d{2}$/);
|
||||
expect(content).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ text: 'Datos' }),
|
||||
expect.objectContaining({ text: 'Relación con el ADOS-2' }),
|
||||
expect.objectContaining({
|
||||
table: expect.objectContaining({
|
||||
body: expect.arrayContaining([['Entonación', 'RRB', '2']]),
|
||||
}),
|
||||
}),
|
||||
expect.objectContaining({ image: 'data:image/png;base64,YQ==' }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('usa los eventos visibles de la búsqueda y ordena primero el par principal', async () => {
|
||||
const entry = [
|
||||
{ resource: record.patient, search: { mode: 'match' } },
|
||||
{ resource: ados, search: { mode: 'include' } },
|
||||
{
|
||||
resource: {
|
||||
resourceType: 'Observation',
|
||||
code: { coding: [{ code: 'eeg.lab_record_id' }] },
|
||||
effectiveDateTime: '2025-11-30',
|
||||
valueString: 'LAB-01',
|
||||
},
|
||||
search: { mode: 'include' },
|
||||
},
|
||||
{
|
||||
resource: {
|
||||
resourceType: 'RiskAssessment',
|
||||
prediction: [
|
||||
{ outcome: { coding: [{ code: 'spikes|occipital|CSS' }] } },
|
||||
{
|
||||
outcome: { coding: [{ code: pair.key }] },
|
||||
extension: [{ url: EXT + 'association-headline', valueBoolean: true }],
|
||||
},
|
||||
],
|
||||
},
|
||||
search: { mode: 'include' },
|
||||
},
|
||||
];
|
||||
const search = vi.fn(async () => ({ entry }));
|
||||
const data = await loadTeaPatient({ search } as unknown as Fhir, 'child');
|
||||
expect(search).toHaveBeenCalledWith('tea', 'Patient', {
|
||||
_id: 'child',
|
||||
_revinclude: ['Observation:subject', 'DiagnosticReport:subject', 'RiskAssessment:subject'],
|
||||
});
|
||||
expect(data.timeline[0]).toEqual(['2025-11-30', 'EEG', 'LAB-01']);
|
||||
expect(data.studies).toHaveLength(0);
|
||||
expect(data.pairs[0].key).toBe(pair.key);
|
||||
});
|
||||
});
|
||||
|
||||
@Component({ selector: 'app-tea-record', template: '<h2>Datos</h2><h2>Línea del tiempo</h2>' })
|
||||
class RecordStub {
|
||||
readonly id = input.required<string>();
|
||||
}
|
||||
|
||||
describe('Secciones por dominio', () => {
|
||||
it('elige las secciones TEA y sigue mostrando las secciones de CaCu y CaMa', async () => {
|
||||
const read = vi.fn(async () => record.patient);
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideRouter([]), { provide: Fhir, useValue: { read, all: async () => [] } }],
|
||||
}).overrideComponent(Paciente, {
|
||||
remove: { imports: [TeaRecord] },
|
||||
add: { imports: [RecordStub] },
|
||||
});
|
||||
const fixture = TestBed.createComponent(Paciente);
|
||||
fixture.componentRef.setInput('id', 'child');
|
||||
fixture.componentRef.setInput('domain', 'tea');
|
||||
await fixture.whenStable();
|
||||
expect(fixture.nativeElement.querySelector('app-tea-record')?.textContent).toContain(
|
||||
'Línea del tiempo',
|
||||
);
|
||||
expect(read).not.toHaveBeenCalled();
|
||||
|
||||
for (const domain of ['cacu', 'cama']) {
|
||||
fixture.componentRef.setInput('domain', domain);
|
||||
await fixture.whenStable();
|
||||
expect(fixture.nativeElement.querySelector('app-tea-record')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).toContain('Historial médico');
|
||||
expect(read).toHaveBeenCalledWith(domain, 'Patient', 'child');
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user