F1c: user fixes

Render the worklist stepper from the Patient stage and read M-CHAT, CSS
and alteration count from its FHIR extensions. Keep the compact stepper
private to Seguimiento and share the dated screening logic with the
patient record. Use the first dated event for each step, require prior
steps, and use the later date when an event predates its prerequisite.
Only a good-quality EEG completes that stage.

Use horizontal Plotly bars on the destination rows for elapsed spans,
diamonds for completed steps, and labels for pending steps. Keep the
screening order on the axis and show 30 days on either side when all
completed steps share one date. Reuse the registered bar and scatter
traces and the rebuild palette.

Use completed months at the applied cutoff and show the marked headline
association with the reference formatting. Resolve item labels from
the model's ADOS-2 observation and fall back to the item code. Move the
existing detail and risk actions into the patient-name cell to keep the
requested ten columns. Keep raw association numbers and separate CI
bounds in Excel and keep the screening dates in the follow-up export.

Update the two logic specs and the follow-up, risk and record page
assertions. All 34 targeted Vitest cases passed with Plotly rendering
stubbed. The local TypeScript check reached the existing PDF export
code and reported missing pdfmake typings. Angular and page runs are
reserved for the test machines.
This commit is contained in:
2026-12-01 11:32:17 -06:00
parent 7c98566579
commit a2bf98e9da
11 changed files with 686 additions and 242 deletions
+104 -102
View File
@@ -1,17 +1,10 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { ados2Component } from '../ados2';
import { downloadXlsx, safeName, type Sheet } from '../export';
import { code, ext, patientName, resources, type Fhir, type Params } from '../fhir';
import { pairTitle, TEA_STEPS, teaSteps } from '../paciente/tea-data';
import { name } from './measures';
import { matchesSearch } from './patient-search';
const TEA_STEPS = [
{ code: 'mchat_only', label: 'M-CHAT' },
{ code: 'psychology', label: 'Psicología' },
{ code: 'neurology', label: 'Neuropediatría' },
{ code: 'eeg', label: 'EEG' },
] as const;
type Prediction = NonNullable<RiskAssessment['prediction']>[number];
function associationPair(p: Prediction) {
@@ -29,18 +22,6 @@ function associationPair(p: Prediction) {
};
}
function concordance(headline?: ReturnType<typeof associationPair>, ados?: Observation): string {
if (!headline || !ados || headline.probability == null || headline.reference == null) return '—';
const outcome = headline.pair?.split('|')[2];
const item = Number(outcome?.match(/^ados2_item_(\d{2})$/)?.[1]);
const score =
outcome === 'CSS' ? ados.valueInteger : ados2Component(ados, item)?.valueQuantity?.value;
if (score == null) return '—';
const event = score >= (outcome === 'CSS' ? 8 : 1);
const predicted = headline.probability >= headline.reference;
return event === predicted ? 'Concordante' : 'No concordante';
}
function byPatient<T extends DiagnosticReport | Observation | RiskAssessment>(
records: T[],
): Map<string | undefined, T[]> {
@@ -58,42 +39,23 @@ export function teaRows(page: Bundle) {
const reports = byPatient(resources<DiagnosticReport>(page, 'DiagnosticReport'));
const observations = byPatient(resources<Observation>(page, 'Observation'));
const risks = byPatient(resources<RiskAssessment>(page, 'RiskAssessment'));
const dateOrder = (a: Observation | DiagnosticReport, b: Observation | DiagnosticReport) =>
(a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? '');
return resources<Patient>(page, 'Patient', 'match').map((patient) => {
const subject = `Patient/${patient.id}`;
const obs = observations.get(subject) ?? [];
const eegs = (reports.get(subject) ?? []).filter((r) => code(r.code) === 'eeg').sort(dateOrder);
const ados = obs.filter((o) => code(o.code) === 'ados2').sort(dateOrder);
const mchat = obs.filter((o) => code(o.code) === 'mchat.score').sort(dateOrder)[0];
const neurology = obs
.filter(
(o) =>
code(o.code) === 'clinical_note.specialty' &&
code(o.valueCodeableConcept) === 'pediatric_neurology',
)
.sort(dateOrder)[0];
const ados = obs
.filter((o) => code(o.code) === 'ados2')
.sort((a, b) => (a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? ''));
const risk = risks.get(subject)?.[0];
const pairs = (risk?.prediction ?? []).map(associationPair);
const headline = pairs.find((p) => p.headline);
const basisAdos = risk?.basis?.find((ref) =>
ref.reference?.startsWith('Observation/'),
)?.reference;
const evaluation = basisAdos
? ados.find((o) => `Observation/${o.id}` === basisAdos)
: ados.at(-1);
const dates = [
mchat?.effectiveDateTime,
ados[0]?.effectiveDateTime,
neurology?.effectiveDateTime,
[
...eegs.map((e) => e.effectiveDateTime),
...obs.filter((o) => code(o.code) === 'eeg.lab_record_id').map((o) => o.effectiveDateTime),
]
.filter((day) => !!day)
.sort()[0],
];
const step = ext(patient, 'tea-step')?.valueCode;
const pairs = (risk?.prediction ?? []).map((p) => {
const pair = associationPair(p);
return { ...pair, title: pairTitle(pair.pair ?? '', evaluation) };
});
return {
patient,
name: patientName(patient),
@@ -104,14 +66,12 @@ export function teaRows(page: Bundle) {
.map((i) => i.value!),
),
],
step: TEA_STEPS.find(({ code }) => code === step)?.label,
case: ext(patient, 'tea-case')?.valueCode,
eegResult: ext(patient, 'tea-eeg-result')?.valueCode,
steps: TEA_STEPS.map((step, i) => ({ ...step, date: dates[i] })),
mchatScore: mchat?.valueQuantity?.value,
css: ados.at(-1)?.valueInteger,
headline,
concordance: concordance(headline, evaluation),
steps: teaSteps(obs, reports.get(subject) ?? [], ext(patient, 'tea-step')?.valueCode),
mchatScore: ext(patient, 'tea-mchat')?.valueDecimal,
css: ext(patient, 'tea-css')?.valueInteger,
alterations: ext(patient, 'tea-alterations')?.valueInteger,
headline: pairs.find((p) => p.headline),
pairs,
};
});
@@ -233,6 +193,22 @@ function choices(...codes: string[]) {
return codes.map((code) => ({ code, label: name(code) }));
}
export function eegResultLabel(result: string | undefined): string {
const filter = TOKEN_FILTERS.find(({ key }) => key === 'eeg')!;
return filter.options.find((option) => option.code === result)?.label ?? '—';
}
export const formatOr = (value?: number): string => (value == null ? '—' : value.toFixed(2));
export const formatIc = (low?: number, high?: number): string =>
low == null || high == null ? '—' : `${low.toFixed(2)}–${high.toFixed(2)}`;
export const formatQ = (q?: number): string =>
q == null ? '—' : q < 0.001 ? '< 0.001' : q.toFixed(3);
export const formatProbability = (probability?: number): string =>
probability == null ? '—' : `${Math.round(probability * 100)} %`;
export function matchesTeaSearch(row: TeaRow, query: string): boolean {
return matchesSearch(query, [
...(row.patient.name ?? []).map(({ text }) => text),
@@ -258,61 +234,87 @@ const columns = (entries: [string, string][]): Sheet['columns'] =>
export function teaWorkbook(
rows: TeaRow[],
risk: boolean,
cutoff = '',
day = new Date(),
): { name: string; sheets: Sheet[] } {
const identity: [string, string][] = [
['id', 'Paciente'],
['record', 'Expediente'],
['name', 'Nombre'],
['sex', 'Sexo'],
['birth', 'Nacimiento'],
['age', 'Edad (meses)'],
];
const headline: [string, string][] = [
['pair', 'Par principal'],
['or', 'OR'],
['q', 'q'],
['concordance', 'Concordancia con el ADOS-2'],
];
const steps: [string, string][] = TEA_STEPS.map(({ code, label }) => [code, label]);
const sheets: Sheet[] = [
{
name: risk ? 'Niños' : 'Seguimiento',
columns: columns([
...identity,
['sex', 'Sexo'],
['birth', 'Nacimiento'],
...(risk ? [] : steps),
...headline,
]),
rows: rows.map((row) => ({
id: row.patient.id,
record: row.recordNumbers.join(', '),
name: row.name,
sex: row.patient.gender ? name(row.patient.gender) : undefined,
birth: row.patient.birthDate,
...Object.fromEntries(row.steps.map(({ code, date }) => [code, date])),
pair: row.headline?.pair,
or: row.headline?.or,
q: row.headline?.q,
concordance: row.concordance,
})),
},
];
if (risk) {
sheets.push({
name: 'Pares',
columns: columns([
['id', 'Paciente'],
['pair', 'Par'],
['or', 'OR'],
['low', 'IC inferior'],
['high', 'IC superior'],
['q', 'q'],
['probability', 'Probabilidad'],
['reference', 'Referencia'],
['sameDirection', 'Mismo sentido'],
]),
rows: rows.flatMap((row) => row.pairs.map((pair) => ({ id: row.patient.id, ...pair }))),
});
}
const people = rows.map((row) => ({
id: row.patient.id,
record: row.recordNumbers.join(', '),
name: row.name,
sex: row.patient.gender ? name(row.patient.gender) : undefined,
birth: row.patient.birthDate,
age: ageMonths(row.patient.birthDate, cutoff),
}));
const sheets: Sheet[] = risk
? [
{
name: 'Niños',
columns: columns([
...identity,
['pair', 'Asociación principal'],
['or', 'Razón de momios'],
['low', 'IC 95 % inferior'],
['high', 'IC 95 % superior'],
['q', 'q'],
['probability', 'Probabilidad'],
['reference', 'Probabilidad de referencia'],
]),
rows: rows.map((row, i) => ({
...people[i],
pair: row.headline?.title,
or: row.headline?.or,
low: row.headline?.low,
high: row.headline?.high,
q: row.headline?.q,
probability: row.headline?.probability,
reference: row.headline?.reference,
})),
},
{
name: 'Pares',
columns: columns([
['id', 'Paciente'],
['pair', 'Par'],
['or', 'OR'],
['low', 'IC inferior'],
['high', 'IC superior'],
['q', 'q'],
['probability', 'Probabilidad'],
['reference', 'Referencia'],
['sameDirection', 'Mismo sentido'],
]),
rows: rows.flatMap((row) => row.pairs.map((pair) => ({ id: row.patient.id, ...pair }))),
},
]
: [
{
name: 'Seguimiento',
columns: columns([
...identity,
...TEA_STEPS.map(({ code, label }): [string, string] => [code, label]),
['mchat', 'Puntaje M-CHAT'],
['css', 'CSS ADOS-2'],
['eegResult', 'Estatus de EEG'],
['alterations', 'Alteraciones encontradas'],
]),
rows: rows.map((row, i) => ({
...people[i],
...Object.fromEntries(row.steps.map(({ code, date }) => [code, date])),
mchat: row.mchatScore,
css: row.css,
eegResult: eegResultLabel(row.eegResult),
alterations: row.alterations,
})),
},
];
const page = risk ? 'riesgos' : 'seguimiento';
return { name: safeName(['tea', page, day.toISOString().slice(0, 10)]), sheets };
}
@@ -322,7 +324,7 @@ export function exportTea(
params: Record<string, string>,
risk: boolean,
): Promise<void> {
const { name, sheets } = teaWorkbook(rows, risk);
const { name, sheets } = teaWorkbook(rows, risk, params['follow-up-cutoff']);
return downloadXlsx(name, sheets, params);
}