Merge parity/F1c

# Conflicts:
#	src/app/indicadores/tea-indicators.spec.ts
This commit is contained in:
2026-12-01 11:51:57 -06:00
11 changed files with 687 additions and 242 deletions
+27 -18
View File
@@ -145,8 +145,14 @@
<tr>
<th scope="col">Expediente</th>
<th scope="col">Nombre</th>
<th scope="col">Pares</th>
<th scope="col">Acciones</th>
<th scope="col">Sexo</th>
<th scope="col">Edad (meses)</th>
<th scope="col">Asociación principal</th>
<th scope="col">Razón de momios</th>
<th scope="col">IC 95 %</th>
<th scope="col">q</th>
<th scope="col">Probabilidad</th>
<th scope="col">Probabilidad de referencia</th>
</tr>
</thead>
<tbody>
@@ -158,9 +164,6 @@
<a [routerLink]="['/indicadores', 'tea', 'pacientes', id]">
{{ row.name || '—' }}
</a>
</td>
<td>{{ row.pairs.length || '—' }}</td>
<td>
<div class="row-actions">
@if (row.pairs.length) {
<button
@@ -175,33 +178,39 @@
<a [routerLink]="['/indicadores', 'tea', 'pacientes', id, 'riesgo']">Riesgo</a>
</div>
</td>
<td>{{ row.patient.gender ? name(row.patient.gender) : '—' }}</td>
<td>{{ ageMonths(row.patient.birthDate, cutoff()) ?? '—' }}</td>
<td>{{ row.headline?.title ?? '—' }}</td>
<td>{{ formatOr(row.headline?.or) }}</td>
<td>{{ formatIc(row.headline?.low, row.headline?.high) }}</td>
<td>{{ formatQ(row.headline?.q) }}</td>
<td>{{ formatProbability(row.headline?.probability) }}</td>
<td>{{ formatProbability(row.headline?.reference) }}</td>
</tr>
@if (expanded()[id] && row.pairs.length) {
<tr>
<td colspan="4">
<td colspan="10">
<table class="plain pairs">
<thead>
<tr>
<th>Par</th>
<th>OR (IC)</th>
<th>Razón de momios</th>
<th>IC 95 %</th>
<th>q</th>
<th>Probabilidad</th>
<th>Referencia</th>
<th>Probabilidad de referencia</th>
<th>Mismo sentido</th>
</tr>
</thead>
<tbody>
@for (pair of row.pairs; track pair.pair) {
<tr>
<td>{{ pair.pair || '—' }}</td>
<td>
{{ (pair.or | number: '1.0-3') ?? '—' }} ({{
(pair.low | number: '1.0-3') ?? '—'
}}–{{ (pair.high | number: '1.0-3') ?? '—' }})
</td>
<td>{{ (pair.q | number: '1.0-4') ?? '—' }}</td>
<td>{{ (pair.probability | number: '1.0-4') ?? '—' }}</td>
<td>{{ (pair.reference | number: '1.0-4') ?? '—' }}</td>
<td>{{ pair.title }}</td>
<td>{{ formatOr(pair.or) }}</td>
<td>{{ formatIc(pair.low, pair.high) }}</td>
<td>{{ formatQ(pair.q) }}</td>
<td>{{ formatProbability(pair.probability) }}</td>
<td>{{ formatProbability(pair.reference) }}</td>
<td>
{{ pair.sameDirection == null ? '—' : pair.sameDirection ? 'Sí' : 'No' }}
</td>
@@ -214,7 +223,7 @@
}
} @empty {
<tr>
<td colspan="4" class="muted">No hay registros para los filtros aplicados.</td>
<td colspan="10" class="muted">No hay registros para los filtros aplicados.</td>
</tr>
}
</tbody>
+10 -2
View File
@@ -1,5 +1,4 @@
import { HttpClient } from '@angular/common/http';
import { DecimalPipe } from '@angular/common';
import { Component, computed, inject, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
@@ -17,11 +16,16 @@ import { name } from './measures';
import { Pager } from './pager';
import { PatientSearch } from './patient-search';
import {
ageMonths,
ASSOCIATION_LABELS,
associationRows,
DEFAULT_ASSOCIATION_FILTER,
exportTea,
fetchTeaRows,
formatIc,
formatOr,
formatProbability,
formatQ,
matchesTeaSearch,
parameters,
SCORE_FILTERS,
@@ -34,7 +38,6 @@ import {
@Component({
selector: 'app-tab-riesgos-tea',
imports: [
DecimalPipe,
FormsModule,
Loading,
MatButtonModule,
@@ -57,6 +60,11 @@ export class TabRiesgosTea {
protected readonly tokenFilters = TOKEN_FILTERS;
protected readonly scoreFilters = SCORE_FILTERS;
protected readonly name = name;
protected readonly ageMonths = ageMonths;
protected readonly formatOr = formatOr;
protected readonly formatIc = formatIc;
protected readonly formatQ = formatQ;
protected readonly formatProbability = formatProbability;
protected readonly search = signal('');
protected readonly association = signal<AssociationFilter>(DEFAULT_ASSOCIATION_FILTER);
protected readonly associationLabels = ASSOCIATION_LABELS;
+11 -14
View File
@@ -103,18 +103,16 @@
<th scope="col">Expediente</th>
<th scope="col">Nombre</th>
<th scope="col">Sexo</th>
<th scope="col">Edad</th>
<th scope="col">Etapas</th>
<th scope="col">Estado del caso</th>
<th scope="col">M-CHAT</th>
<th scope="col">CSS</th>
<th scope="col">EEG</th>
<th scope="col">Concordancia</th>
<th scope="col">Edad (meses)</th>
<th scope="col">Etapa</th>
<th scope="col">Puntaje M-CHAT</th>
<th scope="col">CSS ADOS-2</th>
<th scope="col">Estatus de EEG</th>
<th scope="col">Alteraciones encontradas</th>
</tr>
</thead>
<tbody>
@for (row of rows(); track row.patient.id) {
@let age = ageMonths(row.patient.birthDate, cutoff());
<tr>
<td>{{ row.recordNumbers.join(', ') || '—' }}</td>
<td>
@@ -123,17 +121,16 @@
</a>
</td>
<td>{{ row.patient.gender ? name(row.patient.gender) : '—' }}</td>
<td>{{ age == null ? '—' : age + ' meses' }}</td>
<td>{{ row.step ?? '—' }}</td>
<td>{{ row.case ? name(row.case) : '—' }}</td>
<td>{{ ageMonths(row.patient.birthDate, cutoff()) ?? '—' }}</td>
<td><app-tea-stepper [steps]="row.steps" /></td>
<td>{{ row.mchatScore ?? '—' }}</td>
<td>{{ row.css ?? '—' }}</td>
<td>{{ eegDisplay(row.eegResult) }}</td>
<td>{{ row.concordance }}</td>
<td>{{ eegResultLabel(row.eegResult) }}</td>
<td>{{ row.alterations ?? '—' }}</td>
</tr>
} @empty {
<tr>
<td colspan="10" class="muted">
<td colspan="9" class="muted">
@if (focused()) {
Este paciente no está en la lista de seguimiento
} @else {
+75 -5
View File
@@ -8,12 +8,14 @@ import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
import { Loading } from '../loading';
import type { TeaStep } from '../paciente/tea-data';
import { windowStart } from './follow-up';
import { name } from './measures';
import { Pager } from './pager';
import { PatientSearch, patientSearch } from './patient-search';
import {
ageMonths,
eegResultLabel,
exportTea,
fetchTeaRows,
parameters,
@@ -25,6 +27,77 @@ import {
type TeaFilters,
} from './tea-rows';
@Component({
selector: 'app-tea-stepper',
template: `
<ol role="list" aria-label="Etapas del tamizaje">
@for (step of steps(); track step.code; let i = $index) {
<li
[class.completed]="step.completed"
[class.connected]="step.completed && steps()[i + 1]?.completed"
[attr.aria-current]="i === lastCompleted() ? 'step' : null"
[attr.aria-label]="status(step)"
[attr.title]="status(step)"
>
<span class="circle" aria-hidden="true"></span>
</li>
}
</ol>
`,
styles: `
ol {
--circle-size: 12px;
display: flex;
width: max-content;
padding: 0;
margin: 0;
list-style: none;
}
li {
position: relative;
display: flex;
flex: 1 1 0;
min-width: 24px;
}
li:not(:last-child)::after {
content: '';
position: absolute;
top: calc(var(--circle-size) / 2 - 1px);
left: calc(50% + var(--circle-size) / 2);
width: max(0px, calc(100% - var(--circle-size)));
height: 2px;
background: var(--color-text-secondary);
}
li.connected::after {
background: var(--color-primary);
}
.circle {
box-sizing: border-box;
width: var(--circle-size);
height: var(--circle-size);
margin: 0 auto;
border: 1px solid var(--color-text-secondary);
border-radius: 50%;
}
li.completed .circle {
background: var(--color-primary);
border-color: var(--color-primary);
}
`,
})
class TeaStepper {
readonly steps = input.required<TeaStep[]>();
protected readonly lastCompleted = computed(() =>
this.steps()
.map((step) => step.completed)
.lastIndexOf(true),
);
protected status(step: TeaStep): string {
return `${step.label}: ${step.completed ? 'completado' : 'pendiente'}`;
}
}
@Component({
selector: 'app-tab-seguimiento-tea',
imports: [
@@ -37,6 +110,7 @@ import {
PatientSearch,
Pager,
RouterLink,
TeaStepper,
],
templateUrl: './tab-seguimiento-tea.html',
styleUrl: './tab-seguimiento-tea.scss',
@@ -54,11 +128,11 @@ export class TabSeguimientoTea {
({ key }) => key !== 'sex' && key !== 'alteration' && key !== 'status',
);
protected readonly scoreFilters = SCORE_FILTERS;
private readonly eegOptions = TOKEN_FILTERS.find(({ key }) => key === 'eeg')!.options;
protected readonly size = signal(20);
protected readonly search = signal('');
protected readonly name = name;
protected readonly ageMonths = ageMonths;
protected readonly eegResultLabel = eegResultLabel;
private readonly request = computed(() => {
const id = this.focused();
@@ -99,10 +173,6 @@ export class TabSeguimientoTea {
protected readonly exporting = signal(false);
protected readonly actionError = signal('');
protected eegDisplay(code: string | undefined): string {
return this.eegOptions.find((option) => option.code === code)?.label ?? '—';
}
protected clearFocus(id: string): void {
this.cleared.set(id);
}
+169 -18
View File
@@ -1,5 +1,6 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { EXT } from '../fhir';
import { teaSteps } from '../paciente/tea-data';
import {
ageStack,
nestedDonut,
@@ -9,10 +10,15 @@ import {
teaSankey,
teaSexDonut,
} from './figures';
import { teaSteps } from '../paciente/tea-data';
import type { Catalog } from './pages';
import {
ageMonths,
associationRows,
formatIc,
formatOr,
formatProbability,
formatQ,
matchesTeaSearch,
teaParams,
teaRows,
@@ -34,6 +40,9 @@ function fixture(): Bundle {
{ url: EXT + 'tea-step', valueCode: 'eeg' },
{ url: EXT + 'tea-case', valueCode: 'confirmed' },
{ url: EXT + 'tea-eeg-result', valueCode: 'normal' },
{ url: EXT + 'tea-mchat', valueDecimal: 9 },
{ url: EXT + 'tea-css', valueInteger: 8 },
{ url: EXT + 'tea-alterations', valueInteger: 2 },
],
};
const ados: Observation = {
@@ -71,6 +80,8 @@ function fixture(): Bundle {
{ url: EXT + 'association-headline', valueBoolean: true },
{ url: EXT + 'association-reference-probability', valueDecimal: 0.35 },
{ url: EXT + 'association-odds-ratio', valueDecimal: 2 },
{ url: EXT + 'association-ci-low', valueDecimal: 1.2 },
{ url: EXT + 'association-ci-high', valueDecimal: 4.5 },
{ url: EXT + 'association-q', valueDecimal: 0.01 },
],
},
@@ -82,9 +93,17 @@ function fixture(): Bundle {
code: { coding: [{ code: 'eeg' }] },
subject,
effectiveDateTime: '2026-03-04',
conclusionCode: [{ text: 'Bueno' }],
conclusionCode: [{ coding: [{ code: 'good' }], text: 'Bueno' }],
extension: [{ url: EXT + 'eeg-channels', valueInteger: 19 }],
};
const neurology: Observation = {
resourceType: 'Observation',
status: 'final',
subject,
code: { coding: [{ code: 'clinical_note.specialty' }] },
valueCodeableConcept: { coding: [{ code: 'pediatric_neurology' }] },
effectiveDateTime: '2026-03-03',
};
return {
resourceType: 'Bundle',
type: 'searchset',
@@ -93,6 +112,7 @@ function fixture(): Bundle {
{ resource: { resourceType: 'Patient', id: 'other' }, search: { mode: 'match' } },
{ resource: ados, search: { mode: 'include' } },
{ resource: risk, search: { mode: 'include' } },
{ resource: neurology, search: { mode: 'include' } },
{ resource: eeg, search: { mode: 'include' } },
...['2026-03-01', '2026-02-27'].map((date) => ({
search: { mode: 'include' as const },
@@ -101,7 +121,7 @@ function fixture(): Bundle {
status: 'final' as const,
subject,
code: { coding: [{ code: 'mchat.score' }] },
valueQuantity: { value: 9 },
valueQuantity: { value: 7 },
effectiveDateTime: date,
},
})),
@@ -177,36 +197,54 @@ describe('TEA indicators', () => {
expect(teaParams({ cssMax: 0 })['tea-css']).toEqual(['le0']);
});
it('uses follow-up codes and assembles the included dates and association headline', () => {
it('reads the follow-up extensions and assembles the stepper and association headline', () => {
const [row, other] = teaRows(fixture());
expect(row.steps.map(({ date }) => date)).toEqual([
'2026-02-27',
'2026-03-02',
undefined,
'2026-03-03',
'2026-03-04',
]);
expect(row.steps.map(({ completed }) => completed)).toEqual([true, true, true, true]);
expect(row).toMatchObject({
name: 'Ana López',
step: 'EEG',
case: 'confirmed',
eegResult: 'normal',
recordNumbers: ['123'],
mchatScore: 9,
css: 8,
headline: { pair: cssPair, or: 2, q: 0.01 },
concordance: 'Concordante',
alterations: 2,
headline: {
pair: cssPair,
title: 'Husos N2 · Central · CSS',
or: 2,
low: 1.2,
high: 4.5,
q: 0.01,
},
});
expect(other.concordance).toBe('—');
expect(other.headline).toBeUndefined();
});
it('compares the headline item score with the prediction and reference', () => {
it('titles an item association with the patient’s ADOS-2 item', () => {
const page = fixture();
const risk = page.entry!.find((e) => e.resource?.resourceType === 'RiskAssessment')!
.resource as RiskAssessment;
const prediction = risk.prediction![0];
prediction.outcome = { coding: [{ code: 'rhythm|central|ados2_item_01' }] };
prediction.probabilityDecimal = 0.1;
expect(teaRows(page)[0].concordance).toBe('No concordante');
risk.prediction![0].outcome = { coding: [{ code: 'posterior_rhythm|central|ados2_item_01' }] };
expect(teaRows(page)[0].headline?.title).toBe(
'Ritmo posterior · Central · Frecuencia de la vocalización espontánea dirigida a otros',
);
});
it('formats the association values like the reference list', () => {
expect(formatOr(2)).toBe('2.00');
expect(formatOr(undefined)).toBe('—');
expect(formatIc(1.2, 4.5)).toBe('1.20–4.50');
expect(formatIc(undefined, 4.5)).toBe('—');
expect(formatQ(0.0004)).toBe('< 0.001');
expect(formatQ(0.0123)).toBe('0.012');
expect(formatQ(undefined)).toBe('—');
expect(formatProbability(0.35)).toBe('35 %');
expect(formatProbability(undefined)).toBe('—');
});
it('defaults to all children and filters by association results', () => {
@@ -230,13 +268,20 @@ describe('TEA indicators', () => {
});
it('builds the follow-up workbook', () => {
expect(teaWorkbook(teaRows(fixture()), false, DAY)).toEqual({
expect(teaWorkbook(teaRows(fixture()), false, '2026-03-31', DAY)).toEqual({
name: 'tea-seguimiento-2026-11-30',
sheets: [
expect.objectContaining({
name: 'Seguimiento',
rows: expect.arrayContaining([
expect.objectContaining({ id: 'child', pair: cssPair, eeg: '2026-03-04' }),
expect.objectContaining({
id: 'child',
eeg: '2026-03-04',
mchat: 9,
css: 8,
eegResult: 'Normal',
alterations: 2,
}),
]),
}),
],
@@ -244,10 +289,23 @@ describe('TEA indicators', () => {
});
it('builds the risk workbook with children and pair details', () => {
expect(teaWorkbook(associationRows(teaRows(fixture())), true, DAY)).toEqual({
expect(teaWorkbook(associationRows(teaRows(fixture())), true, '2026-03-31', DAY)).toEqual({
name: 'tea-riesgos-2026-11-30',
sheets: [
expect.objectContaining({ name: 'Niños' }),
expect.objectContaining({
name: 'Niños',
rows: expect.arrayContaining([
expect.objectContaining({
id: 'child',
pair: 'Husos N2 · Central · CSS',
or: 2,
low: 1.2,
high: 4.5,
probability: 0.35,
reference: 0.35,
}),
]),
}),
expect.objectContaining({
name: 'Pares',
rows: [
@@ -361,3 +419,96 @@ describe('TEA clinical figures', () => {
});
});
});
const observation = (field: string, day: string, value?: string): Observation => ({
resourceType: 'Observation',
status: 'final',
code: { coding: [{ code: field }] },
effectiveDateTime: day,
...(value ? { valueCodeableConcept: { coding: [{ code: value }] } } : {}),
});
const eeg = (day: string, quality: string): DiagnosticReport => ({
resourceType: 'DiagnosticReport',
status: 'final',
code: { coding: [{ code: 'eeg' }] },
effectiveDateTime: day,
conclusionCode: [{ coding: [{ code: quality }] }],
});
describe('Etapas del tamizaje TEA', () => {
it('toma la primera fecha de cada etapa en el orden del proceso', () => {
const steps = teaSteps(
[
observation('mchat.score', '2026-03-01'),
observation('mchat.score', '2026-02-27'),
observation('ados2', '2026-03-04'),
observation('clinical_note.specialty', '2026-03-06', 'pediatric_neurology'),
],
[eeg('2026-03-10', 'good')],
);
expect(steps.map(({ code, label }) => ({ code, label }))).toEqual([
{ code: 'mchat_only', label: 'M-CHAT' },
{ code: 'psychology', label: 'Psicología' },
{ code: 'neurology', label: 'Neuropediatría' },
{ code: 'eeg', label: 'EEG' },
]);
expect(steps.map((step) => step.date)).toEqual([
'2026-02-27',
'2026-03-04',
'2026-03-06',
'2026-03-10',
]);
expect(steps.every((step) => step.completed)).toBe(true);
});
it('completa el EEG solo con un estudio de buena calidad', () => {
const observations = [
observation('mchat.score', '2026-02-27'),
observation('ados2', '2026-03-04'),
observation('clinical_note.specialty', '2026-03-06', 'pediatric_neurology'),
observation('eeg.lab_record_id', '2026-03-08'),
];
const steps = teaSteps(observations, [eeg('2026-03-10', 'bad'), eeg('2026-03-12', 'good')]);
expect(steps[3]).toMatchObject({ date: '2026-03-12', completed: true });
expect(teaSteps(observations, [eeg('2026-03-10', 'bad')])[3]).toMatchObject({
date: undefined,
completed: false,
});
expect(teaSteps(observations, [])[3]).toMatchObject({ date: undefined, completed: false });
});
it('ignora las notas de otras especialidades', () => {
const steps = teaSteps(
[
observation('mchat.score', '2026-02-27'),
observation('ados2', '2026-03-04'),
observation('clinical_note.specialty', '2026-03-06', 'pediatrics'),
],
[],
);
expect(steps[2]).toMatchObject({ date: undefined, completed: false });
});
it('deja pendientes las etapas tras un hueco', () => {
const steps = teaSteps(
[observation('mchat.score', '2026-02-27'), observation('ados2', '2026-03-04')],
[eeg('2026-03-10', 'good')],
);
expect(steps.map((step) => step.completed)).toEqual([true, true, false, false]);
expect(steps[3].date).toBeUndefined();
});
it('usa la etapa registrada para mostrar el avance del seguimiento', () => {
const steps = teaSteps([], [], 'neurology');
expect(steps.map((step) => step.completed)).toEqual([true, true, true, false]);
});
it('fecha cada etapa a partir de la anterior cuando el estudio ocurrió antes', () => {
const steps = teaSteps(
[observation('mchat.score', '2026-02-27'), observation('ados2', '2026-02-26')],
[],
);
expect(steps[1]).toMatchObject({ date: '2026-02-27', completed: true });
});
});
+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);
}