diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index 28bbc0e..0b6ef5a 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -22,6 +22,11 @@ test('tea indicators: every tab loads, and the follow-up list exports to Excel', await expect( indicators.locator('[data-measure="M23_PACIENTES_EVALUADOS"] mat-button-toggle-group'), ).toHaveCount(0); + await expect( + indicators + .locator('[data-measure="M23_PACIENTES_EVALUADOS"]') + .getByRole('heading', { name: 'Pacientes en tamizaje por resultado diagnóstico' }), + ).toBeVisible(); await expect( indicators.getByRole('heading', { name: 'Porcentaje de EEG normal y anormal' }), ).toHaveCount(0); diff --git a/src/app/indicadores/figures.ts b/src/app/indicadores/figures.ts index 4f577ef..0ff5e8a 100644 --- a/src/app/indicadores/figures.ts +++ b/src/app/indicadores/figures.ts @@ -272,6 +272,17 @@ export function fill(template: string, r: Reading): string { export function boxFigure(r: Reading, period: string): Figure { const q1 = r.low ?? r.score!; const q3 = r.high ?? r.score!; + const label = (text: string, y: number, yanchor: 'top' | 'middle' | 'bottom') => ({ + x: period, + y, + text: `${text} ${decimal(y)}`, + xref: 'x' as const, + yref: 'y' as const, + xanchor: 'left' as const, + yanchor, + xshift: 56, + showarrow: false, + }); return { data: [ { @@ -285,11 +296,16 @@ export function boxFigure(r: Reading, period: string): Figure { upperfence: [q3], marker: { color: '#4269C2' }, fillcolor: 'rgba(66,105,194,0.55)', - hovertemplate: `Q1 ${decimal(q1)} · mediana ${decimal(r.score!)} · Q3 ${decimal(q3)} días`, + hoverinfo: 'skip', } as Partial, ], layout: { showlegend: false, + annotations: [ + label('Q3', q3, 'bottom'), + label('Mediana', r.score!, 'middle'), + label('Q1', q1, 'top'), + ], yaxis: { title: { text: 'días' }, rangemode: 'tozero', ...valueAxis([q1, r.score!, q3]) }, }, }; @@ -418,19 +434,26 @@ export function ageShare(r: Reading, axis: string): Figure { const bands = ageBands(cells); const x = bands.map(ageLabel); return { - data: TEA_SEXES.map(({ code, color }) => ({ - type: 'bar', - name: name(code), - x, - y: bands.map((band) => { - const row = cells[`${band}|${code}`]; - return row?.['denominator'] ? (100 * (row['numerator'] ?? 0)) / row['denominator'] : null; - }), - marker: { color }, - texttemplate: '%{y:.1~f} %', - textposition: 'outside', - hovertemplate: '%{x}: %{y:.1~f} %%{fullData.name}', - })), + data: TEA_SEXES.map(({ code, color }) => { + const rows = bands.map((band) => cells[`${band}|${code}`]); + const shares = rows.map((row) => + row?.['denominator'] ? (100 * (row['numerator'] ?? 0)) / row['denominator'] : null, + ); + return { + type: 'bar', + name: name(code), + x, + y: shares, + marker: { color }, + text: shares.map((share, i) => + share === null + ? '' + : `${percent(share)} % (${rows[i]['numerator'] ?? 0}/${rows[i]['denominator']})`, + ), + textposition: 'outside', + hovertemplate: '%{x}: %{text}%{fullData.name}', + }; + }), layout: { barmode: 'group', xaxis: { title: { text: 'Grupo de edad' }, type: 'category' }, @@ -507,6 +530,31 @@ export function historyFigure( layout: { ...layout(panel.axis ?? 'Pacientes', [0, ...totals]), barmode: 'stack' }, }; } + if (panel.kind === 'rate') { + const lines = [ + { name: 'Total', color: line, at: (r?: Reading) => r?.score }, + ...TEA_SEXES.map(({ code, color }) => ({ + name: name(code), + color, + at: (r?: Reading) => r?.rates?.['sex']?.[code], + })), + ]; + const data = lines.map(({ name: label, color, at }) => ({ + x, + y: series.map((s) => at(s.r) ?? null), + mode: 'lines+markers' as const, + name: label, + line: { color }, + marker: { color }, + })); + return { + data, + layout: layout( + panel.axis ?? '', + data.flatMap((d) => d.y), + ), + }; + } const k = panel.kind === 'percent' ? 100 : 1; const at = (v?: number) => (v === undefined ? null : v * k); const band = [ @@ -594,7 +642,7 @@ export function teaSankey(r: Reading): Figure { type: 'sankey', arrangement: 'fixed', node: { - label: shown.map((index) => nodes[index].label), + label: shown.map((index) => `${nodes[index].label} · ${count(nodes[index].value)}`), color: shown.map((index) => nodes[index].color), pad: 36, hovertemplate, @@ -613,46 +661,63 @@ export function teaSankey(r: Reading): Figure { }; } +const RATE_UNIT = 'por 10 000 niños'; +const perTenThousand = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 1 }); + +function prevalenceCounts(r: Reading, sex?: string): { confirmed: number; total: number } { + if (!sex) { + return { confirmed: counted(r, 'confirmed'), total: r.populations['initial-population'] ?? 0 }; + } + return { + confirmed: r.strata['sex-category']?.[`${sex}|confirmed`]?.['initial-population'] ?? 0, + total: r.strata['sex']?.[sex]?.['initial-population'] ?? 0, + }; +} + +export function prevalenceHeadline(r: Reading, sex?: string) { + const found = sex ? r.rates?.['sex']?.[sex] : r.score; + if (found === undefined) return undefined; + const { confirmed, total } = prevalenceCounts(r, sex); + return { + value: perTenThousand(found), + detail: `${RATE_UNIT} · ${count(confirmed)} confirmados de ${count(total)} niños`, + }; +} + export function teaSexBars(r: Reading, selectedSex?: string): Figure { - const cells = r.strata['sex-category'] ?? {}; const x = TEA_SEXES.map(({ code }) => name(code)); + const y = TEA_SEXES.map(({ code }) => r.rates?.['sex']?.[code] ?? 0); return { data: [ - { code: 'confirmed', label: 'Diagnóstico confirmado' }, - { code: 'in_population', label: 'Sin diagnóstico confirmado' }, - ].map(({ code: category, label }, i) => { - const y = TEA_SEXES.map( - ({ code }) => cells[`${code}|${category}`]?.['initial-population'] ?? 0, - ); - return { + { type: 'bar', - name: label, + name: 'Prevalencia registrada', x, y, marker: { - color: TEA_SEXES.map(({ color }) => (i ? rgba(color, 0.25) : color)), + color: TEA_SEXES.map(({ color }) => color), line: { - color: TEA_SEXES.map(({ color }) => color), + color: '#000000', width: TEA_SEXES.map(({ code }) => (code === selectedSex ? 2 : 0)), }, }, - customdata: TEA_SEXES.map(({ code }, j) => { - const total = r.strata['sex']?.[code]?.['initial-population'] ?? 0; - return [percent(total ? (100 * y[j]) / total : 0), total]; + text: y.map((value) => perTenThousand(value)), + textposition: 'outside', + cliponaxis: false, + customdata: TEA_SEXES.map(({ code }) => { + const { confirmed, total } = prevalenceCounts(r, code); + return [confirmed, total]; }), - hovertemplate: - '%{x} · %{fullData.name}
%{y:d} niños, %{customdata[0]} % de %{customdata[1]}', - }; - }), + hovertemplate: `%{x}
%{text} ${RATE_UNIT}
%{customdata[0]} confirmados de %{customdata[1]} niños`, + }, + ], layout: { - barmode: 'group', + showlegend: false, xaxis: { title: { text: 'Sexo' }, type: 'category' }, yaxis: { - title: { text: 'Niños' }, + title: { text: 'Casos por 10 000 niños' }, rangemode: 'tozero', - ...valueAxis( - TEA_SEXES.map(({ code }) => r.strata['sex']?.[code]?.['initial-population'] ?? 0), - ), + ...valueAxis(y), }, }, }; diff --git a/src/app/indicadores/measures.ts b/src/app/indicadores/measures.ts index 643a5b7..37ef0d1 100644 --- a/src/app/indicadores/measures.ts +++ b/src/app/indicadores/measures.ts @@ -42,6 +42,7 @@ export interface Reading { high?: number; unit?: string; strata: Record>>; + rates?: Record>; } function counts(group: { @@ -57,8 +58,15 @@ export function reading(report: MeasureReport | undefined): Reading | undefined if (!group) return undefined; const score = group.measureScore; const strata: Reading['strata'] = {}; + const rates: Record> = {}; for (const s of group.stratifier ?? []) { const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-'); + const scored = (s.stratum ?? []).filter((x) => x.measureScore?.value !== undefined); + if (scored.length) { + rates[name] = Object.fromEntries( + scored.map((x) => [x.value?.text ?? '', x.measureScore!.value!]), + ); + } strata[name] = Object.fromEntries( (s.stratum ?? []).map((x) => [ x.component?.length @@ -75,6 +83,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal, unit: score?.unit, strata, + ...(Object.keys(rates).length ? { rates } : {}), }; } diff --git a/src/app/indicadores/pages.ts b/src/app/indicadores/pages.ts index a123de8..993c873 100644 --- a/src/app/indicadores/pages.ts +++ b/src/app/indicadores/pages.ts @@ -157,7 +157,7 @@ export const PAGES: Record = { figures: [ { kind: 'sex-counts', - title: 'Pacientes evaluados por resultado diagnóstico', + title: 'Pacientes en tamizaje por resultado diagnóstico', measure: 'M23_PACIENTES_EVALUADOS', axis: 'Conteo (paciente)', catalog: { @@ -416,7 +416,7 @@ export const PAGES: Record = { export interface HistoryPanel { title: string; measure: string; - kind: 'stack' | 'percent' | 'median'; + kind: 'stack' | 'percent' | 'median' | 'rate'; series?: { code: string; label: string; color: string }[]; axis?: string; group?: string; @@ -573,7 +573,7 @@ export const HISTORY: Record = { kind: 'median', }, stack( - 'Pacientes evaluados por resultado diagnóstico', + 'Pacientes en tamizaje por resultado diagnóstico', 'M23_PACIENTES_EVALUADOS', 'Pacientes', [ @@ -612,10 +612,12 @@ export const HISTORY: Record = { measure: 'M30_RESULTADO_EEG', kind: 'percent', }, - stack('Prevalencia registrada de TEA', 'M31_PREVALENCIA', 'Niños', [ - ['confirmed', 'Diagnóstico confirmado', OLIVE], - ['in_population', 'Sin diagnóstico confirmado', GREY], - ]), + { + title: 'Prevalencia registrada de TEA', + measure: 'M31_PREVALENCIA', + kind: 'rate', + axis: 'Casos por 10 000 niños', + }, ], }, }; diff --git a/src/app/indicadores/tab-indicadores.html b/src/app/indicadores/tab-indicadores.html index 19440fe..2e7c19e 100644 --- a/src/app/indicadores/tab-indicadores.html +++ b/src/app/indicadores/tab-indicadores.html @@ -101,16 +101,16 @@

Resumen

- Al cierre del periodo {{ period }}, se evaluaron + Al cierre del periodo {{ period }}, se registraron en el tamizaje {{ t.evaluated }} niños entre 16 y 36 meses; {{ t.mchatOnly }} únicamente tienen M-CHAT, {{ t.psychology }} hasta la evaluación psicológica y {{ t.neuropediatrics }} presentan evaluación neuropediátrica. En este periodo el {{ t.confirmed }} de los pacientes tiene diagnóstico - confirmado de TEA (CIE-10 F84.0). Las ventanas de tiempo* de tamizaje - son: {{ t.toAdos }} de M-CHAT (psicología) a ADOS-2, - {{ t.toDiagnosis }} de ADOS-2 a diagnóstico. El tiempo* de - tamizaje completo de M-CHAT a diagnóstico fue de {{ t.whole }}. + confirmado de TEA (CIE-10 F84.0). La mediana de la ventana de tiempo de tamizaje de + M-CHAT (psicología) a ADOS-2 es {{ t.toAdos }} y la mediana de ADOS-2 a + diagnóstico es {{ t.toDiagnosis }}. La mediana del tiempo de tamizaje + completo de M-CHAT a diagnóstico fue de {{ t.whole }}.

De los {{ t.diagnosed }} niños con diagnóstico confirmado en este @@ -118,7 +118,6 @@ {{ t.missing }} por realizarlo. {{ t.unusable }} estudios de EEG no son aceptables para un análisis.

-

*tomando la mediana de los tiempos

} @else if (reports.isLoading()) { @@ -147,6 +146,12 @@ Femenino Masculino + @if (prevalenceOf(f); as p) { +
+ {{ p.value }} + {{ p.detail }} +
+ } } @if (reports.isLoading()) { diff --git a/src/app/indicadores/tab-indicadores.ts b/src/app/indicadores/tab-indicadores.ts index 296fbac..f7dec71 100644 --- a/src/app/indicadores/tab-indicadores.ts +++ b/src/app/indicadores/tab-indicadores.ts @@ -14,6 +14,7 @@ import { countBars, fill, nestedDonut, + prevalenceHeadline, rateDots, routeFigure, scenarioBars, @@ -137,6 +138,10 @@ export class TabIndicadores { const r = measure ? this.rd(measure) : undefined; return r && r.score !== undefined ? boxFigure(r, this.applied() ?? '') : undefined; } + protected prevalenceOf(spec: FigureSpec) { + const r = this.rd(spec.measure); + return r ? prevalenceHeadline(r, this.prevalenceSex()) : undefined; + } protected readonly teaSummary = computed(() => { const rd = (c: string) => this.loaded()?.get(c); const status = rd('M28_CASOS_POR_ESTADO'); diff --git a/src/app/indicadores/tea-indicators.spec.ts b/src/app/indicadores/tea-indicators.spec.ts index ca44285..1455707 100644 --- a/src/app/indicadores/tea-indicators.spec.ts +++ b/src/app/indicadores/tea-indicators.spec.ts @@ -4,14 +4,17 @@ import { teaSteps } from '../paciente/tea-data'; import { ageShare, ageStack, + boxFigure, historyFigure, nestedDonut, + prevalenceHeadline, sexCountBars, shareDonut, teaAlterations, teaSankey, teaSexBars, } from './figures'; +import { reading } from './measures'; import type { Catalog } from './pages'; import { ageMonths, @@ -369,35 +372,145 @@ describe('TEA clinical figures', () => { }); }); - it('groups prevalence bars by sex and uses transparency for unconfirmed diagnoses', () => { - const figure = teaSexBars({ - populations: { 'initial-population': 7 }, + it('carries the count in every node label, including the stops', () => { + const figure = teaSankey({ + populations: { 'initial-population': 18 }, strata: { - sex: { female: { 'initial-population': 3 }, male: { 'initial-population': 3 } }, - 'sex-category': { - 'female|confirmed': { 'initial-population': 2 }, - 'female|in_population': { 'initial-population': 1 }, - 'male|confirmed': { 'initial-population': 1 }, - 'male|in_population': { 'initial-population': 2 }, - 'no_data|in_population': { 'initial-population': 1 }, + category: { + mchat_only: { 'initial-population': 6 }, + psychology: { 'initial-population': 2 }, + neuropediatrics: { 'initial-population': 5 }, + eeg: { 'initial-population': 5 }, }, }, }); - expect(figure.layout?.barmode).toBe('group'); - expect(figure.data).toMatchObject([ - { - type: 'bar', - x: ['Masculino', 'Femenino'], - y: [1, 2], - marker: { color: ['#4269C2', '#C24269'] }, - }, - { - type: 'bar', - x: ['Masculino', 'Femenino'], - y: [2, 1], - marker: { color: ['rgba(66,105,194,0.25)', 'rgba(194,66,105,0.25)'] }, + expect(figure.data[0]).toMatchObject({ + node: { + label: [ + 'M-CHAT · 18', + 'Evaluación
psicológica · 12', + 'Evaluación
neuropediátrica · 10', + 'EEG de
buena calidad · 5', + 'Se quedó en evaluación
neuropediátrica · 5', + 'Se quedó en evaluación
psicológica · 2', + 'Se quedó en M-CHAT · 6', + ], }, + }); + }); + + it('annotates only the median and the quartiles on the box', () => { + const figure = boxFigure({ populations: {}, score: 12.5, low: 8, high: 20 }, '2025-S1'); + expect(figure.layout?.annotations?.map((a) => a.text)).toEqual([ + 'Q3 20', + 'Mediana 12.5', + 'Q1 8', ]); + expect(figure.data[0]).toMatchObject({ hoverinfo: 'skip' }); + }); + + const prevalence = { + populations: { 'initial-population': 12 }, + score: 3333.3333, + unit: 'por 10 000', + strata: { + category: { confirmed: { 'initial-population': 4 } }, + sex: { + female: { 'initial-population': 4 }, + male: { 'initial-population': 6 }, + no_data: { 'initial-population': 2 }, + }, + 'sex-category': { + 'female|confirmed': { 'initial-population': 1 }, + 'female|in_population': { 'initial-population': 3 }, + 'male|confirmed': { 'initial-population': 3 }, + 'male|in_population': { 'initial-population': 3 }, + 'no_data|in_population': { 'initial-population': 2 }, + }, + }, + rates: { sex: { female: 2500, male: 5000, no_data: 0 } }, + }; + + it('shows the prevalence rate per 10,000 as the bar text and the counts in the hover', () => { + const figure = teaSexBars(prevalence, 'female'); + expect(figure.layout?.barmode).toBeUndefined(); + expect(figure.data).toHaveLength(1); + expect(figure.data[0]).toMatchObject({ + type: 'bar', + x: ['Masculino', 'Femenino'], + y: [5000, 2500], + text: ['5,000', '2,500'], + customdata: [ + [3, 6], + [1, 4], + ], + marker: { color: ['#4269C2', '#C24269'], line: { width: [0, 2] } }, + }); + expect(figure.data[0]).toMatchObject({ + hovertemplate: expect.stringContaining( + '%{customdata[0]} confirmados de %{customdata[1]} niños', + ), + }); + }); + + it('puts the total or the chosen sex rate in the headline', () => { + expect(prevalenceHeadline(prevalence)).toEqual({ + value: '3,333.3', + detail: 'por 10 000 niños · 4 confirmados de 12 niños', + }); + expect(prevalenceHeadline(prevalence, 'male')).toEqual({ + value: '5,000', + detail: 'por 10 000 niños · 3 confirmados de 6 niños', + }); + expect(prevalenceHeadline({ populations: {}, strata: {} })).toBeUndefined(); + }); + + it('reads the rate of each stratum from the report', () => { + const r = reading({ + resourceType: 'MeasureReport', + status: 'complete', + type: 'summary', + measure: 'M31', + period: { start: '2025-01-01', end: '2025-06-30' }, + group: [ + { + measureScore: { value: 3333.3, unit: 'por 10 000' }, + stratifier: [ + { + code: [{ coding: [{ code: 'sex' }] }], + stratum: [ + { value: { text: 'male' }, measureScore: { value: 5000 } }, + { value: { text: 'female' }, measureScore: { value: 2500 } }, + ], + }, + { + code: [{ coding: [{ code: 'category' }] }], + stratum: [{ value: { text: 'confirmed' } }], + }, + ], + }, + ], + }); + expect(r).toMatchObject({ score: 3333.3, unit: 'por 10 000' }); + expect(r?.rates).toEqual({ sex: { male: 5000, female: 2500 } }); + }); + + it('plots the prevalence rate over time as one line per sex and one for the total', () => { + const figure = historyFigure( + { title: 'Prevalencia', measure: 'M31', kind: 'rate', axis: 'Casos por 10 000 niños' }, + [ + { label: 'Ene', r: prevalence }, + { label: 'Feb', r: undefined }, + ], + '#9C42C2', + 'Mes', + ); + expect(figure.data).toMatchObject([ + { name: 'Total', y: [3333.3333, null], mode: 'lines+markers' }, + { name: 'Masculino', y: [5000, null] }, + { name: 'Femenino', y: [2500, null] }, + ]); + expect(figure.layout?.yaxis?.title).toMatchObject({ text: 'Casos por 10 000 niños' }); }); it('groups diagnostic results by sex using crossed counts', () => { @@ -474,8 +587,20 @@ describe('TEA clinical figures', () => { const figure = ageShare(byAgeAndSex, '% de pacientes con EEG'); expect(figure.layout?.barmode).toBe('group'); expect(figure.data).toMatchObject([ - { name: 'Masculino', x: ageGroups, y: [25, 100], marker: { color: '#4269C2' } }, - { name: 'Femenino', x: ageGroups, y: [50, null], marker: { color: '#C24269' } }, + { + name: 'Masculino', + x: ageGroups, + y: [25, 100], + text: ['25 % (1/4)', '100 % (1/1)'], + marker: { color: '#4269C2' }, + }, + { + name: 'Femenino', + x: ageGroups, + y: [50, null], + text: ['50 % (1/2)', ''], + marker: { color: '#C24269' }, + }, ]); });