import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; 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'; type Prediction = NonNullable[number]; function associationPair(p: Prediction) { const stat = (name: string) => ext(p, `association-${name}`)?.valueDecimal; return { pair: code(p.outcome), or: stat('odds-ratio'), low: stat('ci-low'), high: stat('ci-high'), q: stat('q'), probability: p.probabilityDecimal, reference: stat('reference-probability'), sameDirection: ext(p, 'association-same-direction')?.valueBoolean, headline: ext(p, 'association-headline')?.valueBoolean === true, }; } function byPatient( records: T[], ): Map { const grouped = new Map(); for (const record of records) { const subject = record.subject?.reference; const group = grouped.get(subject); if (group) group.push(record); else grouped.set(subject, [record]); } return grouped; } export function teaRows(page: Bundle) { const reports = byPatient(resources(page, 'DiagnosticReport')); const observations = byPatient(resources(page, 'Observation')); const risks = byPatient(resources(page, 'RiskAssessment')); return resources(page, 'Patient', 'match').map((patient) => { const subject = `Patient/${patient.id}`; const obs = observations.get(subject) ?? []; const ados = obs .filter((o) => code(o.code) === 'ados2') .sort((a, b) => (a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? '')); const risk = risks.get(subject)?.[0]; 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 pairs = (risk?.prediction ?? []).map((p) => { const pair = associationPair(p); return { ...pair, title: pairTitle(pair.pair ?? '', evaluation) }; }); return { patient, name: patientName(patient), recordNumbers: [ ...new Set( (patient.identifier ?? []) .filter((i) => i.system?.startsWith('urn:isssteleon:') && !!i.value) .map((i) => i.value!), ), ], eegResult: ext(patient, 'tea-eeg-result')?.valueCode, 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, }; }); } export type TeaRow = ReturnType[number]; export type TeaFilters = { step?: string; case?: string; eeg?: string; model?: string; age?: string; sex?: string; alteration?: string; mchatMin?: number | null; mchatMax?: number | null; cssMin?: number | null; cssMax?: number | null; window?: number; start?: string; cutoff?: string; status?: string; }; export function teaParams(f: TeaFilters): Params { const range = (min?: number | null, max?: number | null) => { const values = [min == null ? '' : `ge${min}`, max == null ? '' : `le${max}`].filter(Boolean); return values.length ? values : undefined; }; return { 'tea-step': f.step || undefined, 'tea-case': f.case || undefined, 'tea-eeg-result': f.eeg || undefined, 'tea-model': f.model || undefined, 'tea-age-group': f.age || undefined, 'tea-sex': f.sex || undefined, 'tea-alteration': f.alteration || undefined, 'tea-mchat': range(f.mchatMin, f.mchatMax), 'tea-css': range(f.cssMin, f.cssMax), 'follow-up-window': f.window, 'follow-up-start': f.start || undefined, 'follow-up-cutoff': f.cutoff || undefined, 'follow-up-status': f.status || undefined, }; } export type AssociationFilter = 'with' | 'without' | 'all'; export const DEFAULT_ASSOCIATION_FILTER: AssociationFilter = 'all'; export const ASSOCIATION_LABELS = { with: 'Con resultados', without: 'Sin resultados', all: 'Todos', }; export function associationRows( rows: TeaRow[], filter: AssociationFilter = DEFAULT_ASSOCIATION_FILTER, ) { return rows.filter((row) => filter === 'all' || !!row.pairs.length === (filter === 'with')); } const INCLUDES = ['Observation:subject', 'DiagnosticReport:subject', 'RiskAssessment:subject']; export const SCORE_FILTERS = [ { label: 'M-CHAT', min: 'mchatMin', max: 'mchatMax' }, { label: 'CSS', min: 'cssMin', max: 'cssMax' }, ] as const; export const TOKEN_FILTERS = [ { key: 'step', label: 'Etapa', options: TEA_STEPS }, { key: 'case', label: 'Estado del caso', options: choices('confirmed', 'in_process', 'not_confirmed'), }, { key: 'eeg', label: 'Resultado del EEG', options: [ ...choices('normal', 'abnormal', 'no_valid_eeg'), { code: 'not_scored', label: 'Sin analizar' }, ], }, { key: 'model', label: 'Con modelo', options: [ { code: 'yes', label: 'Sí' }, { code: 'no', label: 'No' }, ], }, { key: 'age', label: 'Grupo de edad (meses)', options: [...choices('16-23', '24-29', '30-36'), { code: 'no_data', label: 'Sin dato' }], }, { key: 'sex', label: 'Sexo', options: choices('female', 'male') }, { key: 'alteration', label: 'Alteración', options: choices( 'posterior_rhythm', 'spindles_n2', 'spindles_n3', 'paroxysmal_spikes', 'anteroposterior_gradient', ), }, { key: 'status', label: 'Estatus', options: [ { code: 'active', label: 'Activo' }, { code: 'finished', label: 'Finalizado' }, ], }, ] as const; 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), ...row.recordNumbers, ]); } export function parameters(page?: Bundle): Record { const self = page?.link?.find((l) => l.relation === 'self')?.url; const result: Record = {}; if (!self) return result; new URL(self).searchParams.forEach((value, key) => { if (key === '_id' || !key.startsWith('_')) { result[key] = result[key] ? `${result[key]}, ${value}` : value; } }); return result; } const columns = (entries: [string, string][]): Sheet['columns'] => entries.map(([key, header]) => ({ key, header })); 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 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 }; } export function exportTea( rows: TeaRow[], params: Record, risk: boolean, ): Promise { const { name, sheets } = teaWorkbook(rows, risk, params['follow-up-cutoff']); return downloadXlsx(name, sheets, params); } export function ageMonths(birth: string | undefined, cutoff: string): number | undefined { if (!birth || !cutoff || birth.length !== 10) return undefined; const [by, bm, bd] = birth.split('-').map(Number); const [y, m, d] = cutoff.split('-').map(Number); return Math.max(0, (y - by) * 12 + m - bm - Number(d < bd)); } export function teaPatientPage(fhir: Fhir, params: Params): Promise { return fhir.search('tea', 'Patient', { ...params, _revinclude: INCLUDES }); } export async function fetchTeaRows( fhir: Fhir, params: Params, abort?: AbortSignal, ): Promise<{ first: Bundle; rows: TeaRow[] }> { const first = await teaPatientPage(fhir, { ...params, _count: 200 }); const rows: TeaRow[] = []; let page = first; for (;;) { abort?.throwIfAborted(); rows.push(...teaRows(page)); const next = fhir.follow('tea', page, 'next'); if (!next) return { first, rows }; page = await next; } }