From adff5bac5c749501dfbbd2d002493cd51057e62f Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 30 Nov 2026 14:19:03 -0600 Subject: [PATCH] =?UTF-8?q?Indicadores=20TEA:=20Resumen,=20Trazabilidad,?= =?UTF-8?q?=20Seguimiento,=20An=C3=A1lisis=20de=20riesgo,=20periodicities?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/indicadores/follow-up.ts | 163 +++++++- src/app/indicadores/indicadores.ts | 30 +- src/app/indicadores/layout.ts | 20 +- src/app/indicadores/measures.ts | 118 +++++- src/app/indicadores/tab-definiciones.ts | 12 + src/app/indicadores/tab-indicadores.html | 128 ++++--- src/app/indicadores/tab-indicadores.ts | 60 +++ src/app/indicadores/tab-riesgos.html | 294 +++++++------- src/app/indicadores/tab-riesgos.ts | 23 +- src/app/indicadores/tab-seguimiento.html | 204 +++++----- src/app/indicadores/tab-seguimiento.ts | 20 +- src/app/indicadores/tab-trazabilidad.ts | 160 ++++++-- src/app/indicadores/tea-indicators.spec.ts | 239 ++++++++++++ src/app/indicadores/tea-list.html | 296 +++++++++++++++ src/app/indicadores/tea-list.scss | 48 +++ src/app/indicadores/tea-list.ts | 422 +++++++++++++++++++++ 16 files changed, 1876 insertions(+), 361 deletions(-) create mode 100644 src/app/indicadores/tea-indicators.spec.ts create mode 100644 src/app/indicadores/tea-list.html create mode 100644 src/app/indicadores/tea-list.scss create mode 100644 src/app/indicadores/tea-list.ts diff --git a/src/app/indicadores/follow-up.ts b/src/app/indicadores/follow-up.ts index c389271..5c7684b 100644 --- a/src/app/indicadores/follow-up.ts +++ b/src/app/indicadores/follow-up.ts @@ -1,5 +1,5 @@ import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; -import { code, ext, resources } from '../fhir'; +import { code, ext, label, resources } from '../fhir'; /** One row of the follow-up list: what the list shows of a patient at the cut-off. */ export interface Row { @@ -204,3 +204,164 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] { }; }); } + +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 ADOS2_ITEMS = [ + 'vocalization_directed', + 'pointing', + 'gestures', + 'unusual_eye_contact', + 'facial_expressions', + 'gaze_integration', + 'shared_enjoyment', + 'response_to_name', + 'ignoring', + 'requesting', + 'showing', + 'joint_attention_initiation', + 'joint_attention_response', + 'social_overtures_quality', + 'social_overtures_caregiver', + 'reciprocal_communication', + 'rapport_quality', + 'intonation', + 'stereotyped_language', + 'unusual_sensory_interest', + 'hand_finger_mannerisms', + 'repetitive_interests', +]; + +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 concordance(headline?: ReturnType, ados?: Observation): string { + if (!headline || !ados || headline.probability == null || headline.reference == null) return '—'; + const outcome = headline.pair?.split('|')[2]; + const item = ADOS2_ITEMS[Number(outcome?.match(/^ados2_item_(\d{2})$/)?.[1]) - 1]; + const score = + outcome === 'CSS' + ? ados.valueInteger + : ados.component?.find((c) => item && code(c.code) === `ados2.${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( + 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')); + const dateOrder = (a: Observation | DiagnosticReport, b: Observation | DiagnosticReport) => + (a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? ''); + return resources(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 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 status = ext(patient, 'follow-up-status')?.valueCoding?.code; + 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 explicitStep = TEA_STEPS.findIndex((s) => s.code === ext(patient, 'tea-step')?.valueCode); + const lastReached = + explicitStep >= 0 + ? explicitStep + : status === 'finished' + ? 3 + : dates.slice(0, 3).reduce((last, date, index) => (date ? index : last), -1); + return { + patient, + name: patient.name?.[0]?.text, + recordNumbers: (patient.identifier ?? []) + .filter((i) => i.system?.startsWith('urn:isssteleon:') && !!i.value) + .map((i) => i.value!), + status, + steps: TEA_STEPS.map((step, i) => ({ + ...step, + date: dates[i], + reached: i <= lastReached || (i === 0 && status === 'active'), + })), + mchatScore: mchat?.valueQuantity?.value, + ados: evaluation && { + date: evaluation.effectiveDateTime, + css: evaluation.valueInteger, + module: label( + evaluation.component?.find((c) => code(c.code) === 'ados2.module')?.valueCodeableConcept, + ), + classification: label(evaluation.interpretation?.[0]), + }, + eegs: eegs.map((e) => ({ + id: e.id, + date: e.effectiveDateTime, + quality: label(e.conclusionCode?.[0]), + validity: label(e.conclusionCode?.[1]), + duration: ext(e, 'eeg-duration-min')?.valueDecimal, + channels: ext(e, 'eeg-channels')?.valueInteger, + })), + headline, + concordance: concordance(headline, evaluation), + pairs, + }; + }); +} + +export type TeaRow = ReturnType[number]; diff --git a/src/app/indicadores/indicadores.ts b/src/app/indicadores/indicadores.ts index 368cffe..36028e8 100644 --- a/src/app/indicadores/indicadores.ts +++ b/src/app/indicadores/indicadores.ts @@ -1,4 +1,6 @@ import { Component, computed, inject, input, resource } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { ActivatedRoute } from '@angular/router'; import { MatTabsModule } from '@angular/material/tabs'; import type { Measure } from 'fhir/r4'; import { DOMAINS } from '../app'; @@ -38,8 +40,13 @@ import { TabTrazabilidad } from './tab-trazabilidad'; } @else if (!measures.value()?.length) {

Este dominio todavía no tiene indicadores publicados.

} @else { - - + + @@ -47,7 +54,18 @@ import { TabTrazabilidad } from './tab-trazabilidad'; - @if (domain() === 'cacu') { + @if (domain() === 'tea') { + + + + + + + + + + + } @else if (domain() === 'cacu') { @@ -62,7 +80,7 @@ import { TabTrazabilidad } from './tab-trazabilidad'; } - + @@ -97,6 +115,10 @@ import { TabTrazabilidad } from './tab-trazabilidad'; export class Indicadores { private readonly fhir = inject(Fhir); readonly domain = input.required(); + private readonly query = toSignal(inject(ActivatedRoute).queryParamMap); + protected readonly seguimiento = computed(() => + this.domain() === 'tea' ? (this.query()?.get('seguimiento') ?? undefined) : undefined, + ); protected readonly title = computed( () => DOMAINS[this.domain() as keyof typeof DOMAINS] ?? this.domain(), ); diff --git a/src/app/indicadores/layout.ts b/src/app/indicadores/layout.ts index 33aafc3..258fdbe 100644 --- a/src/app/indicadores/layout.ts +++ b/src/app/indicadores/layout.ts @@ -70,26 +70,16 @@ export const LAYOUTS: Record = { }, tea: { kpis: [ + 'M26_DIAS_MCHAT_ADOS2', + 'M27_DIAS_ADOS2_DIAGNOSTICO', + 'M25_DIAS_MCHAT_DIAGNOSTICO', 'M23_PACIENTES_EVALUADOS', 'M24_CONFIRMACION_DIAGNOSTICO', - 'M25_DIAS_MCHAT_DIAGNOSTICO', 'M21_DIAGNOSTICADOS_CON_EEG', + 'M22_DIAGNOSTICADOS_SIN_EEG', 'M29_CALIDAD_EEG', ], - route: [ - { - label: 'ADOS-2', - step: 'Del M-CHAT al ADOS-2', - fromSample: 'M26_DIAS_MCHAT_ADOS2', - fromStep: 'M26_DIAS_MCHAT_ADOS2', - }, - { - label: 'Valoración neuropediátrica', - step: 'Del ADOS-2 a la valoración neuropediátrica', - fromSample: 'M25_DIAS_MCHAT_DIAGNOSTICO', - fromStep: 'M27_DIAS_ADOS2_DIAGNOSTICO', - }, - ], + route: [], anchor: 'M23_PACIENTES_EVALUADOS', }, }; diff --git a/src/app/indicadores/measures.ts b/src/app/indicadores/measures.ts index 3c87e87..5aeece9 100644 --- a/src/app/indicadores/measures.ts +++ b/src/app/indicadores/measures.ts @@ -113,6 +113,16 @@ const LABELS: Record = { psychology: 'Psicología (ADOS-2)', neuropediatrics: 'Neuropediatría', eeg: 'EEG', + female: 'Femenino', + male: 'Masculino', + abnormal: 'Anormal', + not_scored: 'Sin puntuar', + no_valid_eeg: 'Sin EEG válido', + posterior_rhythm: 'Ritmo posterior', + spindles_n2: 'Husos N2', + spindles_n3: 'Husos N3', + paroxysmal_spikes: 'Puntas paroxísticas', + anteroposterior_gradient: 'Gradiente anteroposterior', good: 'Bueno', bad: 'Malo', not_analyzed: 'Sin analizar', @@ -163,7 +173,15 @@ export function detail(measure: Measure, r: Reading | undefined): string { const pct = (v?: number) => (v === undefined ? '—' : `${(v * 100).toFixed(1)} %`); /** A donut of one stratifier's counts (initial population), or of numerator vs the rest. */ -export function donut(measure: Measure, r: Reading, stratifier = 'category'): Figure { +export type Ring = { labels: string[]; values: number[] }; + +export function donut( + measure: Measure, + r: Reading, + stratifier = 'category', + inner?: Ring, + outer?: Ring, +): Figure { let labels: string[], values: number[]; if (scoring(measure) === 'proportion') { const { numerator = 0, denominator = 0 } = r.populations; @@ -178,20 +196,37 @@ export function donut(measure: Measure, r: Reading, stratifier = 'category'): Fi data: [ { type: 'pie', - hole: 0.62, - labels, - values, + hole: inner ? 0.68 : 0.62, + ...(outer ?? { labels, values }), sort: false, textinfo: 'value+percent', marker: { colors: PALETTE }, }, + ...(inner + ? [ + { + type: 'pie' as const, + hole: 0.45, + ...inner, + sort: false, + textinfo: 'percent' as const, + domain: { x: [0.17, 0.83] as [number, number], y: [0.17, 0.83] as [number, number] }, + marker: { colors: PALETTE }, + }, + ] + : []), ], layout: { showlegend: true, margin: { t: 32, r: 8, b: 32, l: 8 } }, }; } /** Bars per stratum: the rate (proportion) or the count (others). */ -export function strataBars(measure: Measure, r: Reading, stratifier: string): Figure { +export function strataBars( + measure: Measure, + r: Reading, + stratifier: string, + showCounts = false, +): Figure { const cells = Object.entries(r.strata[stratifier] ?? {}); const proportion = scoring(measure) === 'proportion'; const values = cells.map(([, c]) => @@ -208,6 +243,12 @@ export function strataBars(measure: Measure, r: Reading, stratifier: string): Fi orientation: 'h', y: cells.map(([v]) => name(v)), x: values, + ...(showCounts + ? { + text: cells.map(([, c], i) => `${c['numerator'] ?? 0} (${values[i].toFixed(1)} %)`), + hovertemplate: '%{y}: %{text}', + } + : {}), marker: { color: PALETTE[0] }, }, ], @@ -301,3 +342,70 @@ export function history( layout: { yaxis: { title: { text: kind === 'proportion' ? '%' : 'Días' } } }, }; } + +export function boxes(rows: { label: string; r: Reading | undefined }[]): Figure { + return { + data: rows.flatMap(({ label, r }) => + r?.score === undefined || r.low === undefined || r.high === undefined + ? [] + : [ + { + type: 'box' as const, + orientation: 'h' as const, + name: label, + q1: [r.low], + median: [r.score], + q3: [r.high], + lowerfence: [r.low], + upperfence: [r.high], + }, + ], + ), + layout: { xaxis: { title: { text: 'Días' } }, yaxis: { automargin: true } }, + }; +} + +export function sankey( + latest: readonly number[], + eeg: { valid: number; normal: number; abnormal: number }, +): Figure { + const [, psychology, neurology, reachedEeg] = latest.map((_, i) => + latest.slice(i).reduce((sum, count) => sum + count, 0), + ); + return { + data: [ + { + type: 'sankey', + node: { + label: [ + 'M-CHAT', + 'Psicología', + 'Neuropediatría', + 'EEG', + 'Solo M-CHAT', + 'Hasta Psicología', + 'Sin EEG válido', + 'Normal', + 'Anormal', + 'Sin puntuar', + ], + }, + link: { + source: [0, 1, 2, 0, 1, 2, 3, 3, 3], + target: [1, 2, 3, 4, 5, 6, 7, 8, 9], + value: [ + psychology, + neurology, + reachedEeg, + latest[0], + latest[1], + latest[2], + eeg.normal, + eeg.abnormal, + eeg.valid - eeg.normal - eeg.abnormal, + ], + }, + }, + ], + }; +} diff --git a/src/app/indicadores/tab-definiciones.ts b/src/app/indicadores/tab-definiciones.ts index a806cfd..52be42e 100644 --- a/src/app/indicadores/tab-definiciones.ts +++ b/src/app/indicadores/tab-definiciones.ts @@ -18,6 +18,17 @@ const PERIODS: Record = { semester: 'Semestral', month: 'Mensual @Component({ selector: 'app-tab-definiciones', template: ` + @if (domain() === 'tea') { +
+

Periodicidades

+
+ @for (m of measures(); track m.id) { +
{{ m.title }}
+
{{ types(m) || '—' }}
+ } +
+
+ } @@ -48,6 +59,7 @@ const PERIODS: Record = { semester: 'Semestral', month: 'Mensual styles: ':host { display: block; padding-top: 16px; overflow-x: auto; }', }) export class TabDefiniciones { + readonly domain = input(); readonly measures = input.required(); protected readonly scoring = SCORING; protected readonly improvement = IMPROVEMENT; diff --git a/src/app/indicadores/tab-indicadores.html b/src/app/indicadores/tab-indicadores.html index 655120c..fec6afb 100644 --- a/src/app/indicadores/tab-indicadores.html +++ b/src/app/indicadores/tab-indicadores.html @@ -40,63 +40,89 @@

Calculando…

} -@if (kpis().length) { +@if (domain() === 'tea') {

Indicadores de oportunidad

-
- @for (m of kpis(); track m.id) { - +

{{ opportunity() }}

+
+ @for (item of teaFigures(); track item.measure.id) { + -
{{ m.title }}
- + {{ item.measure.title }} + {{ score(item.measure) }} · {{ detail(item.measure) }} +
-
{{ score(m) }}
-
{{ detail(m) }}
+ @for (f of item.figures; track f.title) { +

{{ f.title }}

+ + } @empty { +

Sin datos en el periodo.

+ } +
+
+ } +
+} @else { + @if (kpis().length) { +

Indicadores de oportunidad

+
+ @for (m of kpis(); track m.id) { + + +
{{ m.title }}
+ +
+ +
{{ score(m) }}
+
{{ detail(m) }}
+
+
+ } +
+ } + + @if (layout().route.length) { + + + Ruta del tamizaje + + + {{ routeView() === 'sample' ? 'Acumulado desde la toma' : 'Por pasos' }} + + + Acumulado desde la toma + Por pasos + + + + + + + } + +

Indicadores clínicos

+
+ @for (m of clinical(); track m.id) { + + + {{ m.title }} + {{ score(m) }} · {{ detail(m) }} + + + @for (f of figureSets().get(m.name!) ?? []; track f.title) { +

{{ f.title }}

+ + } @empty { +

Sin datos en el periodo.

+ }
}
} - -@if (layout().route.length) { - - - Ruta del tamizaje - - - {{ routeView() === 'sample' ? 'Acumulado desde la toma' : 'Por pasos' }} - - - Acumulado desde la toma - Por pasos - - - - - - -} - -

Indicadores clínicos

-
- @for (m of clinical(); track m.id) { - - - {{ m.title }} - {{ score(m) }} · {{ detail(m) }} - - - @for (f of figureSets().get(m.name!) ?? []; track f.title) { -

{{ f.title }}

- - } @empty { -

Sin datos en el periodo.

- } -
-
- } -
diff --git a/src/app/indicadores/tab-indicadores.ts b/src/app/indicadores/tab-indicadores.ts index d09d7be..8fe9dba 100644 --- a/src/app/indicadores/tab-indicadores.ts +++ b/src/app/indicadores/tab-indicadores.ts @@ -10,6 +10,7 @@ import { Fhir, resources } from '../fhir'; import { Figure, Plot } from '../plot'; import { LAYOUTS } from './layout'; import { + boxes, detail, donut, formatScore, @@ -20,6 +21,7 @@ import { PeriodType, reading, Reading, + Ring, scoring, STRATA, strataBars, @@ -177,5 +179,63 @@ export class TabIndicadores { })), ]; } + protected readonly opportunity = computed(() => { + const [m26, m27, m25] = this.kpis() + .slice(0, 3) + .map((m) => { + const score = this.r(m)?.score; + return score === undefined ? '—' : this.score(m); + }); + return `La mediana del tiempo del M-CHAT al ADOS-2 fue de ${m26 ?? '—'}, del ADOS-2 a la valoración neuropediátrica de ${m27 ?? '—'} y del M-CHAT al diagnóstico positivo de ${m25 ?? '—'}.`; + }); + + protected readonly teaFigures = computed(() => + this.kpis().map((measure) => { + const r = this.r(measure); + const figures: { title: string; figure: Figure }[] = []; + if (!r || !r.populations['initial-population']) return { measure, figures }; + if (scoring(measure) === 'continuous-variable') { + const figure = boxes([{ label: measure.title ?? '', r }]); + if (figure.data.length) figures.push({ title: 'Mediana y cuartiles', figure }); + } else if (measure.name === 'M24_CONFIRMACION_DIAGNOSTICO') { + const bySex: Reading['strata'][string] = {}; + const outer: Ring = { labels: [], values: [] }; + const cells = Object.entries(r.strata['age_sex'] ?? {}).sort( + ([a], [b]) => a.split('|')[1].localeCompare(b.split('|')[1]) || a.localeCompare(b), + ); + for (const [value, counts] of cells) { + const [age, sex] = value.split('|'); + const total = (bySex[sex] ??= { denominator: 0, numerator: 0 }); + total['denominator'] += counts['denominator'] ?? 0; + total['numerator'] += counts['numerator'] ?? 0; + outer.labels.push(`${name(sex)} · ${name(age)}`); + outer.values.push(counts['denominator'] ?? 0); + } + const inner: Ring = { + labels: Object.keys(bySex).map(name), + values: Object.values(bySex).map((c) => c['denominator']), + }; + figures.push( + { title: 'Por grupo de edad', figure: strataBars(measure, r, 'age_group') }, + { + title: 'Por sexo', + figure: strataBars(measure, { ...r, strata: { sex: bySex } }, 'sex'), + }, + { + title: 'Distribución por sexo', + figure: donut(measure, r, 'category', undefined, inner), + }, + { + title: 'Distribución por sexo y grupo de edad', + figure: donut(measure, r, 'category', inner, outer), + }, + ); + } else { + figures.push({ title: 'Distribución', figure: donut(measure, r) }); + } + return { measure, figures }; + }), + ); + protected readonly name = name; } diff --git a/src/app/indicadores/tab-riesgos.html b/src/app/indicadores/tab-riesgos.html index 6caf560..8e7af83 100644 --- a/src/app/indicadores/tab-riesgos.html +++ b/src/app/indicadores/tab-riesgos.html @@ -1,149 +1,157 @@ -
- - Fecha de corte - - - - Ventana - - @for (m of [1, 3, 6, 12]; track m) { - {{ m }} {{ m === 1 ? 'mes' : 'meses' }} - } - - - - Estatus - - Todos - @for (s of statuses; track s) { - {{ name(s) }} - } - - - - Horizonte - - @for (h of [1, 2, 3, 4, 5]; track h) { - {{ h }} {{ h === 1 ? 'año' : 'años' }} - } - - - - Orden - - Estudio más reciente - Mayor riesgo de LIEAG+ - Mayor riesgo de cáncer - - - - Por página - - @for (n of [20, 50, 100]; track n) { - {{ n }} - } - - - +@if (domain() === 'tea') { + +} @else { +
+ + Fecha de corte + + + + Ventana + + @for (m of [1, 3, 6, 12]; track m) { + {{ m }} {{ m === 1 ? 'mes' : 'meses' }} + } + + + + Estatus + + Todos + @for (s of statuses; track s) { + {{ name(s) }} + } + + + + Horizonte + + @for (h of [1, 2, 3, 4, 5]; track h) { + {{ h }} {{ h === 1 ? 'año' : 'años' }} + } + + + + Orden + + Estudio más reciente + Mayor riesgo de LIEAG+ + Mayor riesgo de cáncer + + + + Por página + + @for (n of [20, 50, 100]; track n) { + {{ n }} + } + + + -@if (error()) { - -} + @if (error()) { + + } -
-
- - - - - - - - - - - - - - - @for (row of rows(); track row.patient.id) { +
+
PacienteGrupo de edadEstatusÚltima citologíaVPHBiopsiaRiesgo LIEAG+ ({{ horizon() }} a)Riesgo cáncer ({{ horizon() }} a)Días toma → diagnóstico
+ - - - - + + + + + + + + + + + + @for (row of rows(); track row.patient.id) { + + + + + + + + - - - - - - - } @empty { - - - - } - -
- {{ - row.name ?? row.patient.id!.slice(0, 10) - }} - @if (row.curp) { -
{{ row.curp }}
- } -
{{ row.ageGroup }}{{ name(row.status) }} - @if (row.cytology; as c) { - {{ c.date }} · + PacienteGrupo de edadEstatusÚltima citologíaVPHBiopsiaRiesgo LIEAG+ ({{ horizon() }} a)Riesgo cáncer ({{ horizon() }} a)Días toma → diagnóstico
+ {{ + row.name ?? row.patient.id!.slice(0, 10) + }} + @if (row.curp) { +
{{ row.curp }}
+ } +
{{ row.ageGroup }}{{ name(row.status) }} + @if (row.cytology; as c) { + {{ c.date }} · + {{ + c.result + ? name(c.result) + : c.adequacy === 'unsatisfactory' + ? 'Insatisfactoria' + : 'Pendiente' + }} + } @else { + — + } + + @if (row.hpv; as h) { + {{ h.positive ? 'Positivo' : 'Negativo' }}{{ h.types1618 ? ' (16/18)' : '' }} + } @else { + — + } + + @if (row.biopsy; as b) { + {{ b.date }} · {{ name(b.histology ?? '') || 'Sin dato' }} + } @else { + — + } + {{ - c.result - ? name(c.result) - : c.adequacy === 'unsatisfactory' - ? 'Insatisfactoria' - : 'Pendiente' + row.risk.cin2 === undefined ? '—' : (row.risk.cin2 * 100 | number: '1.1-1') + ' %' }} - } @else { - — - } - - @if (row.hpv; as h) { - {{ h.positive ? 'Positivo' : 'Negativo' }}{{ h.types1618 ? ' (16/18)' : '' }} - } @else { - — - } - - @if (row.biopsy; as b) { - {{ b.date }} · {{ name(b.histology ?? '') || 'Sin dato' }} - } @else { - — - } - - {{ row.risk.cin2 === undefined ? '—' : (row.risk.cin2 * 100 | number: '1.1-1') + ' %' }} - - {{ - row.risk.cancer === undefined ? '—' : (row.risk.cancer * 100 | number: '1.1-1') + ' %' - }} - {{ row.daysToDiagnosis ?? '—' }}
- {{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }} -
- + + + {{ + row.risk.cancer === undefined + ? '—' + : (row.risk.cancer * 100 | number: '1.1-1') + ' %' + }} + + {{ row.daysToDiagnosis ?? '—' }} + + } @empty { + + + {{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }} + + + } + + + -
- - @if (page()?.total; as total) { - {{ offset() + 1 }}–{{ offset() + rows().length }} de {{ total }} pacientes · corte - {{ applied() }} - } - - - -
+
+ + @if (page()?.total; as total) { + {{ offset() + 1 }}–{{ offset() + rows().length }} de {{ total }} pacientes · corte + {{ applied() }} + } + + + +
+} diff --git a/src/app/indicadores/tab-riesgos.ts b/src/app/indicadores/tab-riesgos.ts index 508dd23..031c56f 100644 --- a/src/app/indicadores/tab-riesgos.ts +++ b/src/app/indicadores/tab-riesgos.ts @@ -9,6 +9,7 @@ import { RouterLink } from '@angular/router'; import type { Bundle } from 'fhir/r4'; import { Fhir } from '../fhir'; import { rows, windowStart } from './follow-up'; +import { TeaList } from './tea-list'; import { name } from './measures'; const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']; @@ -25,6 +26,7 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'] MatInputModule, MatSelectModule, RouterLink, + TeaList, ], templateUrl: './tab-riesgos.html', styleUrl: './tab-riesgos.scss', @@ -46,15 +48,18 @@ export class TabRiesgos { protected readonly name = name; private readonly first = resource({ - params: () => ({ - domain: this.domain(), - 'follow-up-window': this.window(), - 'follow-up-cutoff': this.cutoff() || undefined, - 'follow-up-status': this.status() || undefined, - 'risk-horizon': this.horizon(), - _sort: this.sort(), - _count: this.size(), - }), + params: () => + this.domain() === 'tea' + ? undefined + : { + domain: this.domain(), + 'follow-up-window': this.window(), + 'follow-up-cutoff': this.cutoff() || undefined, + 'follow-up-status': this.status() || undefined, + 'risk-horizon': this.horizon(), + _sort: this.sort(), + _count: this.size(), + }, loader: ({ params: { domain, ...params } }) => { this.moved.set(undefined); return this.fhir.search(domain, 'Patient', { diff --git a/src/app/indicadores/tab-seguimiento.html b/src/app/indicadores/tab-seguimiento.html index 0873cfc..98fa02c 100644 --- a/src/app/indicadores/tab-seguimiento.html +++ b/src/app/indicadores/tab-seguimiento.html @@ -1,102 +1,106 @@ -
- - Fecha de corte - - - - Ventana - - @for (m of [1, 3, 6, 12]; track m) { - {{ m }} {{ m === 1 ? 'mes' : 'meses' }} - } - - - - Estatus - - Todos - @for (s of statuses; track s) { - {{ name(s) }} - } - - - - Por página - - @for (n of [20, 50, 100]; track n) { - {{ n }} - } - - -
+@if (domain() === 'tea') { + +} @else { +
+ + Fecha de corte + + + + Ventana + + @for (m of [1, 3, 6, 12]; track m) { + {{ m }} {{ m === 1 ? 'mes' : 'meses' }} + } + + + + Estatus + + Todos + @for (s of statuses; track s) { + {{ name(s) }} + } + + + + Por página + + @for (n of [20, 50, 100]; track n) { + {{ n }} + } + + +
-@if (error()) { - + @if (error()) { + + } + +
+ + + + + + + + + + + + + @for (row of rows(); track row.patient.id) { + + + + + + + + + } @empty { + + + + } + +
PacienteGrupo de edadMastografíaBiopsiaEstatusPrioridad
+ {{ + row.name ?? row.patient.id!.slice(0, 10) + }} + @if (row.curp) { +
{{ row.curp }}
+ } +
{{ row.ageGroup }}{{ row.mammogram.date }} · {{ name(row.mammogram.birads ?? '') || 'Sin dato' }} + @if (row.biopsy; as b) { + {{ b.date }} · {{ name(b.histology ?? '') || 'Sin resultado' }} + } @else { + — + } + {{ name(row.status) }}{{ priority(row.priority) }}
+ {{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }} +
+
+ +
+ + @if (page()?.total; as total) { + {{ offset() + 1 }}–{{ offset() + rows().length }} de {{ total }} pacientes · corte + {{ applied() }} + } + + + +
} - -
- - - - - - - - - - - - - @for (row of rows(); track row.patient.id) { - - - - - - - - - } @empty { - - - - } - -
PacienteGrupo de edadMastografíaBiopsiaEstatusPrioridad
- {{ - row.name ?? row.patient.id!.slice(0, 10) - }} - @if (row.curp) { -
{{ row.curp }}
- } -
{{ row.ageGroup }}{{ row.mammogram.date }} · {{ name(row.mammogram.birads ?? '') || 'Sin dato' }} - @if (row.biopsy; as b) { - {{ b.date }} · {{ name(b.histology ?? '') || 'Sin resultado' }} - } @else { - — - } - {{ name(row.status) }}{{ priority(row.priority) }}
- {{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }} -
-
- -
- - @if (page()?.total; as total) { - {{ offset() + 1 }}–{{ offset() + rows().length }} de {{ total }} pacientes · corte - {{ applied() }} - } - - - -
diff --git a/src/app/indicadores/tab-seguimiento.ts b/src/app/indicadores/tab-seguimiento.ts index 12ab46c..50a764b 100644 --- a/src/app/indicadores/tab-seguimiento.ts +++ b/src/app/indicadores/tab-seguimiento.ts @@ -8,6 +8,7 @@ import { RouterLink } from '@angular/router'; import type { Bundle } from 'fhir/r4'; import { Fhir } from '../fhir'; import { camaRows } from './follow-up'; +import { TeaList } from './tea-list'; import { name, PRIORITY } from './measures'; const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy']; @@ -23,6 +24,7 @@ const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy MatInputModule, MatSelectModule, RouterLink, + TeaList, ], templateUrl: './tab-seguimiento.html', styleUrl: './tab-riesgos.scss', @@ -30,6 +32,7 @@ const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy export class TabSeguimiento { private readonly fhir = inject(Fhir); readonly domain = input.required(); + readonly patientId = input(); protected readonly cutoff = signal(''); protected readonly window = signal(3); @@ -42,13 +45,16 @@ export class TabSeguimiento { protected readonly priority = (code: string) => PRIORITY[code] ?? code; private readonly first = resource({ - params: () => ({ - domain: this.domain(), - 'follow-up-window': this.window(), - 'follow-up-cutoff': this.cutoff() || undefined, - 'follow-up-status': this.status() || undefined, - _count: this.size(), - }), + params: () => + this.domain() === 'tea' + ? undefined + : { + domain: this.domain(), + 'follow-up-window': this.window(), + 'follow-up-cutoff': this.cutoff() || undefined, + 'follow-up-status': this.status() || undefined, + _count: this.size(), + }, loader: ({ params: { domain, ...params } }) => { this.moved.set(undefined); return this.fhir.search(domain, 'Patient', { diff --git a/src/app/indicadores/tab-trazabilidad.ts b/src/app/indicadores/tab-trazabilidad.ts index b4d8a39..ef433a2 100644 --- a/src/app/indicadores/tab-trazabilidad.ts +++ b/src/app/indicadores/tab-trazabilidad.ts @@ -1,39 +1,94 @@ import { Component, computed, inject, input, resource, signal } from '@angular/core'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatCardModule } from '@angular/material/card'; -import type { Measure, MeasureReport } from 'fhir/r4'; +import type { Measure, MeasureReport, Parameters } from 'fhir/r4'; import { Fhir, resources } from '../fhir'; +import { CardActions } from '../card-actions'; import { Figure, Plot } from '../plot'; -import { history, periods, PeriodType, periodTypes, reading } from './measures'; +import { TEA_STEPS } from './follow-up'; +import { + history, + periodLabel, + periods, + PeriodType, + periodTypes, + reading, + sankey, + strataBars, +} from './measures'; /** Each measure over time: every period of the chosen kind, oldest first. */ @Component({ selector: 'app-tab-trazabilidad', - imports: [MatButtonToggleModule, MatCardModule, Plot], + imports: [MatButtonToggleModule, MatCardModule, Plot, CardActions], template: ` -
- - Mensual - Semestral - -
- @if (series.isLoading()) { -

Calculando…

- } -
- @for (item of figures(); track item.measure.id) { - - {{ item.measure.title }} - - + @if (domain() === 'tea') { + @if (teaFlow.isLoading() || alterations.isLoading()) { +

Calculando…

} -
+ @if (teaFlow.error() || alterations.error()) { +

No se pudo leer la trazabilidad.

+ } +
+ @if (alterations.hasValue() && alterations.value(); as item) { + + + {{ item.measure.title }} + + + +

{{ item.period }}

+ +
+
+ } + @if (teaFlow.hasValue() && teaFlow.value(); as flow) { + + Progresión del proceso diagnóstico + +
+ @for (step of flow.steps; track step.label) { +
{{ step.label }}
+
{{ step.count }}
+ } +
+
+
+ + + Flujo del proceso diagnóstico y estudios de EEG + + + + } +
+ } @else { +
+ + Mensual + Semestral + +
+ @if (series.isLoading()) { +

Calculando…

+ } +
+ @for (item of figures(); track item.measure.id) { + + {{ item.measure.title }} + + + } +
+ } `, styles: ` :host { @@ -62,7 +117,10 @@ export class TabTrazabilidad { protected readonly type = signal('semester'); protected readonly series = resource({ - params: () => ({ domain: this.domain(), type: this.type(), measures: this.measures() }), + params: () => + this.domain() === 'tea' + ? undefined + : { domain: this.domain(), type: this.type(), measures: this.measures() }, loader: async ({ params }) => { const asked = periods(params.type).reverse(); const shown = params.measures.filter((m) => periodTypes(m).includes(params.type)); @@ -79,6 +137,56 @@ export class TabTrazabilidad { }, }); + protected readonly teaFlow = resource({ + params: () => (this.domain() === 'tea' ? this.domain() : undefined), + loader: async ({ params: domain }) => { + const [pages, response] = await Promise.all([ + Promise.all( + TEA_STEPS.map(({ code }) => + this.fhir.search(domain, 'Patient', { 'tea-step': code, _count: 1 }), + ), + ), + this.fhir.search(domain, 'Patient/$eeg-summary', { 'tea-step': 'eeg' }), + ]); + const parameters = (response as unknown as Parameters).parameter ?? []; + const count = (name: string) => parameters.find((p) => p.name === name)?.valueInteger ?? 0; + const latest = pages.map((page) => page.total ?? 0); + return { + steps: TEA_STEPS.map(({ label }, i) => ({ + label, + count: latest.slice(i).reduce((sum, n) => sum + n, 0), + })), + figure: sankey(latest, { + valid: count('valid'), + normal: count('normal'), + abnormal: count('abnormal'), + }), + }; + }, + }); + + protected readonly alterations = resource({ + params: () => + this.domain() === 'tea' + ? this.measures().find((m) => m.name === 'M30_RESULTADO_EEG') + : undefined, + loader: async ({ params: measure }) => { + const asked = periods('semester'); + const pages = await this.fhir.all('tea', 'MeasureReport', { + measure: measure.id!, + 'reporting-period': asked.join(','), + }); + const readings = resources(pages, 'MeasureReport').map(reading); + const index = readings.findIndex((r) => !!r?.populations['initial-population']); + const r = readings[index]; + return { + measure, + period: index < 0 ? 'Sin datos en el periodo' : periodLabel(asked[index]), + figure: r ? strataBars(measure, r, 'alteration', true) : { data: [] }, + }; + }, + }); + protected readonly figures = computed<{ measure: Measure; figure: Figure }[]>(() => (this.series.value() ?? []).map(({ measure, points }) => { // From the first period with data on. diff --git a/src/app/indicadores/tea-indicators.spec.ts b/src/app/indicadores/tea-indicators.spec.ts new file mode 100644 index 0000000..4b77310 --- /dev/null +++ b/src/app/indicadores/tea-indicators.spec.ts @@ -0,0 +1,239 @@ +import type { + Bundle, + DiagnosticReport, + Measure, + Observation, + Patient, + RiskAssessment, +} from 'fhir/r4'; +import { EXT } from '../fhir'; +import { teaRows } from './follow-up'; +import { boxes, donut, sankey, type Reading } from './measures'; +import { associationRows, teaParams, teaWorkbook } from './tea-list'; + +const measure: Measure = { resourceType: 'Measure', status: 'active' }; +const r: Reading = { strata: {}, populations: {}, score: 12, low: 7, high: 18 }; +const cssPair = 'spindles|central|CSS'; + +function fixture(): Bundle { + const subject = { reference: 'Patient/child' }; + const patient: Patient = { + resourceType: 'Patient', + id: 'child', + name: [{ text: 'Ana' }], + identifier: [{ system: 'urn:isssteleon:clinic:source', value: '123' }], + extension: [{ url: EXT + 'follow-up-status', valueCoding: { code: 'finished' } }], + }; + const ados: Observation = { + resourceType: 'Observation', + id: 'evaluation', + status: 'final', + code: { coding: [{ code: 'ados2' }] }, + subject, + effectiveDateTime: '2026-03-02', + valueInteger: 8, + component: [ + { code: { coding: [{ code: 'ados2.vocalization_directed' }] }, valueQuantity: { value: 1 } }, + ], + }; + const risk: RiskAssessment = { + resourceType: 'RiskAssessment', + status: 'final', + subject, + basis: [{ reference: 'Observation/evaluation' }], + prediction: [ + { + outcome: { coding: [{ code: cssPair }] }, + probabilityDecimal: 0.35, + extension: [ + { url: EXT + 'association-headline', valueBoolean: true }, + { url: EXT + 'association-reference-probability', valueDecimal: 0.35 }, + { url: EXT + 'association-odds-ratio', valueDecimal: 2 }, + { url: EXT + 'association-q', valueDecimal: 0.01 }, + ], + }, + ], + }; + const eeg: DiagnosticReport = { + resourceType: 'DiagnosticReport', + status: 'final', + code: { coding: [{ code: 'eeg' }] }, + subject, + effectiveDateTime: '2026-03-04', + conclusionCode: [{ text: 'Bueno' }], + extension: [{ url: EXT + 'eeg-channels', valueInteger: 19 }], + }; + return { + resourceType: 'Bundle', + type: 'searchset', + entry: [ + { resource: patient, search: { mode: 'match' } }, + { resource: { resourceType: 'Patient', id: 'other' }, search: { mode: 'match' } }, + { resource: ados, search: { mode: 'include' } }, + { resource: risk, search: { mode: 'include' } }, + { resource: eeg, search: { mode: 'include' } }, + ...['2026-03-01', '2026-02-27'].map((date) => ({ + search: { mode: 'include' as const }, + resource: { + resourceType: 'Observation' as const, + status: 'final' as const, + subject, + code: { coding: [{ code: 'mchat.score' }] }, + valueQuantity: { value: 9 }, + effectiveDateTime: date, + }, + })), + ], + }; +} + +describe('TEA indicators', () => { + it('uses reported quartiles and skips a measure without a distribution', () => { + expect( + boxes([ + { label: 'M26', r }, + { label: 'M27', r: undefined }, + ]).data, + ).toEqual([expect.objectContaining({ type: 'box', q1: [7], median: [12], q3: [18] })]); + }); + + it('links reached steps, departures and all three EEG outcomes', () => { + expect(sankey([10, 5, 4, 6], { valid: 6, normal: 2, abnormal: 3 }).data[0]).toMatchObject({ + node: { + label: [ + 'M-CHAT', + 'Psicología', + 'Neuropediatría', + 'EEG', + 'Solo M-CHAT', + 'Hasta Psicología', + 'Sin EEG válido', + 'Normal', + 'Anormal', + 'Sin puntuar', + ], + }, + link: { + source: [0, 1, 2, 0, 1, 2, 3, 3, 3], + target: [1, 2, 3, 4, 5, 6, 7, 8, 9], + value: [15, 10, 6, 10, 5, 4, 2, 3, 1], + }, + }); + }); + + it('builds two concentric rings from the supplied counts', () => { + const inner = { labels: ['Femenino'], values: [3] }; + const outer = { labels: ['Femenino · 16-23', 'Femenino · 24-29'], values: [2, 1] }; + expect(donut(measure, r, 'category', inner, outer).data).toEqual([ + expect.objectContaining(outer), + expect.objectContaining(inner), + ]); + expect(donut(measure, r).data).toHaveLength(1); + }); + + it('maps every search filter and encodes closed ranges as repeated ge/le values', () => { + expect( + teaParams({ + step: 'eeg', + eeg: 'normal', + model: 'no', + age: '16-23', + sex: 'female', + alteration: 'spindles_n2', + mchatMin: 0, + mchatMax: 20, + cssMin: 1, + cssMax: 7, + window: 3, + start: '2026-01-01', + cutoff: '2026-03-31', + status: 'finished', + }), + ).toEqual({ + 'tea-step': 'eeg', + 'tea-eeg-result': 'normal', + 'tea-model': 'no', + 'tea-age-group': '16-23', + 'tea-sex': 'female', + 'tea-alteration': 'spindles_n2', + 'tea-mchat': ['ge0', 'le20'], + 'tea-css': ['ge1', 'le7'], + 'follow-up-window': 3, + 'follow-up-start': '2026-01-01', + 'follow-up-cutoff': '2026-03-31', + 'follow-up-status': 'finished', + }); + expect(teaParams({ cssMax: 0 })['tea-css']).toEqual(['le0']); + }); + + it('uses earliest included dates and builds the four detail cards and headline', () => { + const [row, other] = teaRows(fixture()); + expect(row.steps.map(({ date, reached }) => [date, reached])).toEqual([ + ['2026-02-27', true], + ['2026-03-02', true], + [undefined, true], + ['2026-03-04', true], + ]); + expect(row).toMatchObject({ + name: 'Ana', + recordNumbers: ['123'], + mchatScore: 9, + ados: { css: 8 }, + eegs: [{ quality: 'Bueno', channels: 19 }], + headline: { pair: cssPair, or: 2, q: 0.01 }, + concordance: 'Concordante', + }); + expect(other.concordance).toBe('—'); + }); + + it('compares the headline item score with the prediction and reference', () => { + 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'); + }); + + it('defaults to children with association results and supports the other two modes', () => { + const rows = teaRows(fixture()); + expect(associationRows(rows)).toEqual([rows[0]]); + expect(associationRows(rows, 'without')).toEqual([rows[1]]); + expect(associationRows(rows, 'all')).toEqual(rows); + }); + + it('builds the follow-up workbook', () => { + expect(teaWorkbook(teaRows(fixture()), false)).toEqual({ + name: 'seguimiento-tea', + sheets: [ + expect.objectContaining({ + name: 'Seguimiento', + rows: expect.arrayContaining([ + expect.objectContaining({ id: 'child', pair: cssPair, eeg: '2026-03-04' }), + ]), + }), + ], + }); + }); + + it('builds the risk workbook with children and pair details', () => { + expect(teaWorkbook(associationRows(teaRows(fixture())), true)).toEqual({ + name: 'analisis-de-riesgo-tea', + sheets: [ + expect.objectContaining({ name: 'Niños' }), + expect.objectContaining({ + name: 'Pares', + rows: [ + expect.objectContaining({ + id: 'child', + pair: cssPair, + probability: 0.35, + reference: 0.35, + }), + ], + }), + ], + }); + }); +}); diff --git a/src/app/indicadores/tea-list.html b/src/app/indicadores/tea-list.html new file mode 100644 index 0000000..e7b5a3c --- /dev/null +++ b/src/app/indicadores/tea-list.html @@ -0,0 +1,296 @@ +@if (focused(); as id) { + +} @else { +
+ + @for (filter of tokenFilters; track filter.key) { + + } + + + + + + + + @if (risk()) { + + } +
+} + +
+ +
+ +@if (actionError()) { +

{{ actionError() }}

+} +@if (loading() || moving()) { +

Cargando pacientes…

+} +@if (error()) { +

No se pudieron leer los pacientes.

+} @else if (rows().length) { +
+ + + + + + @if (!risk()) { + + + } @else { + + } + + + + + @for (row of rows(); track row.patient.id) { + @let id = row.patient.id!; + + + + @if (!risk()) { + + + } @else { + + } + + + @if (isExpanded(id)) { + + + + } + } + +
ExpedienteNombreProceso diagnósticoConcordancia con el ADOS-2ParesAcciones
{{ row.recordNumbers.join(', ') || '—' }}{{ row.name || '—' }} +
    + @for (step of row.steps; track step.code) { +
  1. + } +
+
+ @if (row.headline; as headline) { + {{ headline.pair || '—' }} · OR {{ (headline.or | number: '1.0-3') ?? '—' }} · q + {{ (headline.q | number: '1.0-4') ?? '—' }} · {{ row.concordance }} + } @else { + — + } + {{ row.pairs.length }} + + Expediente + Riesgo +
+ @if (risk()) { + @if (row.pairs.length) { + + + + + + + + + + + + + @for (pair of row.pairs; track pair.pair) { + + + + + + + + + } + +
ParOR (IC)qProbabilidadReferenciaMismo sentido
{{ pair.pair || '—' }} + {{ (pair.or | number: '1.0-3') ?? '—' }} ({{ + (pair.low | number: '1.0-3') ?? '—' + }}–{{ (pair.high | number: '1.0-3') ?? '—' }}) + {{ (pair.q | number: '1.0-4') ?? '—' }}{{ (pair.probability | number: '1.0-4') ?? '—' }}{{ (pair.reference | number: '1.0-4') ?? '—' }} + {{ + pair.sameDirection == null ? '—' : pair.sameDirection ? 'Sí' : 'No' + }} +
+ } @else { +

Sin resultados de asociación.

+ } + } @else { +
+
+

Datos

+
+
Nombre
+
{{ row.name || '—' }}
+
Expediente
+
{{ row.recordNumbers.join(', ') || '—' }}
+
Sexo
+
{{ row.patient.gender ? name(row.patient.gender) : '—' }}
+
Nacimiento
+
{{ row.patient.birthDate || '—' }}
+
M-CHAT
+
{{ row.mchatScore ?? '—' }}
+
+
+
+

ADOS-2

+ @if (row.ados; as ados) { +
+
Fecha
+
{{ ados.date || '—' }}
+
Módulo
+
{{ ados.module || '—' }}
+
CSS
+
{{ ados.css ?? '—' }}
+
Clasificación
+
{{ ados.classification || '—' }}
+
+ } @else { +

—

+ } +
+
+

EEG

+ @for (eeg of row.eegs; track eeg.id) { +
+
Fecha
+
{{ eeg.date || '—' }}
+
Calidad
+
{{ eeg.quality || '—' }}
+
Validez
+
{{ eeg.validity || '—' }}
+
Duración (min)
+
{{ eeg.duration ?? '—' }}
+
Canales
+
{{ eeg.channels ?? '—' }}
+
+ } @empty { +

—

+ } +
+
+

Asociación

+ @if (row.headline; as headline) { +
+
Par
+
{{ headline.pair || '—' }}
+
OR
+
{{ (headline.or | number: '1.0-3') ?? '—' }}
+
q
+
{{ (headline.q | number: '1.0-4') ?? '—' }}
+
Concordancia con el ADOS-2
+
{{ row.concordance }}
+
+ } @else { +

—

+ } +
+
+ } +
+
+} @else if (!loading()) { +

Sin pacientes para los filtros seleccionados.

+} + +@if (has('previous') || has('next')) { + +} diff --git a/src/app/indicadores/tea-list.scss b/src/app/indicadores/tea-list.scss new file mode 100644 index 0000000..d90bd44 --- /dev/null +++ b/src/app/indicadores/tea-list.scss @@ -0,0 +1,48 @@ +:host { + display: block; + padding-top: 16px; +} +.filters, +.cards { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 12px; +} +.filters label { + display: grid; + gap: 4px; +} +.actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px; + margin-block: 12px; +} +.table-wrap { + overflow-x: auto; +} +.stepper { + display: flex; + gap: 8px; + padding: 0; + list-style: none; +} +.stepper li { + width: 12px; + height: 12px; + border: 2px solid var(--color-primary); + border-radius: 50%; +} +.stepper .reached { + background: var(--color-primary); +} +.highlighted { + background: var(--color-primary-light, #e9f0f5); +} +.cards h3 { + margin-top: 0; +} +.cards dd { + margin: 0 0 8px; +} diff --git a/src/app/indicadores/tea-list.ts b/src/app/indicadores/tea-list.ts new file mode 100644 index 0000000..d1de828 --- /dev/null +++ b/src/app/indicadores/tea-list.ts @@ -0,0 +1,422 @@ +import { DecimalPipe } from '@angular/common'; +import { Component, computed, inject, input, resource, signal } from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { FormsModule } from '@angular/forms'; +import { RouterLink } from '@angular/router'; +import type { Bundle, Patient } from 'fhir/r4'; +import { debounceTime, distinctUntilChanged, map } from 'rxjs'; +import { allRows } from '../export/fetch-all'; +import { downloadXlsx, type Sheet } from '../export/xlsx'; +import { Fhir, type Params } from '../fhir'; +import { TEA_STEPS, teaRows, type TeaRow } from './follow-up'; +import { name } from './measures'; + +export type TeaFilters = { + step?: 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-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, + }; +} + +type AssociationFilter = 'with' | 'without' | 'all'; +export const DEFAULT_ASSOCIATION_FILTER: AssociationFilter = 'with'; +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 PAGE_SIZE = 20; +const INCLUDES = ['Observation:subject', 'DiagnosticReport:subject', 'RiskAssessment:subject']; +const TOKEN_FILTERS = [ + { key: 'step', label: 'Paso', options: TEA_STEPS.map(({ code, label }) => ({ code, label })) }, + { + key: 'eeg', + label: 'Resultado del EEG', + options: choices('normal', 'abnormal', 'no_valid_eeg', 'not_scored'), + }, + { + key: 'model', + label: 'Modelo de EEG', + options: [ + { code: 'yes', label: 'Sí' }, + { code: 'no', label: 'No' }, + ], + }, + { + key: 'age', + label: 'Grupo de edad (meses)', + options: choices('16-23', '24-29', '30-36', 'no_data'), + }, + { 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) })); +} + +function normalized(value: string): string { + return value + .normalize('NFD') + .replace(/\p{Diacritic}/gu, '') + .toLocaleLowerCase('es-MX') + .trim(); +} + +function matches(row: TeaRow, query: string): boolean { + return ( + !query || + [...(row.patient.name ?? []).map((n) => n.text ?? ''), ...row.recordNumbers].some((value) => + normalized(value).includes(query), + ) + ); +} + +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): { name: string; sheets: Sheet[] } { + const identity: [string, string][] = [ + ['id', 'Paciente'], + ['record', 'Expediente'], + ['name', 'Nombre'], + ]; + 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 }))), + }); + } + return { name: risk ? 'analisis-de-riesgo-tea' : 'seguimiento-tea', sheets }; +} + +export function exportTea( + rows: TeaRow[], + params: Record, + risk: boolean, +): Promise { + const { name, sheets } = teaWorkbook(rows, risk); + return downloadXlsx(name, sheets, params); +} + +type Page = { bundle: Bundle; rows: TeaRow[] }; + +@Component({ + selector: 'app-tea-list', + imports: [DecimalPipe, FormsModule, RouterLink], + templateUrl: './tea-list.html', + styleUrl: './tea-list.scss', +}) +export class TeaList { + private readonly fhir = inject(Fhir); + readonly risk = input(false); + readonly patientId = input(); + protected readonly cleared = signal(undefined); + protected readonly focused = computed(() => + this.patientId() === this.cleared() ? undefined : this.patientId(), + ); + + protected readonly filters = signal({ window: 3 }); + protected readonly tokenFilters = TOKEN_FILTERS; + protected readonly windows = [1, 3, 6, 12]; + protected readonly association = signal(DEFAULT_ASSOCIATION_FILTER); + protected readonly associationLabels = ASSOCIATION_LABELS; + protected readonly query = signal(''); + private readonly text = toSignal( + toObservable(this.query).pipe(map(normalized), debounceTime(300), distinctUntilChanged()), + { initialValue: '' }, + ); + protected readonly name = name; + protected readonly expanded = signal>({}); + protected readonly index = signal(0); + protected readonly moving = signal(false); + protected readonly exporting = signal(false); + protected readonly actionError = signal(''); + private readonly moved = signal<{ first: Page; page: Page } | undefined>(undefined); + private readonly exhausted = signal<{ page: Page; relation: string } | undefined>(undefined); + + private readonly request = computed(() => { + const id = this.focused(); + return { + ...(id ? { _id: id } : teaParams(this.filters())), + _revinclude: INCLUDES, + _count: this.risk() ? 200 : PAGE_SIZE, + }; + }); + + private readonly results = resource({ + params: () => ({ + params: this.request(), + query: this.risk() ? '' : this.text(), + risk: this.risk(), + }), + loader: async ({ params, abortSignal }) => { + if (params.risk) { + const rows = await this.fetchRows(params.params, '', abortSignal); + return { first: rows.first, rows: rows.rows }; + } + const bundle = await this.fhir.search('tea', 'Patient', params.params); + const first = await this.scan(bundle, 'next', params.query, abortSignal); + return { first, rows: [] }; + }, + }); + protected readonly loading = this.results.isLoading; + protected readonly error = this.results.error; + private readonly data = computed(() => + this.results.hasValue() ? this.results.value() : undefined, + ); + private readonly page = computed(() => { + const first = this.data()?.first; + const moved = this.moved(); + return moved && moved.first === first ? moved.page : first; + }); + protected readonly riskRows = computed(() => + associationRows(this.data()?.rows ?? [], this.association()).filter((row) => + matches(row, this.text()), + ), + ); + protected readonly rows = computed(() => + this.risk() + ? this.riskRows().slice(this.index() * PAGE_SIZE, (this.index() + 1) * PAGE_SIZE) + : (this.page()?.rows ?? []), + ); + + protected setFilter(key: K, value: TeaFilters[K]): void { + this.index.set(0); + this.filters.update((filters) => ({ ...filters, [key]: value })); + } + + protected setQuery(value: string): void { + this.index.set(0); + this.query.set(value); + } + + protected setAssociation(value: AssociationFilter): void { + this.index.set(0); + this.association.set(value); + } + + protected isExpanded(id: string): boolean { + return this.expanded()[id] ?? id === this.focused(); + } + + protected toggle(id: string): void { + this.expanded.update((open) => ({ ...open, [id]: !this.isExpanded(id) })); + } + + protected has(relation: 'next' | 'previous'): boolean { + if (this.risk()) { + return relation === 'previous' + ? this.index() > 0 + : (this.index() + 1) * PAGE_SIZE < this.riskRows().length; + } + const page = this.page(); + const exhausted = this.exhausted(); + return ( + !!page?.bundle.link?.some((link) => link.relation === relation) && + !(exhausted?.page === page && exhausted?.relation === relation) + ); + } + + protected async go(relation: 'next' | 'previous'): Promise { + if (this.risk()) { + this.index.update((i) => i + (relation === 'next' ? 1 : -1)); + return; + } + const first = this.data()?.first; + const page = this.page(); + if (!first || !page) return; + const next = this.fhir.follow('tea', page.bundle, relation); + if (!next) return; + this.moving.set(true); + this.actionError.set(''); + try { + const found = await this.scan(await next, relation, this.text()); + if (this.data()?.first === first) { + if (found.rows.length) this.moved.set({ first, page: found }); + else this.exhausted.set({ page, relation }); + } + } catch { + this.actionError.set('No se pudo cambiar de página.'); + } finally { + this.moving.set(false); + } + } + + protected async export(): Promise { + this.exporting.set(true); + this.actionError.set(''); + try { + const risk = this.risk(); + const query = this.text(); + const first = this.data()?.first.bundle; + const applied = parameters(first); + const rows = risk + ? this.riskRows() + : ( + await this.fetchRows( + { + ...this.request(), + 'follow-up-cutoff': applied['follow-up-cutoff'], + _count: 200, + }, + query, + ) + ).rows; + await exportTea( + rows, + { + ...applied, + ...(query ? { Búsqueda: this.query() } : {}), + ...(risk ? { 'Modelo de asociación': ASSOCIATION_LABELS[this.association()] } : {}), + }, + risk, + ); + } catch { + this.actionError.set('No se pudo exportar el archivo.'); + } finally { + this.exporting.set(false); + } + } + + private async scan( + bundle: Bundle, + relation: 'next' | 'previous', + query: string, + abort?: AbortSignal, + ): Promise { + let current = bundle; + for (;;) { + abort?.throwIfAborted(); + const rows = teaRows(current).filter((row) => matches(row, query)); + if (rows.length) return { bundle: current, rows }; + const next = this.fhir.follow('tea', current, relation); + if (!next) return { bundle, rows }; + current = await next; + } + } + + private async fetchRows(params: Params, query: string, abort?: AbortSignal) { + const first = await this.fhir.search('tea', 'Patient', params); + const rows = new Map(); + let page = first; + const patients = await allRows('first', async (url) => { + abort?.throwIfAborted(); + if (url !== 'first') page = await this.fhir.follow('tea', page, 'next')!; + const matched = teaRows(page).filter((row) => matches(row, query)); + for (const row of matched) rows.set(row.patient.id, row); + return { ...page, entry: matched.map(({ patient }) => ({ resource: patient })) }; + }); + return { + first: { bundle: first, rows: [] }, + rows: patients.map((patient) => rows.get(patient.id)!), + }; + } +}