Merge parity/F1f

This commit is contained in:
2026-12-01 13:45:25 -06:00
6 changed files with 174 additions and 206 deletions
+7 -1
View File
@@ -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);
+79 -147
View File
@@ -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<string, number>][] {
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}<br>%{fullData.name}: %{y} pacientes<extra></extra>',
})) as Partial<Plotly.Data>[],
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}<br>%{fullData.name}: %{y} pacientes<extra></extra>',
})) as Partial<Plotly.Data>[];
}),
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} %<extra></extra>',
} as Partial<Plotly.Data>,
],
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} %<extra>%{fullData.name}</extra>',
})),
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}<extra>%{fullData.name}</extra>',
})) as Partial<Plotly.Data>[],
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}<br>${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}<br>%{value} niños, %{customdata[0]} % de %{customdata[1]}<extra></extra>',
} as Partial<Plotly.Data>,
],
'%{x} · %{fullData.name}<br>%{y} niños, %{customdata[0]} % de %{customdata[1]}<extra></extra>',
};
}),
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: `<b>${share(centerCases, centerTotal)} %</b><br>${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' },
},
};
}
+4 -6
View File
@@ -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<string, Page> = {
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<string, Page> = {
},
},
{
kind: 'sex-donut',
kind: 'sex-bars',
title: 'Prevalencia registrada de TEA',
measure: 'M31_PREVALENCIA',
},
+2 -17
View File
@@ -137,17 +137,7 @@
<mat-card-content>
<h2 class="box-title">{{ f.title }}</h2>
<p class="state">Filtro general aplicado: {{ period }}</p>
@if (f.kind === 'counts' && f.bySex) {
<mat-button-toggle-group
aria-label="Estratificación"
[value]="bySex()"
(change)="bySex.set($event.value)"
>
<mat-button-toggle [value]="false">Sin estratificar</mat-button-toggle>
<mat-button-toggle [value]="true">Por sexo</mat-button-toggle>
</mat-button-toggle-group>
}
@if (f.kind === 'sex-donut') {
@if (f.kind === 'sex-bars') {
<mat-button-toggle-group
aria-label="Sexo"
[value]="prevalenceSex()"
@@ -161,12 +151,7 @@
@if (reports.isLoading()) {
<app-loading what="la figura" [figure]="true" />
} @else if (figureOf(f); as fig) {
<app-plot [figure]="fig" [height]="f.kind === 'sex-donut' ? 420 : 320" />
@if (f.kind === 'age-stack') {
@if (figureOf(f, 'sex'); as bySexFigure) {
<app-plot [figure]="bySexFigure" [height]="320" />
}
}
<app-plot [figure]="fig" [height]="320" />
} @else {
<div class="empty-figure">Sin datos publicados</div>
}
+8 -9
View File
@@ -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<PeriodType>('semester');
protected readonly options = computed(() => periods(this.type()));
protected readonly chosen = signal<string | undefined>(undefined);
protected readonly bySex = signal(false);
protected readonly prevalenceSex = signal<string | undefined>(undefined);
protected readonly applied = signal<string | undefined>(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':
+74 -26
View File
@@ -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' } },
]);
});