diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index da8f927..5bbe1c2 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -42,7 +42,7 @@ test('tea indicators: every tab loads, and the follow-up list exports to Excel', await expect(page.locator('app-tab-trazabilidad app-plot').first()).toBeVisible(); await page.getByRole('tab', { name: 'Seguimiento' }).click(); - const rows = page.locator('app-tab-seguimiento table tbody tr'); + const rows = page.locator('app-tab-seguimiento-tea table tbody tr'); await expect(rows.first().locator('td').first()).toHaveText(/^N-?\d{4}$/); const name = await downloaded( page, @@ -52,8 +52,16 @@ test('tea indicators: every tab loads, and the follow-up list exports to Excel', expect(name).toMatch(/^tea-seguimiento-/); await page.getByRole('tab', { name: 'Análisis de riesgo' }).click(); - await expect(page.locator('app-tab-riesgos app-tea-list')).toBeVisible(); - await expect(page.getByText('Cargando pacientes…')).toHaveCount(0); + const risk = page.locator('app-tab-riesgos-tea'); + await expect( + risk.getByRole('heading', { name: 'EEG de los pacientes del periodo' }), + ).toBeVisible(); + await expect(risk.locator('table.worklist tbody tr').first().locator('td').first()).toHaveText( + /^N-?\d{4}$/, + ); + await risk.getByRole('combobox', { name: 'Modelo de asociación' }).click(); + await page.getByRole('option', { name: 'Con resultados' }).click(); + await expect(risk.getByText('No hay registros para los filtros aplicados.')).toBeVisible(); await page.getByRole('tab', { name: 'Datos y definiciones' }).click(); await expect(page.locator('app-tab-definiciones details')).toHaveCount(measures); @@ -64,9 +72,9 @@ test('tea patient: the record and the risk page load and export to PDF', async ( const problems = watch(page); await page.goto('/indicadores/tea'); await page.getByRole('tab', { name: 'Seguimiento' }).click(); - const first = page.locator('app-tab-seguimiento table tbody tr').first(); + const first = page.locator('app-tab-seguimiento-tea table tbody tr').first(); await expect(first.locator('td').first()).toHaveText(/^N-?\d{4}$/); - await first.getByRole('link', { name: 'Expediente' }).click(); + await first.getByRole('link').click(); await expect(page).toHaveURL(/\/indicadores\/tea\/pacientes\/[^/]+$/); await expect(page.getByRole('heading', { level: 1 })).toBeVisible(); @@ -74,7 +82,20 @@ test('tea patient: the record and the risk page load and export to PDF', async ( const record = await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf'); expect(record).toMatch(/^tea-seguimiento-/); - await page.getByRole('link', { name: 'Riesgo' }).click(); + await page.getByRole('link', { name: 'Regresar a Seguimiento' }).click(); + const focused = page.locator('app-tab-seguimiento-tea'); + await expect(focused.getByRole('button', { name: 'Ver todos los pacientes' })).toBeVisible(); + const focusedRows = focused.locator('table tbody tr'); + await expect(focusedRows).toHaveCount(1); + await expect(focusedRows.first().locator('td').nth(4)).toHaveText( + /M-CHAT|Psicología|Neuropediatría|EEG/, + ); + await expect(focusedRows.first().locator('td').nth(5)).toHaveText( + /Diagnóstico confirmado|En proceso|Sin TEA/, + ); + await focusedRows.first().getByRole('link').click(); + + await page.getByRole('link', { name: 'Análisis de riesgo' }).click(); await expect(page.getByRole('heading', { name: 'Análisis de riesgo TEA' })).toBeVisible(); await expect(page.locator('app-tea-section').first()).toBeVisible(); expect(await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf')).toMatch( diff --git a/src/app/indicadores/follow-up.ts b/src/app/indicadores/follow-up.ts index 2d1d58f..435be37 100644 --- a/src/app/indicadores/follow-up.ts +++ b/src/app/indicadores/follow-up.ts @@ -1,6 +1,5 @@ import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; -import { ados2Component, ados2Groups } from '../ados2'; -import { code, ext, label, resources } from '../fhir'; +import { code, ext, resources } from '../fhir'; /** One row of the follow-up list: what the list shows of a patient at the cut-off. */ export interface Row { @@ -207,142 +206,3 @@ 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; - -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 = 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( - 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: [ - ...new Set( - (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]), - groups: ados2Groups(evaluation), - }, - 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/tab-riesgos-tea.html b/src/app/indicadores/tab-riesgos-tea.html new file mode 100644 index 0000000..c3cd8c0 --- /dev/null +++ b/src/app/indicadores/tab-riesgos-tea.html @@ -0,0 +1,239 @@ +
+ + + Fecha de corte + + + + Ventana de meses + + @for (months of [1, 3, 6, 12]; track months) { + {{ months }} {{ months === 1 ? 'mes' : 'meses' }} + } + + + @for (filter of tokenFilters; track filter.key) { + + {{ filter.label }} + + Todos + @for (option of filter.options; track option.code) { + {{ option.label }} + } + + + } + @for (filter of scoreFilters; track filter.label) { + + {{ filter.label }} mínimo + + + + {{ filter.label }} máximo + + + } + + Inicio + + + + Modelo de asociación + + @for (option of associationOptions; track option) { + {{ associationLabels[option] }} + } + + + + Registros por página + + @for (n of [20, 50, 100]; track n) { + {{ n }} + } + + +
+ +@if (cutoff()) { +

Ventana consultada: {{ start() }} al {{ cutoff() }}.

+} + +@if (summary(); as eeg) { +
+

EEG de los pacientes del periodo

+
+ {{ eeg.normal }} Normales + {{ eeg.abnormal }} Anormales + {{ eeg.notValid }} Sin EEG válido +
+ @if (eeg.alterations.length) { +
    + @for (alteration of eeg.alterations; track alteration.code) { +
  • {{ name(alteration.code) }}: {{ alteration.patients }}
  • + } +
+ } +
+} @else if (summaryError()) { +

No se pudo leer el resumen de EEG.

+} + +
+ +
+ +@if (actionError()) { +

{{ actionError() }}

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

No se pudieron leer los pacientes.

+} @else if (loading()) { + +} + +@if (!loading() && !error()) { +
+ + + + + + + + + + + + @for (row of rows(); track row.patient.id) { + @let id = row.patient.id!; + + + + + + + @if (expanded()[id] && row.pairs.length) { + + + + } + } @empty { + + + + } + +
+ Resultados de asociación por paciente +
ExpedienteNombreParesAcciones
{{ row.recordNumbers.join(', ') || '—' }} + + {{ row.name || '—' }} + + {{ row.pairs.length || '—' }} +
+ @if (row.pairs.length) { + + } + Riesgo +
+
+ + + + + + + + + + + + + @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' + }} +
+
No hay registros para los filtros aplicados.
+
+ + +} diff --git a/src/app/indicadores/tab-riesgos-tea.scss b/src/app/indicadores/tab-riesgos-tea.scss new file mode 100644 index 0000000..9258d38 --- /dev/null +++ b/src/app/indicadores/tab-riesgos-tea.scss @@ -0,0 +1,27 @@ +.eeg-summary { + margin-bottom: var(--space-4); +} + +.eeg-summary h3 { + margin-top: 0; +} + +.counts, +.by-alteration { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); +} + +.by-alteration { + padding: 0; + margin-bottom: 0; + list-style: none; +} + +.row-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-3); +} diff --git a/src/app/indicadores/tab-riesgos-tea.ts b/src/app/indicadores/tab-riesgos-tea.ts new file mode 100644 index 0000000..6ae84dc --- /dev/null +++ b/src/app/indicadores/tab-riesgos-tea.ts @@ -0,0 +1,150 @@ +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'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatSelectModule } from '@angular/material/select'; +import { RouterLink } from '@angular/router'; +import type { Parameters } from 'fhir/r4'; +import { firstValueFrom } from 'rxjs'; +import { ApiConfiguration } from '../api/api-configuration'; +import { Fhir } from '../fhir'; +import { Loading } from '../loading'; +import { windowStart } from './follow-up'; +import { name } from './measures'; +import { PatientSearch } from './patient-search'; +import { + ASSOCIATION_LABELS, + associationRows, + DEFAULT_ASSOCIATION_FILTER, + exportTea, + fetchTeaRows, + matchesTeaSearch, + parameters, + SCORE_FILTERS, + teaParams, + TOKEN_FILTERS, + type AssociationFilter, + type TeaFilters, +} from './tea-rows'; + +@Component({ + selector: 'app-tab-riesgos-tea', + imports: [ + DecimalPipe, + FormsModule, + Loading, + MatButtonModule, + MatFormFieldModule, + MatInputModule, + MatSelectModule, + PatientSearch, + RouterLink, + ], + templateUrl: './tab-riesgos-tea.html', + styleUrls: ['./tab-seguimiento-tea.scss', './tab-riesgos-tea.scss'], +}) +export class TabRiesgosTea { + private readonly fhir = inject(Fhir); + private readonly http = inject(HttpClient); + private readonly root = inject(ApiConfiguration).rootUrl; + + protected readonly filters = signal({ window: 3 }); + protected readonly tokenFilters = TOKEN_FILTERS; + protected readonly scoreFilters = SCORE_FILTERS; + protected readonly name = name; + protected readonly search = signal(''); + protected readonly association = signal(DEFAULT_ASSOCIATION_FILTER); + protected readonly associationLabels = ASSOCIATION_LABELS; + protected readonly associationOptions = ['all', 'with', 'without'] as const; + protected readonly size = signal(20); + protected readonly index = signal(0); + protected readonly expanded = signal>({}); + protected readonly exporting = signal(false); + protected readonly actionError = signal(''); + + private readonly serverFilters = computed(() => teaParams(this.filters())); + private readonly results = resource({ + params: () => this.serverFilters(), + loader: ({ params, abortSignal }) => fetchTeaRows(this.fhir, params, abortSignal), + }); + private readonly summaryResult = resource({ + params: () => + Object.fromEntries( + Object.entries(this.serverFilters()).filter(([, value]) => value !== undefined), + ) as Record, + loader: ({ params }) => + firstValueFrom( + this.http.get(`${this.root}/tea/fhir/Patient/$eeg-summary`, { params }), + ), + }); + protected readonly summary = computed(() => { + if (!this.summaryResult.hasValue()) return undefined; + const entries = this.summaryResult.value().parameter ?? []; + const count = (key: string) => entries.find((entry) => entry.name === key)?.valueInteger ?? 0; + return { + normal: count('normal'), + abnormal: count('abnormal'), + notValid: count('not_valid'), + alterations: entries + .filter((entry) => entry.name === 'by_alteration') + .map(({ part }) => ({ + code: part?.find((entry) => entry.name === 'alteration')?.valueCode ?? '', + patients: part?.find((entry) => entry.name === 'patients')?.valueInteger ?? 0, + })), + }; + }); + protected readonly summaryError = this.summaryResult.error; + protected readonly loading = this.results.isLoading; + protected readonly error = this.results.error; + private readonly applied = computed(() => + parameters(this.results.hasValue() ? this.results.value().first : undefined), + ); + protected readonly cutoff = computed(() => this.applied()['follow-up-cutoff'] ?? ''); + protected readonly start = computed( + () => + this.filters().start || + (this.cutoff() ? windowStart(this.cutoff(), this.filters().window ?? 3) : ''), + ); + protected readonly filtered = computed(() => + associationRows(this.results.hasValue() ? this.results.value().rows : [], this.association()) + .filter((row) => matchesTeaSearch(row, this.search())), + ); + protected readonly rows = computed(() => + this.filtered().slice(this.index() * this.size(), (this.index() + 1) * this.size()), + ); + protected readonly pageCount = computed(() => + Math.max(1, Math.ceil(this.filtered().length / this.size())), + ); + + protected setFilter(key: K, value: TeaFilters[K]): void { + this.index.set(0); + this.filters.update((filters) => ({ ...filters, [key]: value })); + } + + protected toggle(id: string): void { + this.expanded.update((open) => ({ ...open, [id]: !open[id] })); + } + + protected async export(): Promise { + this.exporting.set(true); + this.actionError.set(''); + try { + await exportTea( + this.filtered(), + { + ...this.applied(), + ...(this.search() ? { Búsqueda: this.search() } : {}), + 'Modelo de asociación': ASSOCIATION_LABELS[this.association()], + }, + true, + ); + } catch { + this.actionError.set('No se pudo exportar el archivo.'); + } finally { + this.exporting.set(false); + } + } +} diff --git a/src/app/indicadores/tab-riesgos.html b/src/app/indicadores/tab-riesgos.html index 94613c8..9500b4d 100644 --- a/src/app/indicadores/tab-riesgos.html +++ b/src/app/indicadores/tab-riesgos.html @@ -1,5 +1,5 @@ @if (domain() === 'tea') { - + } @else {
diff --git a/src/app/indicadores/tab-riesgos.ts b/src/app/indicadores/tab-riesgos.ts index 06fad46..9fbaaf0 100644 --- a/src/app/indicadores/tab-riesgos.ts +++ b/src/app/indicadores/tab-riesgos.ts @@ -10,7 +10,7 @@ import type { Bundle } from 'fhir/r4'; import { Fhir } from '../fhir'; import { Row, rows, windowStart } from './follow-up'; import { PatientSearch, patientSearch } from './patient-search'; -import { TeaList } from './tea-list'; +import { TabRiesgosTea } from './tab-riesgos-tea'; import { Loading } from '../loading'; import { name } from './measures'; @@ -30,7 +30,7 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'] MatInputModule, MatSelectModule, RouterLink, - TeaList, + TabRiesgosTea, ], templateUrl: './tab-riesgos.html', styleUrl: './tab-riesgos.scss', diff --git a/src/app/indicadores/tab-seguimiento-tea.html b/src/app/indicadores/tab-seguimiento-tea.html new file mode 100644 index 0000000..3e2ab01 --- /dev/null +++ b/src/app/indicadores/tab-seguimiento-tea.html @@ -0,0 +1,169 @@ +@if (focused(); as id) { + +} @else { +
+ + + Fecha de corte + + + + Ventana de meses + + @for (months of [1, 3, 6, 12]; track months) { + + {{ months }} {{ months === 1 ? 'mes' : 'meses' }} + + } + + + @for (filter of tokenFilters; track filter.key) { + + {{ filter.label }} + + Todos + @for (option of filter.options; track option.code) { + {{ option.label }} + } + + + } + @for (filter of scoreFilters; track filter.label) { + + {{ filter.label }} mínimo + + + + {{ filter.label }} máximo + + + } + + Registros por página + + @for (n of [20, 50, 100]; track n) { + {{ n }} + } + + +
+ @if (cutoff()) { +

Ventana consultada: {{ start() }} al {{ cutoff() }}.

+ } +} + +
+ +
+ +@if (actionError()) { +

{{ actionError() }}

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

No se pudieron leer los pacientes.

+} @else if (loading()) { + +} + +@if (!loading() && !error() && page()) { +
+ + + + + + + + + + + + + + + + + + @for (row of rows(); track row.patient.id) { + @let age = ageMonths(row.patient.birthDate, cutoff()); + + + + + + + + + + + + + } @empty { + + + + } + +
+ Seguimiento de pacientes +
ExpedienteNombreSexoEdadEtapasEstado del casoM-CHATCSSEEGConcordancia
{{ row.recordNumbers.join(', ') || '—' }} + + {{ row.name || '—' }} + + {{ row.patient.gender ? name(row.patient.gender) : '—' }}{{ age == null ? '—' : age + ' meses' }}{{ row.step ?? '—' }}{{ row.case ? name(row.case) : '—' }}{{ row.mchatScore ?? '—' }}{{ row.css ?? '—' }}{{ eegDisplay(row.eegResult) }}{{ row.concordance }}
+ @if (focused()) { + Este paciente no está en la lista de seguimiento + } @else { + No hay registros para los filtros aplicados. + } +
+
+ + @if (!focused()) { + + } +} diff --git a/src/app/indicadores/tab-seguimiento-tea.scss b/src/app/indicadores/tab-seguimiento-tea.scss new file mode 100644 index 0000000..7234c53 --- /dev/null +++ b/src/app/indicadores/tab-seguimiento-tea.scss @@ -0,0 +1,46 @@ +:host { + display: block; + padding-top: var(--space-4); +} + +.filters, +.actions, +.pager { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-3); +} + +.filters, +.actions { + margin-bottom: var(--space-4); +} + +.filters mat-form-field { + min-width: 14.5rem; +} + +.table-wrap { + overflow-x: auto; + padding: 0; +} + +.worklist caption { + text-align: left; + font-weight: 500; + padding: var(--space-3); +} + +a { + color: var(--color-action); +} + +.pager { + justify-content: flex-end; + margin-top: var(--space-3); +} + +.pager .muted { + margin-right: auto; +} diff --git a/src/app/indicadores/tab-seguimiento-tea.ts b/src/app/indicadores/tab-seguimiento-tea.ts new file mode 100644 index 0000000..b85d629 --- /dev/null +++ b/src/app/indicadores/tab-seguimiento-tea.ts @@ -0,0 +1,154 @@ +import { Component, computed, inject, input, resource, signal } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatSelectModule } from '@angular/material/select'; +import { RouterLink } from '@angular/router'; +import type { Bundle } from 'fhir/r4'; +import { Fhir } from '../fhir'; +import { Loading } from '../loading'; +import { windowStart } from './follow-up'; +import { name } from './measures'; +import { PatientSearch, patientSearch } from './patient-search'; +import { + ageMonths, + exportTea, + fetchTeaRows, + parameters, + SCORE_FILTERS, + teaParams, + teaPatientPage, + teaRows, + TOKEN_FILTERS, + type TeaFilters, +} from './tea-rows'; + +@Component({ + selector: 'app-tab-seguimiento-tea', + imports: [ + FormsModule, + Loading, + MatButtonModule, + MatFormFieldModule, + MatInputModule, + MatSelectModule, + PatientSearch, + RouterLink, + ], + templateUrl: './tab-seguimiento-tea.html', + styleUrl: './tab-seguimiento-tea.scss', +}) +export class TabSeguimientoTea { + private readonly fhir = inject(Fhir); + readonly patientId = input(); + + private 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.filter( + ({ 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; + + private readonly request = computed(() => { + const id = this.focused(); + return id + ? { _id: id, 'follow-up-start': '0001-01-01' } + : { ...teaParams(this.filters()), ...patientSearch(this.search()) }; + }); + private readonly first = resource({ + params: () => ({ ...this.request(), _count: this.size() }), + loader: ({ params }) => teaPatientPage(this.fhir, params), + }); + private readonly moved = signal< + { first: Bundle; page: Bundle } | undefined + >(undefined); + protected readonly page = computed(() => { + const first = this.first.hasValue() ? this.first.value() : undefined; + const moved = this.moved(); + return moved && moved.first === first ? moved.page : first; + }); + private readonly applied = computed(() => parameters(this.page())); + protected readonly cutoff = computed(() => this.applied()['follow-up-cutoff'] ?? ''); + protected readonly start = computed(() => + this.cutoff() ? windowStart(this.cutoff(), this.filters().window ?? 3) : '', + ); + protected readonly rows = computed(() => { + const page = this.page(); + return page ? teaRows(page) : []; + }); + protected readonly pageNumber = computed(() => { + const self = this.page()?.link?.find(({ relation }) => relation === 'self')?.url; + const offset = self ? Number(new URL(self).searchParams.get('_offset')) : 0; + return Math.floor(offset / this.size()) + 1; + }); + protected readonly pageCount = computed(() => + Math.max(1, Math.ceil((this.page()?.total ?? 0) / this.size())), + ); + protected readonly error = this.first.error; + protected readonly moving = signal(false); + protected readonly loading = computed(() => this.first.isLoading() || this.moving()); + 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); + } + + protected setFilter(key: K, value: TeaFilters[K]): void { + this.filters.update((filters) => ({ ...filters, [key]: value })); + } + + protected has(relation: 'next' | 'previous'): boolean { + return !!this.page()?.link?.some((link) => link.relation === relation); + } + + protected async go(relation: 'next' | 'previous'): Promise { + const first = this.first.hasValue() ? this.first.value() : undefined; + const page = this.page(); + if (!first || !page) return; + const next = this.fhir.follow('tea', page, relation); + if (!next) return; + this.moving.set(true); + this.actionError.set(''); + try { + const found = await next; + if (this.first.hasValue() && this.first.value() === first) { + this.moved.set({ first, page: found }); + } + } 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 applied = this.applied(); + const { rows } = await fetchTeaRows(this.fhir, { + ...this.request(), + 'follow-up-cutoff': applied['follow-up-cutoff'], + }); + await exportTea(rows, applied, false); + } catch { + this.actionError.set('No se pudo exportar el archivo.'); + } finally { + this.exporting.set(false); + } + } +} diff --git a/src/app/indicadores/tab-seguimiento.html b/src/app/indicadores/tab-seguimiento.html index 053cd15..7959369 100644 --- a/src/app/indicadores/tab-seguimiento.html +++ b/src/app/indicadores/tab-seguimiento.html @@ -1,5 +1,5 @@ @if (domain() === 'tea') { - + } @else { diff --git a/src/app/indicadores/tab-seguimiento.ts b/src/app/indicadores/tab-seguimiento.ts index 43362a1..12dc2b2 100644 --- a/src/app/indicadores/tab-seguimiento.ts +++ b/src/app/indicadores/tab-seguimiento.ts @@ -9,7 +9,7 @@ import type { Bundle } from 'fhir/r4'; import { Fhir } from '../fhir'; import { camaRows, windowStart } from './follow-up'; import { PatientSearch, patientSearch } from './patient-search'; -import { TeaList } from './tea-list'; +import { TabSeguimientoTea } from './tab-seguimiento-tea'; import { Loading } from '../loading'; import { name, PRIORITY } from './measures'; @@ -28,7 +28,7 @@ const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy MatInputModule, MatSelectModule, RouterLink, - TeaList, + TabSeguimientoTea, ], templateUrl: './tab-seguimiento.html', styleUrl: './tab-riesgos.scss', diff --git a/src/app/indicadores/tea-indicators.spec.ts b/src/app/indicadores/tea-indicators.spec.ts index ce1bbbd..1691c6c 100644 --- a/src/app/indicadores/tea-indicators.spec.ts +++ b/src/app/indicadores/tea-indicators.spec.ts @@ -7,9 +7,15 @@ import type { RiskAssessment, } from 'fhir/r4'; import { EXT } from '../fhir'; -import { teaRows } from './follow-up'; import { donut, type Reading } from './measures'; -import { associationRows, teaParams, teaWorkbook } from './tea-list'; +import { + ageMonths, + associationRows, + matchesTeaSearch, + teaParams, + teaRows, + teaWorkbook, +} from './tea-rows'; const measure: Measure = { resourceType: 'Measure', status: 'active' }; const r: Reading = { strata: {}, populations: {}, score: 12, low: 7, high: 18 }; @@ -21,9 +27,14 @@ function fixture(): Bundle { const patient: Patient = { resourceType: 'Patient', id: 'child', - name: [{ text: 'Ana' }], + name: [{ text: 'Ana López' }], identifier: [{ system: 'urn:isssteleon:clinic:source', value: '123' }], - extension: [{ url: EXT + 'follow-up-status', valueCoding: { code: 'finished' } }], + extension: [ + { url: EXT + 'follow-up-status', valueCoding: { code: 'finished' } }, + { url: EXT + 'tea-step', valueCode: 'eeg' }, + { url: EXT + 'tea-case', valueCode: 'confirmed' }, + { url: EXT + 'tea-eeg-result', valueCode: 'normal' }, + ], }; const ados: Observation = { resourceType: 'Observation', @@ -113,6 +124,7 @@ describe('TEA indicators', () => { expect( teaParams({ step: 'eeg', + case: 'confirmed', eeg: 'normal', model: 'no', age: '16-23', @@ -129,6 +141,7 @@ describe('TEA indicators', () => { }), ).toEqual({ 'tea-step': 'eeg', + 'tea-case': 'confirmed', 'tea-eeg-result': 'normal', 'tea-model': 'no', 'tea-age-group': '16-23', @@ -144,39 +157,22 @@ describe('TEA indicators', () => { expect(teaParams({ cssMax: 0 })['tea-css']).toEqual(['le0']); }); - it('uses earliest included dates and builds the four detail cards and headline', () => { + it('uses follow-up codes and assembles the included dates and association 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.steps.map(({ date }) => date)).toEqual([ + '2026-02-27', + '2026-03-02', + undefined, + '2026-03-04', ]); expect(row).toMatchObject({ - name: 'Ana', + name: 'Ana López', + step: 'EEG', + case: 'confirmed', + eegResult: 'normal', recordNumbers: ['123'], mchatScore: 9, - ados: { - css: 8, - groups: [ - { - domain: 'Afectación social (AS)', - subdomains: [ - { - subdomain: 'Comunicación', - items: [ - { - code: 'A-2', - title: 'Frecuencia de la vocalización espontánea dirigida a otros', - score: 1, - }, - ], - }, - ], - }, - ], - }, - eegs: [{ quality: 'Bueno', channels: 19 }], + css: 8, headline: { pair: cssPair, or: 2, q: 0.01 }, concordance: 'Concordante', }); @@ -193,11 +189,24 @@ describe('TEA indicators', () => { expect(teaRows(page)[0].concordance).toBe('No concordante'); }); - it('defaults to children with association results and supports the other two modes', () => { + it('defaults to all children and filters by association results', () => { const rows = teaRows(fixture()); - expect(associationRows(rows)).toEqual([rows[0]]); + expect(associationRows(rows)).toEqual(rows); + expect(associationRows(rows, 'with')).toEqual([rows[0]]); expect(associationRows(rows, 'without')).toEqual([rows[1]]); - expect(associationRows(rows, 'all')).toEqual(rows); + }); + + it('matches names and record numbers in the risk list', () => { + const [row] = teaRows(fixture()); + expect(matchesTeaSearch(row, 'lopez an')).toBe(true); + expect(matchesTeaSearch(row, '123')).toBe(true); + expect(matchesTeaSearch(row, '456')).toBe(false); + }); + + it('calculates completed months at the cut-off', () => { + expect(ageMonths('2024-01-15', '2026-01-14')).toBe(23); + expect(ageMonths('2024-01-15', '2026-01-15')).toBe(24); + expect(ageMonths(undefined, '2026-01-15')).toBeUndefined(); }); it('builds the follow-up workbook', () => { diff --git a/src/app/indicadores/tea-list.html b/src/app/indicadores/tea-list.html deleted file mode 100644 index dd4f73c..0000000 --- a/src/app/indicadores/tea-list.html +++ /dev/null @@ -1,326 +0,0 @@ -@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 || '—' }}
-
- @if (ados.groups.length) { - - - - - - - - - @for (group of ados.groups; track group.domain) { - - - - - @for (sub of group.subdomains; track sub.subdomain) { - - - - @for (item of sub.items; track item.code) { - - - - - - } - } - - } -
CódigoÍtemPuntaje
{{ group.domain }}
{{ sub.subdomain }}
{{ item.code }}{{ item.title }}{{ item.score ?? '—' }}
- } - } @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 deleted file mode 100644 index d90bd44..0000000 --- a/src/app/indicadores/tea-list.scss +++ /dev/null @@ -1,48 +0,0 @@ -: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 deleted file mode 100644 index 5bd82d5..0000000 --- a/src/app/indicadores/tea-list.ts +++ /dev/null @@ -1,428 +0,0 @@ -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 { safeName } from '../export/safe-name'; -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, - day = new Date(), -): { 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 }))), - }); - } - 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); - 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)!), - }; - } -} diff --git a/src/app/indicadores/tea-rows.ts b/src/app/indicadores/tea-rows.ts new file mode 100644 index 0000000..2c91ccb --- /dev/null +++ b/src/app/indicadores/tea-rows.ts @@ -0,0 +1,356 @@ +import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; +import { ados2Component } from '../ados2'; +import { safeName } from '../export/safe-name'; +import { downloadXlsx, type Sheet } from '../export/xlsx'; +import { code, ext, resources, type Fhir, type Params } from '../fhir'; +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[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 = 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( + 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 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; + return { + patient, + name: patient.name?.[0]?.text, + recordNumbers: [ + ...new Set( + (patient.identifier ?? []) + .filter((i) => i.system?.startsWith('urn:isssteleon:') && !!i.value) + .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), + 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 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, + day = new Date(), +): { 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 }))), + }); + } + 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); + 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; + } +}