From c4920ed7eb89092c3ab07c8a5503a3361a96c801 Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 1 Dec 2026 11:33:06 -0600 Subject: [PATCH] F1b: user fixes Use the existing Plotly card and registered Sankey trace. Build transition totals from the remaining stages and omit zero-flow links. Build the prevalence donut from the report counts, with a grey slice for missing sex and controls to highlight each recorded sex. Use grouped bars for M23 and separate age and sex stacks for M24. Use the existing stacked history style for M31 and put the M30 figure behind one page flag. Cover the builders and the existing TEA page case. --- e2e/pages.spec.ts | 26 ++- src/app/indicadores/figures.ts | 247 +++++++++++++++++++-- src/app/indicadores/measures.ts | 2 + src/app/indicadores/pages.ts | 70 +++--- src/app/indicadores/tab-indicadores.html | 35 ++- src/app/indicadores/tab-indicadores.ts | 20 +- src/app/indicadores/tea-indicators.spec.ts | 108 ++++++++- 7 files changed, 451 insertions(+), 57 deletions(-) diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index 780cc4a..b2b67dc 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -10,11 +10,25 @@ test('tea indicators: every tab loads, and the follow-up list exports to Excel', ); await page.goto('/indicadores/tea'); const measures = (await (await listed).json()).entry.length; + expect(measures).toBe(11); await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible(); - await expect(page.locator('app-tab-indicadores [data-measure]').first()).toBeVisible(); + const indicators = page.locator('app-tab-indicadores'); + await expect(indicators.locator('[data-measure]')).toHaveCount(10); + await expect(indicators.locator('[data-figure="sankey"] .sankey')).toBeVisible(); + await expect(indicators.locator('[data-figure="sex-donut"] .pielayer')).toBeVisible(); + await expect( + indicators.getByRole('heading', { name: 'Porcentaje de EEG normal y anormal' }), + ).toHaveCount(0); await page.getByRole('tab', { name: 'Trazabilidad' }).click(); - await expect(page.getByText('Progresión del proceso diagnóstico')).toBeVisible(); + const history = page.locator('app-tab-trazabilidad'); + await expect(history.locator('[data-measure]')).toHaveCount(11); + await expect( + history.getByRole('heading', { name: 'Prevalencia registrada de TEA' }), + ).toBeVisible(); + await expect( + history.getByRole('heading', { name: 'Porcentaje de EEG normal y anormal' }), + ).toBeVisible(); await expect(page.locator('app-tab-trazabilidad app-plot').first()).toBeVisible(); await page.getByRole('tab', { name: 'Seguimiento' }).click(); @@ -40,7 +54,13 @@ test('tea indicators: every tab loads, and the follow-up list exports to Excel', 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); + const definitions = page.locator('app-tab-definiciones'); + await expect(definitions.locator('details')).toHaveCount(measures); + await expect( + definitions.getByText('Porcentaje de EEG normal y anormal', { exact: true }), + ).toBeVisible(); + await definitions.getByText('Prevalencia registrada de TEA', { exact: true }).click(); + await expect(definitions.getByText(/Every child loaded on the platform/)).toBeVisible(); expect(problems).toEqual([]); }); diff --git a/src/app/indicadores/figures.ts b/src/app/indicadores/figures.ts index e56b4d3..d57db07 100644 --- a/src/app/indicadores/figures.ts +++ b/src/app/indicadores/figures.ts @@ -349,29 +349,37 @@ function ages(r: Reading): [string, Record][] { ); } -export function ageStack(r: Reading, names: [string, string]): Figure { - const rows = ages(r); - const x = rows.map(([a]) => ageLabel(a)); +export function ageStack( + r: Reading, + names: [string, string], + stratum: 'age_group' | 'sex' = 'age_group', +): Figure { + const rows = stratum === 'sex' ? Object.entries(r.strata['sex'] ?? {}) : ages(r); + const x = rows.map(([value]) => (stratum === 'sex' ? name(value) : ageLabel(value))); + const numerators = rows.map(([, c]) => c['numerator'] ?? 0); + const denominators = rows.map(([, c]) => c['denominator'] ?? 0); + const colors = rows.map( + ([code]) => TEA_SEXES.find((sex) => sex.code === code)?.color ?? '#C9CDD2', + ); return { - data: [ - { - type: 'bar', - name: names[0], - x, - y: rows.map(([, c]) => c['numerator'] ?? 0), - marker: { color: AGE_COLORS[0] }, - }, - { - type: 'bar', - name: names[1], - x, - y: rows.map(([, c]) => (c['denominator'] ?? 0) - (c['numerator'] ?? 0)), - marker: { color: AGE_COLORS[1] }, - }, - ] as Partial[], + data: [numerators, denominators.map((n, i) => n - numerators[i])].map((y, i) => ({ + type: 'bar', + name: names[i], + x, + y, + marker: + stratum === 'sex' + ? { color: colors, pattern: { shape: i ? '/' : '' } } + : { color: AGE_COLORS[i] }, + text: y.map((n, j) => + denominators[j] ? `${n} (${percent((100 * n) / denominators[j])} %)` : '', + ), + textposition: 'inside', + hovertemplate: '%{x}
%{fullData.name}: %{y} pacientes', + })) as Partial[], layout: { barmode: 'stack', - xaxis: { title: { text: 'Grupo de edad' }, type: 'category' }, + xaxis: { title: { text: stratum === 'sex' ? 'Sexo' : 'Grupo de edad' }, type: 'category' }, yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero' }, }, }; @@ -458,3 +466,202 @@ export function historyFigure( layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días'), }; } + +const TEA_SEXES = [ + { code: 'female', color: ROSE }, + { code: 'male', color: '#4269C2' }, + { code: 'no_data', color: '#C9CDD2' }, +]; + +export function sexCountBars(r: Reading, catalog: Catalog, axis: string, period: string): Figure { + const base = countBars(r, catalog, axis, period); + const cells = r.strata['sex-category'] ?? {}; + return { + data: TEA_SEXES.map(({ code }, i) => ({ + ...base.data[0], + name: name(code), + marker: { + color: catalog.categories.map((c) => c.color), + pattern: { shape: ['', '/', '\\'][i] }, + }, + x: catalog.categories.map((c) => cells[`${code}|${c.code}`]?.['initial-population'] ?? 0), + })) as Partial[], + layout: { ...base.layout, barmode: 'group', showlegend: true }, + }; +} + +export function teaSankey(r: Reading): Figure { + const [mchat, psychology, neuro, eeg] = [ + 'mchat_only', + 'psychology', + 'neuropediatrics', + 'eeg', + ].map((code) => counted(r, code)); + const labels = [ + 'M-CHAT', + 'Evaluación psicológica', + 'Evaluación neuropediátrica', + 'EEG de buena calidad', + 'Se quedó en M-CHAT', + 'Se quedó en evaluación psicológica', + 'Se quedó en evaluación neuropediátrica', + ]; + const colors = ['#B8433A', '#D0B778', '#7184A2', OLIVE, '#888888', '#888888', '#888888']; + const links = [ + { source: 0, target: 1, value: psychology + neuro + eeg }, + { source: 0, target: 4, value: mchat }, + { source: 1, target: 2, value: neuro + eeg }, + { source: 1, target: 5, value: psychology }, + { source: 2, target: 3, value: eeg }, + { source: 2, target: 6, value: neuro }, + ].filter(({ value }) => value > 0); + const hovertemplate = '%{label}
%{value} pacientes'; + return { + data: [ + { + type: 'sankey', + arrangement: 'fixed', + node: { label: labels, color: colors, align: 'left', pad: 24, hovertemplate }, + link: { + source: links.map(({ source }) => source), + target: links.map(({ target }) => target), + value: links.map(({ value }) => value), + color: links.map(({ target }) => rgba(colors[target], 0.45)), + label: links.map(({ target }) => labels[target]), + hovertemplate, + }, + } as Partial, + ], + layout: { margin: { l: 20, r: 20, t: 24, b: 24 } }, + }; +} + +export function teaSexDonut(r: Reading, selectedSex?: string): Figure { + const confirmed = counted(r, 'confirmed'); + const total = r.populations['initial-population'] ?? 0; + const share = (part: number, whole: number) => percent(whole ? (100 * part) / whole : 0); + const slices = TEA_SEXES.slice(0, 2).flatMap(({ code, color }) => { + const sexTotal = r.strata['sex']?.[code]?.['initial-population'] ?? 0; + const cases = r.strata['sex-category']?.[`${code}|confirmed`]?.['initial-population'] ?? 0; + return [ + { + label: `${name(code)} · Diagnóstico confirmado`, + value: cases, + total: sexTotal, + color, + line: color, + code, + confirmed: true, + }, + { + label: `${name(code)} · Sin diagnóstico confirmado`, + value: sexTotal - cases, + total: sexTotal, + color: rgba(color, 0.25), + line: color, + code, + confirmed: false, + }, + ]; + }); + const unknown = total - slices.reduce((n, { value }) => n + value, 0); + if (unknown) { + const { color } = TEA_SEXES[2]; + slices.push({ + label: 'Sin sexo registrado', + value: unknown, + total: unknown, + color, + line: color, + code: 'no_data', + confirmed: false, + }); + } + const selected = slices.find((s) => s.code === selectedSex); + const centerCases = selected?.value ?? confirmed; + const centerTotal = selected?.total ?? total; + return { + data: [ + { + type: 'pie', + hole: 0.58, + sort: false, + direction: 'clockwise', + labels: slices.map((s) => s.label), + values: slices.map((s) => s.value), + marker: { + colors: slices.map((s) => (!selected || s.code === selected.code ? s.color : '#E1E3E5')), + line: { + color: slices.map((s) => (!selected || s.code === selected.code ? s.line : '#C9CDD2')), + width: 1.5, + }, + }, + text: slices.map((s) => + !total || s.value / total < 0.04 + ? '' + : s.confirmed + ? `${s.value}
${share(s.value, s.total)} %` + : String(s.value), + ), + textinfo: 'text', + textposition: 'inside', + insidetextorientation: 'horizontal', + customdata: slices.map((s) => [share(s.value, s.total), s.total]), + hovertemplate: + '%{label}
%{value} niños, %{customdata[0]} % de %{customdata[1]}', + } as Partial, + ], + layout: { + showlegend: true, + legend: { + orientation: 'h', + y: -0.12, + yanchor: 'top', + itemclick: false, + itemdoubleclick: false, + }, + margin: { l: 24, r: 24, t: 24, b: 96 }, + annotations: [ + { + x: 0.5, + y: 0.5, + xref: 'paper', + yref: 'paper', + showarrow: false, + text: `${share(centerCases, centerTotal)} %
${centerCases} de ${centerTotal} ${selected ? `(${name(selected.code).toLowerCase()})` : 'niños'}`, + font: { size: 18 }, + }, + ], + }, + }; +} + +export function teaAlterations(r: Reading): Figure { + const rows = [['', r.populations] as const, ...Object.entries(r.strata['alteration'] ?? {})]; + const customdata = rows.map(([, c]) => [c['numerator'], c['denominator']]); + const rates = customdata.map(([n, total]) => (total ? (100 * n) / total : 0)); + return { + data: [ + { + type: 'bar', + x: rows.map(([code]) => (code ? name(code) : 'Alguna alteración')), + y: rates, + marker: { color: rows.map((_, i) => PALETTE[(i + 1) % PALETTE.length]) }, + text: rates.map((rate) => `${percent(rate)} %`), + textposition: 'outside', + cliponaxis: false, + customdata, + hovertemplate: + '%{x}
%{text} (%{customdata[0]} de %{customdata[1]} niños)', + } as Partial, + ], + layout: { + xaxis: { type: 'category', title: { text: 'Alteración del EEG' } }, + yaxis: { + range: [0, 100], + ticksuffix: ' %', + title: { text: '% de niños con EEG de buena calidad' }, + }, + }, + }; +} diff --git a/src/app/indicadores/measures.ts b/src/app/indicadores/measures.ts index 3525083..643a5b7 100644 --- a/src/app/indicadores/measures.ts +++ b/src/app/indicadores/measures.ts @@ -130,6 +130,8 @@ export const PRIORITY: Record = { high: 'Alta', medium: 'Media', export const STRATA: Record = { category: 'Categoría', age_group: 'Grupo de edad', + sex: 'Sexo', + age_sex: 'Grupo de edad y sexo', follow_up_status: 'Estatus de seguimiento', result: 'Citología de alto grado', birads: 'BI-RADS de la mastografía', diff --git a/src/app/indicadores/pages.ts b/src/app/indicadores/pages.ts index a9447a8..9f6c773 100644 --- a/src/app/indicadores/pages.ts +++ b/src/app/indicadores/pages.ts @@ -31,7 +31,15 @@ export type FigureSpec = center: string; } | { kind: 'scenario-bars'; title: string; measure: string; catalog: Catalog; stratum: string } - | { kind: 'counts'; title: string; measure: string; catalog: Catalog; axis: string } + | { + kind: 'counts'; + title: string; + measure: string; + catalog: Catalog; + axis: string; + bySex?: boolean; + } + | { kind: 'sankey' | 'sex-donut' | 'alterations'; title: string; measure: string } | { kind: 'age-stack' | 'age-share'; title: string; @@ -61,6 +69,8 @@ export interface Catalog { faded?: string[]; } +const TEA_ALTERATIONS_VALIDADAS = false; + const OLIVE = '#A8C243'; const ROSE = '#C24269'; @@ -150,6 +160,7 @@ export const PAGES: Record = { kind: 'counts', title: 'Pacientes evaluados por resultado diagnóstico', measure: 'M23_PACIENTES_EVALUADOS', + bySex: true, axis: 'Conteo (paciente)', catalog: { groups: [], @@ -178,29 +189,9 @@ export const PAGES: Record = { names: ['% de pacientes sin EEG', ''], }, { - kind: 'counts', + kind: 'sankey', title: 'Casos por estatus', measure: 'M28_CASOS_POR_ESTADO', - axis: 'Conteo (paciente)', - catalog: { - groups: [], - categories: [ - { code: 'mchat_only', label: 'Solo M-CHAT', color: '#B8433A', group: '' }, - { - code: 'psychology', - label: 'Hasta evaluación psicológica', - color: '#42C29C', - group: '', - }, - { - code: 'neuropediatrics', - label: 'Hasta evaluación neuropediátrica', - color: '#7184A2', - group: '', - }, - { code: 'eeg', label: 'Con EEG', color: OLIVE, group: '' }, - ], - }, }, { kind: 'counts', @@ -216,6 +207,20 @@ export const PAGES: Record = { ], }, }, + { + kind: 'sex-donut', + title: 'Prevalencia registrada de TEA', + measure: 'M31_PREVALENCIA', + }, + ...(TEA_ALTERATIONS_VALIDADAS + ? ([ + { + kind: 'alterations', + title: 'Porcentaje de EEG normal y anormal', + measure: 'M30_RESULTADO_EEG', + }, + ] satisfies FigureSpec[]) + : []), ], }, ], @@ -569,10 +574,15 @@ export const HISTORY: Record = { measure: 'M25_DIAS_MCHAT_DIAGNOSTICO', kind: 'median', }, - stack('Progresión del proceso diagnóstico', 'M23_PACIENTES_EVALUADOS', 'Pacientes', [ - ['confirmed', 'Diagnóstico confirmado', '#A8C243'], - ['in_process', 'En proceso', '#B8433A'], - ]), + stack( + 'Pacientes evaluados por resultado diagnóstico', + 'M23_PACIENTES_EVALUADOS', + 'Pacientes', + [ + ['confirmed', 'Diagnóstico confirmado', '#A8C243'], + ['in_process', 'En proceso', '#B8433A'], + ], + ), { title: 'Porcentaje de confirmación diagnóstica', measure: 'M24_CONFIRMACION_DIAGNOSTICO', @@ -588,7 +598,7 @@ export const HISTORY: Record = { measure: 'M22_DIAGNOSTICADOS_SIN_EEG', kind: 'percent', }, - stack('Flujo del proceso diagnóstico y estudios de EEG', 'M28_CASOS_POR_ESTADO', 'Casos', [ + stack('Casos por estatus', 'M28_CASOS_POR_ESTADO', 'Casos', [ ['mchat_only', 'Solo M-CHAT', '#B8433A'], ['psychology', 'Hasta evaluación psicológica', '#42C29C'], ['neuropediatrics', 'Hasta evaluación neuropediátrica', '#7184A2'], @@ -600,10 +610,14 @@ export const HISTORY: Record = { ['not_analyzed', 'Sin analizar', GREY], ]), { - title: 'Porcentaje de EEG con alteraciones', + title: 'Porcentaje de EEG normal y anormal', 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], + ]), ], }, }; diff --git a/src/app/indicadores/tab-indicadores.html b/src/app/indicadores/tab-indicadores.html index c9edae8..89a1606 100644 --- a/src/app/indicadores/tab-indicadores.html +++ b/src/app/indicadores/tab-indicadores.html @@ -128,14 +128,45 @@ @case ('grid') {
@for (f of section.figures; track f.title) { - +

{{ f.title }}

Filtro general aplicado: {{ period }}

+ @if (f.kind === 'counts' && f.bySex) { + + Sin estratificar + Por sexo + + } + @if (f.kind === 'sex-donut') { + + Ambos sexos + Femenino + Masculino + + } @if (reports.isLoading()) { } @else if (figureOf(f); as fig) { - + + @if (f.kind === 'age-stack') { + @if (figureOf(f, 'sex'); as bySexFigure) { + + } + } } @else {
Sin datos publicados
} diff --git a/src/app/indicadores/tab-indicadores.ts b/src/app/indicadores/tab-indicadores.ts index 973fa57..928fa74 100644 --- a/src/app/indicadores/tab-indicadores.ts +++ b/src/app/indicadores/tab-indicadores.ts @@ -18,6 +18,10 @@ import { routeFigure, scenarioBars, shareDonut, + sexCountBars, + teaAlterations, + teaSankey, + teaSexDonut, } from './figures'; import { FigureSpec, Kpi, PAGES, Section } from './pages'; import { name, periods, PeriodType, reading, Reading } from './measures'; @@ -45,6 +49,8 @@ export class TabIndicadores { protected readonly type = signal('semester'); protected readonly options = computed(() => periods(this.type())); protected readonly chosen = signal(undefined); + protected readonly bySex = signal(false); + protected readonly prevalenceSex = signal(undefined); protected readonly applied = signal(undefined); protected readonly page = computed(() => PAGES[this.domain()]); @@ -173,7 +179,7 @@ export class TabIndicadores { const steps = section.steps.map((s) => ({ label: s.label, r: this.rd(s.measure) })); return steps.some((s) => s.r?.score !== undefined) ? routeFigure(steps) : undefined; } - protected figureOf(spec: FigureSpec): Figure | undefined { + protected figureOf(spec: FigureSpec, stratum?: 'sex'): Figure | undefined { const r = this.rd(spec.measure); if (!r || !(r.populations['initial-population'] ?? 0)) return undefined; switch (spec.kind) { @@ -182,9 +188,17 @@ export class TabIndicadores { case 'share-donut': return shareDonut(r, spec.catalog, spec.center); case 'counts': - return countBars(r, spec.catalog, spec.axis, this.applied() ?? ''); + return spec.bySex && this.bySex() + ? sexCountBars(r, spec.catalog, spec.axis, this.applied() ?? '') + : countBars(r, spec.catalog, spec.axis, this.applied() ?? ''); + case 'sankey': + return teaSankey(r); + case 'sex-donut': + return teaSexDonut(r, this.prevalenceSex()); + case 'alterations': + return teaAlterations(r); case 'age-stack': - return ageStack(r, spec.names); + return ageStack(r, spec.names, stratum); case 'age-share': return ageShare(r, spec.names[0]); case 'scenario-bars': diff --git a/src/app/indicadores/tea-indicators.spec.ts b/src/app/indicadores/tea-indicators.spec.ts index 0f6994d..f8b9d1a 100644 --- a/src/app/indicadores/tea-indicators.spec.ts +++ b/src/app/indicadores/tea-indicators.spec.ts @@ -1,6 +1,14 @@ import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; import { EXT } from '../fhir'; -import { nestedDonut, shareDonut } from './figures'; +import { + ageStack, + nestedDonut, + sexCountBars, + shareDonut, + teaAlterations, + teaSankey, + teaSexDonut, +} from './figures'; import type { Catalog } from './pages'; import { ageMonths, @@ -255,3 +263,101 @@ describe('TEA indicators', () => { }); }); }); + +describe('TEA clinical figures', () => { + it('conserves children at each stage and omits empty stops', () => { + const figure = teaSankey({ + populations: { 'initial-population': 9 }, + strata: { + category: { + mchat_only: { 'initial-population': 2 }, + neuropediatrics: { 'initial-population': 3 }, + eeg: { 'initial-population': 4 }, + }, + }, + }); + expect(figure.data[0]).toMatchObject({ + type: 'sankey', + link: { source: [0, 0, 1, 2, 2], target: [1, 4, 2, 3, 6], value: [7, 2, 7, 4, 3] }, + }); + }); + + it('splits prevalence by sex and diagnosis and includes children without a recorded sex', () => { + const r = { + populations: { 'initial-population': 7 }, + strata: { + category: { confirmed: { 'initial-population': 3 } }, + sex: { female: { 'initial-population': 3 }, male: { 'initial-population': 3 } }, + 'sex-category': { + 'female|confirmed': { 'initial-population': 2 }, + 'male|confirmed': { 'initial-population': 1 }, + }, + }, + }; + const figure = teaSexDonut(r); + expect(figure.data[0]).toMatchObject({ type: 'pie', values: [2, 1, 1, 2, 1] }); + expect(figure.layout?.annotations?.[0].text).toContain('3 de 7 niños'); + expect(teaSexDonut(r, 'female').layout?.annotations?.[0].text).toContain('2 de 3 (femenino)'); + }); + + it('uses crossed counts for diagnostic results and sex totals for confirmation', () => { + const catalog: Catalog = { + groups: [], + categories: [ + { code: 'confirmed', label: 'Confirmados', color: '#A8C243', group: '' }, + { code: 'in_process', label: 'En proceso', color: '#B8433A', group: '' }, + ], + }; + const result = sexCountBars( + { + populations: {}, + strata: { + 'sex-category': { + 'female|confirmed': { 'initial-population': 2 }, + 'female|in_process': { 'initial-population': 1 }, + 'male|in_process': { 'initial-population': 3 }, + }, + }, + }, + catalog, + 'Pacientes', + '2025-S1', + ); + expect(result.data).toMatchObject([ + { name: 'Femenino', x: [2, 1] }, + { name: 'Masculino', x: [0, 3] }, + { name: 'Sin dato', x: [0, 0] }, + ]); + + const confirmation = ageStack( + { + populations: {}, + strata: { + sex: { female: { numerator: 2, denominator: 3 }, male: { numerator: 0, denominator: 3 } }, + }, + }, + ['Confirmados', 'En proceso'], + 'sex', + ); + expect(confirmation.data).toMatchObject([ + { x: ['Femenino', 'Masculino'], y: [2, 0] }, + { x: ['Femenino', 'Masculino'], y: [1, 3] }, + ]); + }); + + it('includes the total and independent alteration rates', () => { + const figure = teaAlterations({ + populations: { numerator: 3, denominator: 4 }, + strata: { + alteration: { + posterior_rhythm: { numerator: 2, denominator: 4 }, + spindles_n2: { numerator: 2, denominator: 4 }, + }, + }, + }); + expect(figure.data[0]).toMatchObject({ + x: ['Alguna alteración', 'Ritmo posterior', 'Husos N2'], + y: [75, 50, 50], + }); + }); +});