Merge parity/F1c
# Conflicts: # src/app/indicadores/tea-indicators.spec.ts
This commit is contained in:
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,16 +10,51 @@ import { ados2Component, ados2Groups } from '../ados2';
|
||||
import { ZONE_NAMES } from '../eeg-labels';
|
||||
import { code, CURP, ext, Fhir, label, resources } from '../fhir';
|
||||
|
||||
const NSS = 'https://isssteleon.org/fhir/sid/nss';
|
||||
export 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;
|
||||
|
||||
const steps: Record<string, string> = {
|
||||
mchat_only: 'Solo M-CHAT',
|
||||
psychology: 'Psicología',
|
||||
neurology: 'Neurología',
|
||||
eeg: 'EEG',
|
||||
};
|
||||
export type TeaStep = { code: string; label: string; date?: string; completed: boolean };
|
||||
|
||||
const metrics: Record<string, string> = {
|
||||
const firstDate = (items: { effectiveDateTime?: string }[]): string | undefined =>
|
||||
items
|
||||
.map((item) => item.effectiveDateTime)
|
||||
.filter((day): day is string => !!day)
|
||||
.sort()[0];
|
||||
|
||||
export function teaSteps(
|
||||
observations: Observation[],
|
||||
reports: DiagnosticReport[],
|
||||
stage?: string,
|
||||
): TeaStep[] {
|
||||
const dates = [
|
||||
firstDate(observations.filter((o) => code(o.code) === 'mchat.score')),
|
||||
firstDate(observations.filter((o) => code(o.code) === 'ados2')),
|
||||
firstDate(
|
||||
observations.filter(
|
||||
(o) =>
|
||||
code(o.code) === 'clinical_note.specialty' &&
|
||||
code(o.valueCodeableConcept) === 'pediatric_neurology',
|
||||
),
|
||||
),
|
||||
firstDate(
|
||||
reports.filter((r) => code(r.code) === 'eeg' && code(r.conclusionCode?.[0]) === 'good'),
|
||||
),
|
||||
];
|
||||
const current = TEA_STEPS.findIndex(({ code }) => code === stage);
|
||||
let previous: string | undefined;
|
||||
return TEA_STEPS.map((step, i) => {
|
||||
const date = dates[i];
|
||||
const reached = i === 0 ? date : previous && date && (date < previous ? previous : date);
|
||||
previous = reached;
|
||||
return { ...step, date: reached, completed: current < 0 ? reached != null : i <= current };
|
||||
});
|
||||
}
|
||||
|
||||
const METRIC_TITLES: Record<string, string> = {
|
||||
posterior_rhythm: 'Ritmo posterior',
|
||||
spindles_n2: 'Husos N2',
|
||||
spindles_n3: 'Husos N3',
|
||||
@@ -27,13 +62,36 @@ const metrics: Record<string, string> = {
|
||||
anteroposterior_gradient: 'Gradiente anteroposterior',
|
||||
};
|
||||
|
||||
const biomarkers: Record<string, string> = {
|
||||
const BIOMARKER_METRICS: Record<string, string> = {
|
||||
spikes: 'paroxysmal_spikes',
|
||||
spindles: 'spindles_n2',
|
||||
posterior_rhythm: 'posterior_rhythm',
|
||||
gradient: 'anteroposterior_gradient',
|
||||
};
|
||||
|
||||
export function zoneLabel(zone: string): string {
|
||||
return zone === 'frontal_midline' ? 'Frontal medial' : (ZONE_NAMES[zone] ?? zone);
|
||||
}
|
||||
|
||||
export function pairTitle(key: string, ados?: Observation): string {
|
||||
const [biomarker, zone = '', outcome = ''] = key.split('|');
|
||||
const item = /^ados2_item_(\d+)$/.exec(outcome);
|
||||
return [
|
||||
METRIC_TITLES[BIOMARKER_METRICS[biomarker]] ?? biomarker,
|
||||
zoneLabel(zone),
|
||||
item ? label(ados2Component(ados, Number(item[1]))?.code) || outcome : outcome,
|
||||
].join(' · ');
|
||||
}
|
||||
|
||||
const NSS = 'https://isssteleon.org/fhir/sid/nss';
|
||||
|
||||
const steps: Record<string, string> = {
|
||||
mchat_only: 'Solo M-CHAT',
|
||||
psychology: 'Psicología',
|
||||
neurology: 'Neurología',
|
||||
eeg: 'EEG',
|
||||
};
|
||||
|
||||
const classifications: Record<string, string> = {
|
||||
non_spectrum: 'Fuera del espectro',
|
||||
autism_spectrum: 'Espectro autista',
|
||||
@@ -130,46 +188,6 @@ export function adosSummary(observation: Observation): string[][] {
|
||||
];
|
||||
}
|
||||
|
||||
function timeline(observations: Observation[], ados: Observation[], reports: DiagnosticReport[]) {
|
||||
const events = [
|
||||
...ados.map((o) => [o.effectiveDateTime ?? '', 'ADOS-2', adosSummary(o)[2][1]]),
|
||||
...reports.map((r) => [
|
||||
r.effectiveDateTime ?? '',
|
||||
'EEG',
|
||||
shown(quality[code(r.conclusionCode?.[0]) ?? '']),
|
||||
]),
|
||||
];
|
||||
const notes = new Map<string, Observation[]>();
|
||||
for (const o of observations) {
|
||||
const field = code(o.code);
|
||||
const date = o.effectiveDateTime ?? '';
|
||||
if (field === 'mchat.score') {
|
||||
events.push([date, 'M-CHAT', observationValue(o)]);
|
||||
}
|
||||
if (field === 'eeg.lab_record_id' && !reports.some((r) => r.effectiveDateTime === date)) {
|
||||
events.push([date, 'EEG', observationValue(o)]);
|
||||
}
|
||||
if (field?.startsWith('clinical_note.') && o.encounter?.reference) {
|
||||
const group = notes.get(o.encounter.reference) ?? [];
|
||||
group.push(o);
|
||||
notes.set(o.encounter.reference, group);
|
||||
}
|
||||
}
|
||||
for (const group of notes.values()) {
|
||||
const specialty = group.find((o) => code(o.code) === 'clinical_note.specialty');
|
||||
if (code(specialty?.valueCodeableConcept) === 'pediatric_neurology') {
|
||||
const detail = group
|
||||
.filter((o) => o !== specialty)
|
||||
.map(observationValue)
|
||||
.join(' · ');
|
||||
events.push([specialty?.effectiveDateTime ?? '', 'Nota de neurología', shown(detail)]);
|
||||
}
|
||||
}
|
||||
return events
|
||||
.sort((a, b) => b[0].localeCompare(a[0]))
|
||||
.map(([date, kind, detail]) => [shown(date), kind, detail]);
|
||||
}
|
||||
|
||||
function checkRow(o: Observation): string[] {
|
||||
const range = o.referenceRange?.[0];
|
||||
const abnormal = code(o.interpretation?.[0]);
|
||||
@@ -193,7 +211,7 @@ function metric(o: Observation) {
|
||||
const key = code(o.code) ?? '';
|
||||
return {
|
||||
key,
|
||||
title: metrics[key] ?? shown(label(o.code)),
|
||||
title: METRIC_TITLES[key] ?? shown(label(o.code)),
|
||||
value: o.valueQuantity?.value,
|
||||
unit: o.valueQuantity?.unit,
|
||||
z: ext(o, 'eeg-z')?.valueDecimal,
|
||||
@@ -248,10 +266,6 @@ export type Pair = {
|
||||
|
||||
export type Study = ReturnType<typeof study>;
|
||||
|
||||
export function zoneLabel(zone: string): string {
|
||||
return zone === 'frontal_midline' ? 'Frontal medial' : (ZONE_NAMES[zone] ?? zone);
|
||||
}
|
||||
|
||||
export function alteration(outside: number | undefined): string {
|
||||
return outside == null ? '—' : outside < 0 ? 'Bajo' : outside > 0 ? 'Alto' : 'En rango';
|
||||
}
|
||||
@@ -264,20 +278,15 @@ function associations(
|
||||
return (risk?.prediction ?? [])
|
||||
.map((p): Pair => {
|
||||
const key = code(p.outcome) ?? '';
|
||||
const [biomarker, zone = '', outcome = ''] = key.split('|');
|
||||
const metric = eeg?.metrics.find((m) => m.key === biomarkers[biomarker]);
|
||||
const [biomarker, zone = ''] = key.split('|');
|
||||
const metric = eeg?.metrics.find((m) => m.key === BIOMARKER_METRICS[biomarker]);
|
||||
const site =
|
||||
zone === 'global' || biomarker === 'posterior_rhythm'
|
||||
? metric
|
||||
: metric?.sites.find((s) => s.kind === 'zone' && s.name === zone);
|
||||
const item = /^ados2_item_(\d+)$/.exec(outcome);
|
||||
return {
|
||||
key,
|
||||
title: [
|
||||
metric?.title ?? metrics[biomarkers[biomarker]] ?? biomarker,
|
||||
zoneLabel(zone),
|
||||
item ? label(ados2Component(ados[0], Number(item[1]))?.code) || outcome : outcome,
|
||||
].join(' · '),
|
||||
title: pairTitle(key, ados[0]),
|
||||
headline: ext(p, 'association-headline')?.valueBoolean === true,
|
||||
altered: site?.outside != null && site.outside !== 0,
|
||||
z: site?.z,
|
||||
@@ -316,7 +325,7 @@ export async function loadTeaPatient(fhir: Fhir, id: string) {
|
||||
patient,
|
||||
ados,
|
||||
studies,
|
||||
timeline: timeline(observations, ados, reports),
|
||||
steps: teaSteps(observations, reports),
|
||||
riskStudy,
|
||||
pairs: associations(risk, riskStudy, ados),
|
||||
};
|
||||
|
||||
@@ -1,6 +1,98 @@
|
||||
import { banded } from '../gobernanza/figures';
|
||||
import { Figure, PALETTE } from '../plot';
|
||||
import { Metric, Pair, Site, Study, zoneLabel } from './tea-data';
|
||||
import { Metric, Pair, Site, Study, TeaStep, zoneLabel } from './tea-data';
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
const day = (iso: string): string => {
|
||||
const [y, m, d] = iso.slice(0, 10).split('-');
|
||||
return `${d}/${m}/${y}`;
|
||||
};
|
||||
|
||||
export function timeline(steps: TeaStep[]): Figure | null {
|
||||
const done = steps.filter((step): step is TeaStep & { date: string } =>
|
||||
Boolean(step.completed && step.date),
|
||||
);
|
||||
if (!done.length) return null;
|
||||
const spans = done.slice(1).map((step, i) => ({ from: done[i], to: step }));
|
||||
const last = done.at(-1)!.date;
|
||||
const bars = {
|
||||
type: 'bar',
|
||||
orientation: 'h',
|
||||
base: spans.map(({ from }) => from.date),
|
||||
x: spans.map(({ from, to }) => Date.parse(to.date) - Date.parse(from.date)),
|
||||
y: spans.map(({ to }) => to.label),
|
||||
width: 0.24,
|
||||
marker: { color: PALETTE[6] },
|
||||
hoverinfo: 'skip',
|
||||
showlegend: false,
|
||||
} satisfies Figure['data'][number] & { base: string[] };
|
||||
return {
|
||||
data: [
|
||||
bars,
|
||||
{
|
||||
type: 'scatter',
|
||||
mode: 'markers',
|
||||
x: done.map((step) => step.date),
|
||||
y: done.map((step) => step.label),
|
||||
marker: {
|
||||
symbol: 'diamond',
|
||||
size: 16,
|
||||
color: PALETTE[0],
|
||||
line: { color: '#17324d', width: 1 },
|
||||
},
|
||||
customdata: done.map((step) => day(step.date)),
|
||||
hovertemplate: '%{y} · %{customdata}<extra></extra>',
|
||||
showlegend: false,
|
||||
},
|
||||
],
|
||||
layout: {
|
||||
showlegend: false,
|
||||
margin: { l: 140, r: 90, t: 16, b: 40 },
|
||||
xaxis: {
|
||||
type: 'date',
|
||||
tickformat: '%d/%m/%Y',
|
||||
...(done.every((step) => step.date === last)
|
||||
? {
|
||||
range: [
|
||||
new Date(Date.parse(last) - 30 * DAY).toISOString().slice(0, 10),
|
||||
new Date(Date.parse(last) + 30 * DAY).toISOString().slice(0, 10),
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
yaxis: {
|
||||
type: 'category',
|
||||
categoryorder: 'array',
|
||||
categoryarray: steps.map((step) => step.label).reverse(),
|
||||
range: [-0.5, steps.length - 0.5],
|
||||
fixedrange: true,
|
||||
},
|
||||
annotations: [
|
||||
...spans.map((span) => ({
|
||||
x: new Date((Date.parse(span.from.date) + Date.parse(span.to.date)) / 2)
|
||||
.toISOString()
|
||||
.slice(0, 10),
|
||||
y: span.to.label,
|
||||
yshift: 14,
|
||||
showarrow: false,
|
||||
text: `${Math.round((Date.parse(span.to.date) - Date.parse(span.from.date)) / DAY)} días`,
|
||||
})),
|
||||
...steps
|
||||
.filter((step) => !step.completed)
|
||||
.map((step) => ({
|
||||
x: 1,
|
||||
xref: 'paper' as const,
|
||||
xanchor: 'right' as const,
|
||||
y: step.label,
|
||||
showarrow: false,
|
||||
font: { color: PALETTE[6] },
|
||||
text: 'Pendiente',
|
||||
})),
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const electrodes: Record<string, [number, number]> = {
|
||||
Fp1: [-0.3, 0.87],
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Observation, Patient } from 'fhir/r4';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { EXT } from '../fhir';
|
||||
import { identityRows, Metric, Pair } from './tea-data';
|
||||
import { ageNorm, forest, headMap, probabilityCurve, zBars } from './tea-figures';
|
||||
import { identityRows, Metric, Pair, pairTitle, TeaStep, zoneLabel } from './tea-data';
|
||||
import { ageNorm, forest, headMap, probabilityCurve, timeline, zBars } from './tea-figures';
|
||||
import {
|
||||
forestTitle,
|
||||
probabilityTitle,
|
||||
@@ -91,13 +91,20 @@ const ados: Observation = {
|
||||
],
|
||||
};
|
||||
|
||||
const steps: TeaStep[] = [
|
||||
{ code: 'mchat_only', label: 'M-CHAT', date: '2025-11-01', completed: true },
|
||||
{ code: 'psychology', label: 'Psicología', date: '2025-11-22', completed: true },
|
||||
{ code: 'neurology', label: 'Neuropediatría', completed: false },
|
||||
{ code: 'eeg', label: 'EEG', completed: false },
|
||||
];
|
||||
|
||||
const record = {
|
||||
patient: {
|
||||
resourceType: 'Patient' as const,
|
||||
id: 'child',
|
||||
name: [{ text: 'Paciente de prueba' }],
|
||||
},
|
||||
timeline: [['2025-11-22', 'ADOS-2', '—']],
|
||||
steps,
|
||||
ados: [ados],
|
||||
studies: [],
|
||||
riskStudy: undefined,
|
||||
@@ -150,6 +157,47 @@ describe('Figuras del paciente TEA', () => {
|
||||
{ mode: 'markers', x: [0], y: [20] },
|
||||
]);
|
||||
});
|
||||
|
||||
it('marca con un rombo cada etapa completada en su fecha', () => {
|
||||
const figure = timeline(steps)!;
|
||||
const markers = figure.data.find((trace) => trace.type === 'scatter')!;
|
||||
expect(markers).toMatchObject({
|
||||
marker: expect.objectContaining({ symbol: 'diamond' }),
|
||||
x: ['2025-11-01', '2025-11-22'],
|
||||
y: ['M-CHAT', 'Psicología'],
|
||||
});
|
||||
expect(figure.data[0]).toMatchObject({
|
||||
type: 'bar',
|
||||
orientation: 'h',
|
||||
base: ['2025-11-01'],
|
||||
x: [21 * 24 * 60 * 60 * 1000],
|
||||
y: ['Psicología'],
|
||||
});
|
||||
});
|
||||
|
||||
it('anota los días entre etapas y deja pendientes las que faltan', () => {
|
||||
const figure = timeline(steps)!;
|
||||
const notes = figure.layout?.annotations ?? [];
|
||||
expect(notes.map((note) => note.text)).toEqual(['21 días', 'Pendiente', 'Pendiente']);
|
||||
expect(notes.slice(1).map((note) => note.y)).toEqual(['Neuropediatría', 'EEG']);
|
||||
expect(figure.layout?.yaxis?.categoryarray).toEqual([
|
||||
'EEG',
|
||||
'Neuropediatría',
|
||||
'Psicología',
|
||||
'M-CHAT',
|
||||
]);
|
||||
});
|
||||
|
||||
it('amplía el eje de una sola fecha y no dibuja nada sin etapas completadas', () => {
|
||||
const single = timeline([
|
||||
steps[0],
|
||||
...steps.slice(1).map((s) => ({ ...s, completed: false })),
|
||||
])!;
|
||||
expect(single.layout?.xaxis?.range).toEqual(['2025-10-02', '2025-12-01']);
|
||||
expect(
|
||||
timeline(steps.map((step) => ({ ...step, completed: false, date: undefined }))),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Expediente TEA', () => {
|
||||
@@ -192,6 +240,23 @@ describe('Expediente TEA', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('dibuja la línea del tiempo como un Gantt con rombos, no como tabla', () => {
|
||||
const [section] = recordSections(record, new Map());
|
||||
expect(section.title).toBe('Línea del tiempo');
|
||||
expect(section.blocks).toHaveLength(1);
|
||||
expect(section.blocks[0].table).toBeUndefined();
|
||||
expect(section.blocks[0].chart?.title).toBe('Etapas del tamizaje');
|
||||
expect(section.blocks[0].chart?.figure.data.at(-1)).toMatchObject({
|
||||
mode: 'markers',
|
||||
x: ['2025-11-01', '2025-11-22'],
|
||||
});
|
||||
const pending = recordSections(
|
||||
{ ...record, steps: steps.map((step) => ({ ...step, completed: false, date: undefined })) },
|
||||
new Map(),
|
||||
)[0];
|
||||
expect(pending.blocks).toEqual([]);
|
||||
});
|
||||
|
||||
it('agrupa los ítems del módulo con dominio, subdominio, código y título', () => {
|
||||
const section = recordSections(record, new Map()).find((s) => s.title === 'ADOS-2');
|
||||
expect(section?.blocks).toHaveLength(1);
|
||||
@@ -278,3 +343,26 @@ describe('Análisis de riesgo TEA', () => {
|
||||
expect(chosen?.blocks[0].chart?.title).toBe(pair.title);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Títulos de las asociaciones TEA', () => {
|
||||
it('nombra la métrica, la zona y el resultado del par', () => {
|
||||
expect(pairTitle('spindles|central|CSS')).toBe('Husos N2 · Central · CSS');
|
||||
expect(pairTitle('posterior_rhythm|posterior|CSS')).toBe('Ritmo posterior · Posterior · CSS');
|
||||
});
|
||||
|
||||
it('resuelve el ítem del ADOS-2 con la evaluación del paciente', () => {
|
||||
expect(pairTitle('spikes|frontal_midline|ados2_item_02', ados)).toBe(
|
||||
'Puntas paroxísticas · Frontal medial · Señalar',
|
||||
);
|
||||
expect(pairTitle('spikes|frontal_midline|ados2_item_02')).toBe(
|
||||
'Puntas paroxísticas · Frontal medial · ados2_item_02',
|
||||
);
|
||||
});
|
||||
|
||||
it('conserva los códigos que no conoce', () => {
|
||||
expect(zoneLabel('frontal_midline')).toBe('Frontal medial');
|
||||
expect(zoneLabel('central')).toBe('Central');
|
||||
expect(zoneLabel('unknown')).toBe('unknown');
|
||||
expect(pairTitle('unknown|unknown|CSS')).toBe('unknown · unknown · CSS');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import { downloadPdf, safeName, type PdfContent } from '../export';
|
||||
import type { Figure } from '../plot';
|
||||
import plotly from '../plotly-bundle';
|
||||
import { adosItems, adosSummary, alteration, Pair, percent, shown, TeaPatient } from './tea-data';
|
||||
import { forest, headMap, probabilityCurve, zBars } from './tea-figures';
|
||||
import { forest, headMap, probabilityCurve, timeline, zBars } from './tea-figures';
|
||||
|
||||
type Table = { headers: string[]; rows: string[][] };
|
||||
type Chart = { title: string; figure: Figure; height?: number };
|
||||
@@ -34,17 +34,13 @@ function associationRows(pairs: Pair[]): string[][] {
|
||||
}
|
||||
|
||||
export function recordSections(patient: TeaPatient, norms: ReadonlyMap<string, Chart>): Section[] {
|
||||
const gantt = timeline(patient.steps);
|
||||
return [
|
||||
{
|
||||
title: 'Línea del tiempo',
|
||||
blocks: [
|
||||
{
|
||||
table: {
|
||||
headers: ['Fecha', 'Evento', 'Detalle'],
|
||||
rows: patient.timeline,
|
||||
},
|
||||
},
|
||||
],
|
||||
blocks: gantt
|
||||
? [{ chart: { title: 'Etapas del tamizaje', figure: gantt, height: 260 } }]
|
||||
: [],
|
||||
},
|
||||
{
|
||||
title: 'ADOS-2',
|
||||
|
||||
Reference in New Issue
Block a user