Files
WebApp/src/app/paciente/tea-patient.ts
T
alberto 3f6fa28590 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.
2026-11-30 14:19:03 -06:00

208 lines
6.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Component, computed, ElementRef, inject, input, resource, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { RouterLink } from '@angular/router';
import { Api } from '../api/api';
import { curve } from '../api/fn/models/curve';
import { Fhir } from '../fhir';
import { Plot } from '../plot';
import { loadTeaPatient, Study } from './tea-data';
import { ageNorm, Centile, forest, probabilityCurve, zBars } from './tea-figures';
import {
calculation,
exportTeaPdf,
forestTitle,
limitations,
probabilityRows,
probabilityTitle,
recordSections,
Section,
} from './tea-sections';
@Component({
selector: 'app-tea-section',
imports: [MatCardModule, Plot],
templateUrl: './tea-section.html',
styleUrl: './tea-section.scss',
})
export class TeaSection {
readonly section = input.required<Section>();
}
@Component({
selector: 'app-tea-record',
imports: [TeaSection, RouterLink, MatButtonModule],
templateUrl: './tea-record.html',
})
export class TeaRecord {
private readonly fhir = inject(Fhir);
private readonly api = inject(Api);
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
readonly id = input.required<string>();
protected readonly patient = resource({
params: () => this.id(),
loader: ({ params }) => loadTeaPatient(this.fhir, params),
});
protected readonly norms = resource({
params: () => (this.patient.hasValue() ? this.patient.value().studies : undefined),
loader: ({ params }) => this.loadNorms(params),
});
protected readonly sections = computed(() => {
const patient = this.patient.hasValue() ? this.patient.value() : undefined;
return patient
? recordSections(patient, this.norms.hasValue() ? this.norms.value() : new Map())
: [];
});
protected readonly exporting = signal(false);
protected readonly exportError = signal(false);
private async loadNorms(studies: Study[]) {
const curves = new Map<string, Promise<Centile[]>>();
const charts = await Promise.all(
studies.flatMap((eeg) =>
eeg.metrics.map(async (metric) => {
const model = /^tea\.([^/]+)\/([1-9]\d*)$/.exec(metric.model ?? '');
if (
!model ||
metric.key === 'paroxysmal_spikes' ||
metric.value == null ||
eeg.age == null
) {
return undefined;
}
const [, name, version] = model;
const key = model[0];
if (!curves.has(key)) {
curves.set(
key,
this.api
.invoke(curve, { domain: 'tea', name, version: Number(version) })
.then((rows) => rows as Centile[])
.catch(() => []),
);
}
const rows = await curves.get(key)!;
if (!rows.some((row) => row.median != null)) return undefined;
return [
`${eeg.id}|${metric.key}`,
{
title: 'Norma por edad · p5–p95',
figure: ageNorm(rows, metric, eeg.age),
},
] as const;
}),
),
);
return new Map(charts.filter((chart) => chart !== undefined));
}
protected async download(): Promise<void> {
this.exportError.set(false);
this.exporting.set(true);
try {
await exportTeaPdf(
'seguimiento',
'Expediente TEA',
this.sections(),
this.host.nativeElement.querySelectorAll<HTMLDivElement>('app-plot .plot'),
);
} catch {
this.exportError.set(true);
} finally {
this.exporting.set(false);
}
}
}
@Component({
selector: 'app-tea-risk',
imports: [TeaSection, RouterLink, MatButtonModule],
templateUrl: './tea-risk.html',
})
export class TeaRisk {
private readonly fhir = inject(Fhir);
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
readonly id = input.required<string>();
protected readonly patient = resource({
params: () => this.id(),
loader: ({ params }) => loadTeaPatient(this.fhir, params),
});
protected readonly onlyAltered = signal(false);
protected readonly selectedKey = signal('');
protected readonly selectedPair = computed(() => {
const pairs = this.patient.hasValue() ? this.patient.value().pairs : [];
return pairs.find((pair) => pair.key === this.selectedKey()) ?? pairs[0];
});
protected readonly forestTitle = forestTitle;
protected readonly probabilityTitle = probabilityTitle;
protected readonly sections = computed<Section[]>(() => {
if (!this.patient.hasValue()) return [];
const patient = this.patient.value();
const studies = patient.riskStudy ? [patient.riskStudy] : patient.studies;
const scores = studies
.map((eeg) => ({ date: eeg.date, figure: zBars(eeg) }))
.find(({ figure }) => figure.data[0].x?.length);
const effects = forest(patient.pairs, this.onlyAltered());
const pair = this.selectedPair();
return [
{ title: 'Qué calcula', blocks: [{ text: calculation }] },
{
title: 'Puntuaciones z por métrica y zona',
blocks: scores
? [
{
chart: {
title: scores.date,
figure: scores.figure,
height: Math.max(340, 24 * (scores.figure.data[0].x?.length ?? 0) + 80),
},
},
]
: [],
},
{
title: forestTitle,
blocks: [
effects.data[0].x?.length
? {
chart: {
title: 'OR e IC 95 %',
figure: effects,
height: Math.max(340, 26 * effects.data[0].x.length + 80),
},
}
: { text: '—' },
],
},
{
title: 'Probabilidad frente a la referencia',
blocks: [{ table: probabilityRows(patient.pairs) }],
},
{
title: probabilityTitle,
blocks: pair ? [{ chart: { title: pair.title, figure: probabilityCurve(pair) } }] : [],
},
{ title: 'Limitaciones', blocks: [{ text: limitations }] },
];
});
protected readonly exporting = signal(false);
protected readonly exportError = signal(false);
protected async download(): Promise<void> {
this.exportError.set(false);
this.exporting.set(true);
try {
await exportTeaPdf(
'riesgos',
'Análisis de riesgo TEA',
this.sections(),
this.host.nativeElement.querySelectorAll<HTMLDivElement>('app-plot .plot'),
);
} catch {
this.exportError.set(true);
} finally {
this.exporting.set(false);
}
}
}