From 789145b93c25514e9f7d8593c55433a8f759bd3e Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 1 Dec 2026 13:36:44 -0600 Subject: [PATCH] F1f: TEA indicator chart formats (sex by age group, men blue, women magenta) Reuse the existing male blue and female magenta, in that order. Read the published sex-by-result and age-by-sex cells and omit unknown sex. Keep the report age labels and sort by the starting month. Use zero for absent count cells and omit rates without denominators. Keep M24 count heights and percentage labels. Stack the two outcomes within each sex using Plotly offset groups. Use the previous prevalence alpha of 0.25 for both transparent outcomes. For M31, use the published outcome counts and keep the sex focus control by outlining the selected bars while preserving both fill colors. Use the standard chart card height and identify changed figures by measure in the page checks. Prettier, targeted figure type checking, and the 23 indicator logic tests passed. Full application type checking requires the unavailable pdfmake dependencies in this checkout. Angular and Playwright runs are reserved for the test machines. --- e2e/pages.spec.ts | 8 +- src/app/indicadores/figures.ts | 226 +++++++-------------- src/app/indicadores/pages.ts | 10 +- src/app/indicadores/tab-indicadores.html | 19 +- src/app/indicadores/tab-indicadores.ts | 17 +- src/app/indicadores/tea-indicators.spec.ts | 100 ++++++--- 6 files changed, 174 insertions(+), 206 deletions(-) diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index 5d83f68..c39f01b 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -15,7 +15,13 @@ test('tea indicators: every tab loads, and the follow-up list exports to Excel', 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.locator('[data-measure="M31_PREVALENCIA"] .barlayer')).toBeVisible(); + await expect( + indicators.locator('[data-measure="M24_CONFIRMACION_DIAGNOSTICO"] app-plot'), + ).toHaveCount(1); + await expect( + indicators.locator('[data-measure="M23_PACIENTES_EVALUADOS"] mat-button-toggle-group'), + ).toHaveCount(0); 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 3b7ea5d..50914f5 100644 --- a/src/app/indicadores/figures.ts +++ b/src/app/indicadores/figures.ts @@ -340,69 +340,70 @@ export function countBars(r: Reading, catalog: Catalog, axis: string, period: st }; } -const AGE_COLORS = ['#A8C243', '#42C29C', '#9C42C2', '#4269C2']; +const TEA_SEXES = [ + { code: 'male', color: '#4269C2' }, + { code: 'female', color: ROSE }, +]; + const ageLabel = (band: string) => band.replace(/^(\d+)-(\d+)$/, '$1 a $2 meses'); -function ages(r: Reading): [string, Record][] { - return Object.entries(r.strata['age_group'] ?? {}).sort( - ([a], [b]) => parseInt(a, 10) - parseInt(b, 10), - ); +function ageBands(cells: Reading['strata'][string]): string[] { + const bands = Object.keys(cells) + .map((key) => key.split('|')) + .filter(([, code]) => TEA_SEXES.some((sex) => sex.code === code)) + .map(([band]) => band); + return [...new Set(bands)].sort((a, b) => parseInt(a, 10) - parseInt(b, 10)); } -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', - ); +export function ageStack(r: Reading, names: [string, string]): Figure { + const cells = r.strata['age_sex'] ?? {}; + const bands = ageBands(cells); + const x = bands.map(ageLabel); return { - 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[], + data: TEA_SEXES.flatMap(({ code, color }) => { + const rows = bands.map((band) => cells[`${band}|${code}`]); + const confirmed = rows.map((row) => row?.['numerator'] ?? 0); + const totals = rows.map((row) => row?.['denominator'] ?? 0); + return [confirmed, totals.map((n, i) => n - confirmed[i])].map((y, i) => ({ + type: 'bar', + name: `${name(code)} · ${names[i]}`, + offsetgroup: code, + x, + y, + marker: { color: i ? rgba(color, 0.25) : color }, + text: y.map((n, j) => (n ? `${n} (${percent((100 * n) / totals[j])} %)` : '')), + textposition: 'inside', + hovertemplate: '%{x}
%{fullData.name}: %{y} pacientes', + })) as Partial[]; + }), layout: { barmode: 'stack', - xaxis: { title: { text: stratum === 'sex' ? 'Sexo' : 'Grupo de edad' }, type: 'category' }, + xaxis: { title: { text: 'Grupo de edad' }, type: 'category' }, yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero' }, }, }; } export function ageShare(r: Reading, axis: string): Figure { - const rows = ages(r); + const cells = r.strata['age_sex'] ?? {}; + const bands = ageBands(cells); + const x = bands.map(ageLabel); return { - data: [ - { - type: 'bar', - x: rows.map(([a]) => ageLabel(a)), - y: rows.map(([, c]) => - c['denominator'] ? (100 * (c['numerator'] ?? 0)) / c['denominator'] : 0, - ), - marker: { color: rows.map((_, i) => AGE_COLORS[i % AGE_COLORS.length]) }, - texttemplate: '%{y:.1f} %', - textposition: 'outside', - hovertemplate: '%{x}: %{y:.1f} %', - } as Partial, - ], + 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:.1f} %', + textposition: 'outside', + hovertemplate: '%{x}: %{y:.1f} %%{fullData.name}', + })), layout: { - showlegend: false, + barmode: 'group', xaxis: { title: { text: 'Grupo de edad' }, type: 'category' }, yaxis: { title: { text: axis }, range: [0, 100], ticksuffix: ' %' }, }, @@ -467,24 +468,16 @@ export function historyFigure( }; } -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) => ({ + data: TEA_SEXES.map(({ code, color }) => ({ ...base.data[0], name: name(code), - marker: { - color: catalog.categories.map((c) => c.color), - pattern: { shape: ['', '/', '\\'][i] }, - }, + marker: { color }, x: catalog.categories.map((c) => cells[`${code}|${c.code}`]?.['initial-population'] ?? 0), + hovertemplate: '%{y}: %{x}%{fullData.name}', })) as Partial[], layout: { ...base.layout, barmode: 'group', showlegend: true }, }; @@ -539,102 +532,41 @@ export function teaSankey(r: Reading): Figure { }; } -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; +export function teaSexBars(r: Reading, selectedSex?: string): Figure { + const cells = r.strata['sex-category'] ?? {}; + const x = TEA_SEXES.map(({ code }) => name(code)); return { data: [ - { - type: 'pie', - hole: 0.58, - sort: false, - direction: 'clockwise', - labels: slices.map((s) => s.label), - values: slices.map((s) => s.value), + { 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, + x, + y, marker: { - colors: slices.map((s) => (!selected || s.code === selected.code ? s.color : '#E1E3E5')), + color: TEA_SEXES.map(({ color }) => (i ? rgba(color, 0.25) : color)), line: { - color: slices.map((s) => (!selected || s.code === selected.code ? s.line : '#C9CDD2')), - width: 1.5, + color: TEA_SEXES.map(({ color }) => color), + width: TEA_SEXES.map(({ code }) => (code === selectedSex ? 2 : 0)), }, }, - 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]), + customdata: TEA_SEXES.map(({ code }, j) => { + const total = r.strata['sex']?.[code]?.['initial-population'] ?? 0; + return [percent(total ? (100 * y[j]) / total : 0), total]; + }), hovertemplate: - '%{label}
%{value} niños, %{customdata[0]} % de %{customdata[1]}', - } as Partial, - ], + '%{x} · %{fullData.name}
%{y} niños, %{customdata[0]} % de %{customdata[1]}', + }; + }), 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 }, - }, - ], + barmode: 'group', + xaxis: { title: { text: 'Sexo' }, type: 'category' }, + yaxis: { title: { text: 'Niños' }, rangemode: 'tozero' }, }, }; } diff --git a/src/app/indicadores/pages.ts b/src/app/indicadores/pages.ts index 9f6c773..a123de8 100644 --- a/src/app/indicadores/pages.ts +++ b/src/app/indicadores/pages.ts @@ -32,14 +32,13 @@ export type FigureSpec = } | { kind: 'scenario-bars'; title: string; measure: string; catalog: Catalog; stratum: string } | { - kind: 'counts'; + kind: 'counts' | 'sex-counts'; title: string; measure: string; catalog: Catalog; axis: string; - bySex?: boolean; } - | { kind: 'sankey' | 'sex-donut' | 'alterations'; title: string; measure: string } + | { kind: 'sankey' | 'sex-bars' | 'alterations'; title: string; measure: string } | { kind: 'age-stack' | 'age-share'; title: string; @@ -157,10 +156,9 @@ export const PAGES: Record = { kind: 'grid', figures: [ { - kind: 'counts', + kind: 'sex-counts', title: 'Pacientes evaluados por resultado diagnóstico', measure: 'M23_PACIENTES_EVALUADOS', - bySex: true, axis: 'Conteo (paciente)', catalog: { groups: [], @@ -208,7 +206,7 @@ export const PAGES: Record = { }, }, { - kind: 'sex-donut', + kind: 'sex-bars', title: 'Prevalencia registrada de TEA', measure: 'M31_PREVALENCIA', }, diff --git a/src/app/indicadores/tab-indicadores.html b/src/app/indicadores/tab-indicadores.html index 89a1606..19440fe 100644 --- a/src/app/indicadores/tab-indicadores.html +++ b/src/app/indicadores/tab-indicadores.html @@ -137,17 +137,7 @@

{{ f.title }}

Filtro general aplicado: {{ period }}

- @if (f.kind === 'counts' && f.bySex) { - - Sin estratificar - Por sexo - - } - @if (f.kind === 'sex-donut') { + @if (f.kind === 'sex-bars') { } @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 928fa74..296fbac 100644 --- a/src/app/indicadores/tab-indicadores.ts +++ b/src/app/indicadores/tab-indicadores.ts @@ -21,7 +21,7 @@ import { sexCountBars, teaAlterations, teaSankey, - teaSexDonut, + teaSexBars, } from './figures'; import { FigureSpec, Kpi, PAGES, Section } from './pages'; import { name, periods, PeriodType, reading, Reading } from './measures'; @@ -49,7 +49,6 @@ 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); @@ -179,7 +178,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, stratum?: 'sex'): Figure | undefined { + protected figureOf(spec: FigureSpec): Figure | undefined { const r = this.rd(spec.measure); if (!r || !(r.populations['initial-population'] ?? 0)) return undefined; switch (spec.kind) { @@ -188,17 +187,17 @@ export class TabIndicadores { case 'share-donut': return shareDonut(r, spec.catalog, spec.center); case 'counts': - return spec.bySex && this.bySex() - ? sexCountBars(r, spec.catalog, spec.axis, this.applied() ?? '') - : countBars(r, spec.catalog, spec.axis, this.applied() ?? ''); + return countBars(r, spec.catalog, spec.axis, this.applied() ?? ''); + case 'sex-counts': + return sexCountBars(r, spec.catalog, spec.axis, this.applied() ?? ''); case 'sankey': return teaSankey(r); - case 'sex-donut': - return teaSexDonut(r, this.prevalenceSex()); + case 'sex-bars': + return teaSexBars(r, this.prevalenceSex()); case 'alterations': return teaAlterations(r); case 'age-stack': - return ageStack(r, spec.names, stratum); + return ageStack(r, spec.names); 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 e92e31b..ef10570 100644 --- a/src/app/indicadores/tea-indicators.spec.ts +++ b/src/app/indicadores/tea-indicators.spec.ts @@ -2,13 +2,14 @@ import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } f import { EXT } from '../fhir'; import { teaSteps } from '../paciente/tea-data'; import { + ageShare, ageStack, nestedDonut, sexCountBars, shareDonut, teaAlterations, teaSankey, - teaSexDonut, + teaSexBars, } from './figures'; import type { Catalog } from './pages'; import { @@ -354,25 +355,38 @@ describe('TEA clinical figures', () => { expect(new Set(places).size).toBe(places.length); }); - it('splits prevalence by sex and diagnosis and includes children without a recorded sex', () => { - const r = { + it('groups prevalence bars by sex and uses transparency for unconfirmed diagnoses', () => { + const figure = teaSexBars({ 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 }, + 'female|in_population': { 'initial-population': 1 }, 'male|confirmed': { 'initial-population': 1 }, + 'male|in_population': { 'initial-population': 2 }, + 'no_data|in_population': { '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)'); + }); + 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)'] }, + }, + ]); }); - it('uses crossed counts for diagnostic results and sex totals for confirmation', () => { + it('groups diagnostic results by sex using crossed counts', () => { const catalog: Catalog = { groups: [], categories: [ @@ -388,6 +402,7 @@ describe('TEA clinical figures', () => { 'female|confirmed': { 'initial-population': 2 }, 'female|in_process': { 'initial-population': 1 }, 'male|in_process': { 'initial-population': 3 }, + 'no_data|confirmed': { 'initial-population': 1 }, }, }, }, @@ -395,25 +410,58 @@ describe('TEA clinical figures', () => { 'Pacientes', '2025-S1', ); + expect(result.layout?.barmode).toBe('group'); 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 } }, - }, + name: 'Masculino', + x: [0, 3], + y: ['Confirmados', 'En proceso'], + marker: { color: '#4269C2' }, }, - ['Confirmados', 'En proceso'], - 'sex', - ); - expect(confirmation.data).toMatchObject([ - { x: ['Femenino', 'Masculino'], y: [2, 0] }, - { x: ['Femenino', 'Masculino'], y: [1, 3] }, + { + name: 'Femenino', + x: [2, 1], + y: ['Confirmados', 'En proceso'], + marker: { color: '#C24269' }, + }, + ]); + }); + + const byAgeAndSex = { + populations: {}, + strata: { + age_sex: { + '24-36|male': { numerator: 1, denominator: 1 }, + '16-23|female': { numerator: 1, denominator: 2 }, + '16-23|male': { numerator: 1, denominator: 4 }, + '37-48|no_data': { numerator: 1, denominator: 1 }, + }, + }, + }; + const ageGroups = ['16 a 23 meses', '24 a 36 meses']; + + it('stacks diagnostic status in one bar per sex in each age group', () => { + const figure = ageStack(byAgeAndSex, ['Confirmados', 'En proceso']); + expect(figure.layout?.barmode).toBe('stack'); + expect(figure.data).toMatchObject([ + { x: ageGroups, offsetgroup: 'male', y: [1, 1], marker: { color: '#4269C2' } }, + { x: ageGroups, offsetgroup: 'male', y: [3, 0], marker: { color: 'rgba(66,105,194,0.25)' } }, + { x: ageGroups, offsetgroup: 'female', y: [1, 0], marker: { color: '#C24269' } }, + { + x: ageGroups, + offsetgroup: 'female', + y: [1, 0], + marker: { color: 'rgba(194,66,105,0.25)' }, + }, + ]); + }); + + it('groups EEG percentages by age and sex and omits missing denominators', () => { + 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' } }, ]); });