CaMa Indicadores as the old page: its cards, timeliness boxes with pending ones, BI-RADS 4–6 donuts, malignancy by BI-RADS and the biopsy donut, the confirmation card; page definitions apart from figure builders

This commit is contained in:
Roberto Treviño
2026-11-28 10:09:30 -06:00
parent 9a15ac6fcb
commit 3e096dd03f
6 changed files with 692 additions and 308 deletions
+5 -2
View File
@@ -186,12 +186,15 @@ function captured(domain: string) {
const path = `../tests/fixtures/reference/${domain}/ui/pages.json`; const path = `../tests/fixtures/reference/${domain}/ui/pages.json`;
const items = JSON.parse(readFileSync(path, 'utf8')).tabs['Indicadores'] as any[]; const items = JSON.parse(readFileSync(path, 'utf8')).tabs['Indicadores'] as any[];
const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad'); const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad');
return items.slice(from).filter((i) => ['h2', 'h3', 'plot'].includes(i.kind)); return items
.slice(from)
.filter((i) => ['h2', 'h3', 'plot'].includes(i.kind))
.filter((i) => !/^(cacu|cama|tea), /.test(i.text ?? '')); // a figure's machine caption
} }
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>'); const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+'); const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
for (const domain of ['cacu']) { for (const domain of ['cacu', 'cama']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({ test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page, page,
}) => { }) => {
+328
View File
@@ -0,0 +1,328 @@
import type { Figure } from '../plot';
import type { Reading } from './measures';
import type { Catalog, Category } from './pages';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
const count = (n: number) => n.toLocaleString('es-MX');
const percent = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
function rgba(hex: string, alpha: number): string {
const v = parseInt(hex.slice(1), 16);
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
}
/** The screening route: each step's median days from the sample, with Q1–Q3. */
export function routeFigure(steps: { label: string; r: Reading | undefined }[]): Figure {
const shown = steps.filter((s) => s.r?.score !== undefined);
return {
data: [
{
type: 'bar',
orientation: 'h',
y: shown.map(
(s) => `${s.label}<br>n = ${count(s.r!.populations['measure-observation'] ?? 0)}`,
),
x: shown.map((s) => s.r!.score!),
marker: { color: OLIVE },
error_x: {
type: 'data',
symmetric: false,
thickness: 1.5,
width: 6,
array: shown.map((s) => (s.r!.high ?? s.r!.score!) - s.r!.score!),
arrayminus: shown.map((s) => s.r!.score! - (s.r!.low ?? s.r!.score!)),
},
hovertemplate: '%{y}<br>mediana %{x} días<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: { title: { text: 'Días' }, rangemode: 'tozero', zeroline: false },
yaxis: { autorange: 'reversed', type: 'category', automargin: true },
},
};
}
/** A category's count in the report (the composition's `category` stratum). */
function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0;
}
/** Groups inside, their categories outside, the total in the centre. */
export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
const groups = catalog.groups.map((g) =>
catalog.categories.reduce((n, c, i) => n + (c.group === g.id ? values[i] : 0), 0),
);
const faded = new Set(catalog.faded ?? []);
const share = (n: number) => (total ? `${percent((100 * n) / total)} %` : '');
const common = {
type: 'pie',
sort: false,
direction: 'clockwise',
rotation: 0,
showlegend: false,
textinfo: 'text',
textposition: 'inside',
insidetextorientation: 'horizontal',
};
return {
data: [
{
...common,
name: 'centro',
values: [1],
labels: ['centro'],
domain: { x: [0.32, 0.68], y: [0.32, 0.68] },
text: [`<b>${count(total)}</b><br>${center}`],
marker: { colors: ['#FFFFFF'] },
hoverinfo: 'skip',
},
{
...common,
name: 'grupos',
values: groups,
labels: catalog.groups.map((g) => g.label),
hole: 0.62,
domain: { x: [0.16, 0.84], y: [0.16, 0.84] },
text: groups.map((n, i) =>
total && n / total >= 0.05 ? `${catalog.groups[i].label}<br>${share(n)}` : '',
),
marker: {
colors: catalog.groups.map((g) =>
rgba(
g.color,
catalog.categories.some((c) => c.group === g.id && !faded.has(c.code)) ? 1 : 0.3,
),
),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
},
{
...common,
name: 'categorias',
values,
labels: catalog.categories.map((c) => c.label),
hole: 0.74,
domain: { x: [0, 1], y: [0, 1] },
text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')),
marker: {
colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
},
] as Partial<Plotly.Data>[],
layout: { margin: { t: 10, l: 10, r: 10, b: 10 } },
};
}
/** Each clinical scenario's results as shares of its patients, one stacked bar each. */
export function scenarioBars(
r: Reading,
catalog: Catalog,
stratum: string,
label: (code: string) => string,
): Figure {
const cells = r.strata[`${stratum}-category`] ?? {};
const scenarios = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))].sort((a, b) =>
label(a).localeCompare(label(b), 'es'),
);
const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0;
const totals = scenarios.map((s) => catalog.categories.reduce((t, c) => t + n(s, c.code), 0));
const y = scenarios.map(label);
return {
data: catalog.categories.map((c) => ({
type: 'bar',
orientation: 'h',
name: c.label,
y,
x: scenarios.map((s, i) => (totals[i] ? (100 * n(s, c.code)) / totals[i] : 0)),
customdata: scenarios.map((s) => n(s, c.code)),
marker: { color: c.color },
hovertemplate: `${c.label}<br>%{y}: %{customdata} (%{x:.1f} %)<extra></extra>`,
})) as Partial<Plotly.Data>[],
layout: {
barmode: 'stack',
xaxis: {
title: { text: '% de pacientes del escenario con resultado' },
ticksuffix: ' %',
range: [0, 100],
},
yaxis: {
type: 'category',
autorange: 'reversed',
categoryorder: 'array',
categoryarray: y,
automargin: true,
},
legend: { orientation: 'h', y: -0.25 },
},
};
}
/** Wilson score interval at 95 %, in percent. */
export function wilson(k: number, n: number): [number, number] {
const z = 1.959963984540054;
const p = k / n;
const d = 1 + (z * z) / n;
const c = (p + (z * z) / (2 * n)) / d;
const h = (z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n))) / d;
return [100 * (c - h), 100 * (c + h)];
}
/** Per cytology result: of the women with a biopsy, the share whose biopsy is a positive,
* with its 95 % interval; a result nobody had a biopsy for is named, not drawn. */
export function rateDots(
r: Reading,
spec: { stratum: string; rows: Category[]; positive: string[]; axis: string; colored?: boolean },
): Figure {
const cells = r.strata[`${spec.stratum}-category`] ?? {};
const rows = spec.rows.map((row) => {
const of = Object.entries(cells).filter(([k]) => k.split('|')[0] === row.code);
const biopsied = of.filter(([k]) => !['no_biopsy', 'no_data'].includes(k.split('|')[1]));
const den = biopsied.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const k = biopsied
.filter(([key]) => spec.positive.includes(key.split('|')[1]))
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const rate = den ? (100 * k) / den : null;
const [low, high] = den ? wilson(k, den) : [null, null];
return { row, k, den, rate, low, high };
});
const y = rows.map((x) => x.row.label);
return {
data: [
{
type: 'scatter',
mode: 'markers',
name: 'tasas',
y,
x: rows.map((x) => x.rate),
marker: { size: 12, color: spec.colored ? rows.map((x) => x.row.color) : ROSE },
cliponaxis: false,
error_x: {
type: 'data',
symmetric: false,
color: ROSE,
thickness: 2,
width: 6,
array: rows.map((x) => (x.rate === null ? 0 : x.high! - x.rate)),
arrayminus: rows.map((x) => (x.rate === null ? 0 : x.rate - x.low!)),
},
hovertemplate: '%{y}: %{x:.1f} %<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
margin: { t: 24, r: 110, b: 56, l: 56 },
yaxis: {
type: 'category',
categoryorder: 'array',
categoryarray: [...y].reverse(),
automargin: true,
},
xaxis: { range: [0, 100], ticksuffix: ' %', zeroline: false, title: { text: spec.axis } },
annotations: rows.map((x) => ({
x: 1,
xref: 'paper',
xanchor: 'left',
xshift: 8,
y: x.row.label,
yref: 'y',
showarrow: false,
align: 'left',
text: x.den
? `<b>${percent(x.rate!)} %</b><br>${x.k}/${x.den}`
: spec.colored
? 'Sin pacientes'
: 'Sin biopsias',
})),
},
};
}
const decimal = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 2 });
/** A card's template filled from its measure's reading in the period: {n} counted, {obs}
* measured, {median} {q1} {q3} days, {num} {den} {pct}. */
export function fill(template: string, r: Reading): string {
const p = r.populations;
const values: Record<string, string> = {
n: count(p['initial-population'] ?? 0),
obs: count(p['measure-observation'] ?? 0),
median: r.score === undefined ? '' : decimal(r.score),
q1: decimal(r.low ?? r.score ?? 0),
q3: decimal(r.high ?? r.score ?? 0),
num: count(p['numerator'] ?? 0),
den: count(p['denominator'] ?? 0),
pct: r.score === undefined ? '' : percent(r.score * 100),
};
return template.replace(/\{(\w+)\}/g, (_, k) => values[k] ?? '');
}
/** A duration's quartile box in the period. */
export function boxFigure(r: Reading, period: string): Figure {
const q1 = r.low ?? r.score!;
const q3 = r.high ?? r.score!;
return {
data: [
{
type: 'box',
name: 'Total',
x: [period],
q1: [q1],
median: [r.score!],
q3: [q3],
lowerfence: [q1],
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<extra></extra>`,
} as Partial<Plotly.Data>,
],
layout: { showlegend: false, yaxis: { title: { text: 'días' }, rangemode: 'tozero' } },
};
}
/** One ring: the categories' shares, the total in the centre. */
export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
return {
data: [
{
type: 'pie',
hole: 0.54,
sort: false,
direction: 'clockwise',
labels: catalog.categories.map((c) => c.label),
values,
marker: {
colors: catalog.categories.map((c) => c.color),
line: { color: '#FFFFFF', width: 2 },
},
// an empty slice says nothing (its label would sit on its neighbours')
texttemplate: values.map((v) => (v ? '%{label}<br>%{percent}' : '')),
textposition: 'outside',
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
margin: { t: 30, l: 60, r: 60, b: 30 },
annotations: [
{
text: `<b>${count(total)}</b><br>${center}`,
showarrow: false,
x: 0.5,
y: 0.5,
xref: 'paper',
yref: 'paper',
},
],
},
};
}
+181 -248
View File
@@ -1,20 +1,36 @@
import type { Figure } from '../plot';
import type { Reading } from './measures';
/** A domain's Indicadores page as the old app showed it (tests/fixtures/reference/<domain>/ui): /** A domain's Indicadores page as the old app showed it (tests/fixtures/reference/<domain>/ui):
* the timeliness cards with their own words, then the clinical sections and their figures. * the timeliness cards with their own words, then the clinical sections and their figures.
* Measures are named by their code (`Measure.name`). */ * Measures are named by their code (`Measure.name`). */
export interface Page { export interface Page {
kpis: { measure: string; title: string; note?: string }[]; kpis: Kpi[];
/** Under the cards, before the clinical indicators (CaMa's timeliness boxes). */
opportunity?: Section[];
clinical: Section[]; clinical: Section[];
/** The measure whose data decides the default period. */ /** The measure whose data decides the default period. */
anchor: string; anchor: string;
} }
/** A card: its measure (none: not published yet), its title, and its value and note as
* templates (figures.fill). */
export interface Kpi {
measure?: string;
title: string;
value?: string;
note?: string;
}
export type Section = export type Section =
| { kind: 'route'; title: string; steps: { label: string; measure: string }[] } | { kind: 'route'; title: string; steps: { label: string; measure: string }[] }
| { kind: 'figures'; title: string; figures: FigureSpec[] }; | { kind: 'figures'; title?: string; figures: FigureSpec[] }
| { kind: 'boxes'; title: string; cards: { measure?: string; title: string }[] }
| ({ kind: 'card' } & Kpi);
/** Figure titles may carry `{p}`, the applied period. */
export type FigureSpec = export type FigureSpec =
| { kind: 'donut'; title: string; measure: string; catalog: Catalog; center: string } | {
kind: 'donut' | 'share-donut';
title: string;
measure: string;
catalog: Catalog;
center: string;
}
| { kind: 'scenario-bars'; title: string; measure: string; catalog: Catalog; stratum: string } | { kind: 'scenario-bars'; title: string; measure: string; catalog: Catalog; stratum: string }
| { | {
kind: 'rates'; kind: 'rates';
@@ -22,6 +38,8 @@ export type FigureSpec =
measure: string; measure: string;
stratum: string; stratum: string;
rows: Category[]; rows: Category[];
/** each row in its category's colour (else all rose) */
colored?: boolean;
/** the categories (of the measure) that count as a positive */ /** the categories (of the measure) that count as a positive */
positive: string[]; positive: string[];
axis: string; axis: string;
@@ -75,21 +93,171 @@ const BIOPSY: Catalog = {
faded: ['normal', 'LSIL'], faded: ['normal', 'LSIL'],
}; };
const CACU_DAYS = {
value: '{median} días (mediana)',
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
};
const CAMA_DAYS = {
value: '{median} días (mediana)',
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
};
const PENDING = 'Este indicador aún no está publicado por el catálogo institucional.';
/** BI-RADS 4 to 6 as the old app named and coloured them. */
const BIRADS: Catalog = {
groups: [],
categories: [
{ code: '4', label: 'BI-RADS 4 (sin subcategoría)', color: '#C24269', group: '' },
{ code: '4A', label: 'BI-RADS 4A', color: '#9C42C2', group: '' },
{ code: '4B', label: 'BI-RADS 4B', color: '#5C42C2', group: '' },
{ code: '4C', label: 'BI-RADS 4C', color: '#C2429C', group: '' },
{ code: '5', label: 'BI-RADS 5', color: '#8E2F62', group: '' },
{ code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' },
],
};
const BREAST_BIOPSY: Catalog = {
groups: [
{ id: 'benign', label: 'No maligno', color: '#42C29C' },
{ id: 'malignant', label: 'Maligno', color: ROSE },
],
categories: [
{ code: 'benign', label: 'Benigno', color: OLIVE, group: 'benign' },
{ code: 'in_situ', label: 'Carcinoma in situ', color: '#9C42C2', group: 'malignant' },
{ code: 'invasive', label: 'Carcinoma invasor', color: '#5C42C2', group: 'malignant' },
],
};
export const PAGES: Record<string, Page> = { export const PAGES: Record<string, Page> = {
cama: {
anchor: 'CAMA_BIRADS456_PACIENTE',
kpis: [
{
measure: 'CAMA_BIRADS456_PACIENTE',
title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
value: '{n} pacientes',
note: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
},
{
measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
title: 'Tasa de confirmación histopatológica',
value: '{pct} %',
note: '{num} de {den} biopsias con riesgo a carcinoma.',
},
{
measure: 'CAMA_EU38A',
title: 'Tiempo de toma de mastografía a interpretación radiológica',
...CAMA_DAYS,
},
{
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Tiempo de interpretación radiológica a diagnóstico',
...CAMA_DAYS,
},
{
title: 'Tiempo de diagnóstico a tratamiento',
value: 'Indicador no disponible',
note: PENDING,
},
],
opportunity: [
{
kind: 'boxes',
title: 'Tiempo de tamizaje a diagnóstico',
cards: [
{
measure: 'CAMA_EU38A',
title: 'Tiempo de toma de mastografía a interpretación radiológica',
},
{
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Tiempo de interpretación radiológica a diagnóstico',
},
{ title: 'Tiempo de interpretación radiológica a resultado de biopsia' },
{ title: 'Tiempo de diagnóstico a tratamiento' },
{ measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', title: 'Tiempo de tamizaje a diagnóstico' },
],
},
],
clinical: [
{
kind: 'figures',
figures: [
{
kind: 'share-donut',
title: 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en {p}',
measure: 'CAMA_BIRADS456_MASTOGRAFIA',
catalog: BIRADS,
center: 'mastografías',
},
{
kind: 'share-donut',
title: 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en {p}',
measure: 'CAMA_BIRADS456_PACIENTE',
catalog: BIRADS,
center: 'pacientes',
},
],
},
{
kind: 'figures',
title: 'Resultado histopatológico por categoría BI-RADS',
figures: [
{
kind: 'rates',
title: 'Por categoría BI-RADS, {p}',
measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
stratum: 'birads',
rows: BIRADS.categories,
colored: true,
positive: ['in_situ', 'invasive'],
axis: 'Porcentaje con resultado maligno',
},
{
kind: 'donut',
title: 'Resultado de la biopsia, {p}',
measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
catalog: BREAST_BIOPSY,
center: 'con resultado',
},
],
},
{
kind: 'card',
measure: 'CAMA_CONFIRMACION_BIRADS45',
title: 'Tasa de confirmación histopatológica',
value: '{pct} %',
note: '{num} de {den} mastografías BI-RADS 4 y 5 con reporte de biopsia.',
},
],
},
cacu: { cacu: {
anchor: 'CACU_EU7', anchor: 'CACU_EU7',
kpis: [ kpis: [
{ {
measure: 'CACU_EU7', measure: 'CACU_EU7',
title: 'Pacientes evaluadas', title: 'Pacientes evaluadas',
value: '{n} pacientes',
note: 'Pacientes con citología tomada en el periodo.', note: 'Pacientes con citología tomada en el periodo.',
}, },
{ measure: 'CACU_EU_TIEMPO_REPORTE', title: 'Tiempo desde la toma de muestra al resultado' }, {
{ measure: 'CACU_DIAS_TOMA_DIAGNOSTICO', title: 'Tiempo de tamizaje a diagnóstico' }, measure: 'CACU_EU_TIEMPO_REPORTE',
{ measure: 'CACU_DIAS_TOMA_TRATAMIENTO', title: 'Tiempo de tamizaje a tratamiento' }, title: 'Tiempo desde la toma de muestra al resultado',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Tiempo de tamizaje a tratamiento',
...CACU_DAYS,
},
{ {
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento', title: 'Tiempo de diagnóstico a tratamiento',
...CACU_DAYS,
}, },
], ],
clinical: [ clinical: [
@@ -109,14 +277,14 @@ export const PAGES: Record<string, Page> = {
figures: [ figures: [
{ {
kind: 'donut', kind: 'donut',
title: 'Distribución de resultados', title: 'Distribución de resultados, {p}',
measure: 'CACU_EU7', measure: 'CACU_EU7',
catalog: CYTOLOGY, catalog: CYTOLOGY,
center: 'pacientes', center: 'pacientes',
}, },
{ {
kind: 'scenario-bars', kind: 'scenario-bars',
title: 'TOTAL por escenario clínico', title: 'TOTAL por escenario clínico, {p}',
measure: 'CACU_EU7', measure: 'CACU_EU7',
catalog: CYTOLOGY, catalog: CYTOLOGY,
stratum: 'follow_up_status', stratum: 'follow_up_status',
@@ -129,7 +297,7 @@ export const PAGES: Record<string, Page> = {
figures: [ figures: [
{ {
kind: 'rates', kind: 'rates',
title: 'Por resultado de la citología', title: 'Por resultado de la citología, {p}',
measure: 'CACU_CONFIRMACION_CITOLOGIA', measure: 'CACU_CONFIRMACION_CITOLOGIA',
stratum: 'result', stratum: 'result',
rows: CYTOLOGY.categories.filter((c) => ['ASC-H', 'HSIL', 'CIS'].includes(c.code)), rows: CYTOLOGY.categories.filter((c) => ['ASC-H', 'HSIL', 'CIS'].includes(c.code)),
@@ -138,7 +306,7 @@ export const PAGES: Record<string, Page> = {
}, },
{ {
kind: 'donut', kind: 'donut',
title: 'Resultado de la biopsia', title: 'Resultado de la biopsia, {p}',
measure: 'CACU_CONFIRMACION_CITOLOGIA', measure: 'CACU_CONFIRMACION_CITOLOGIA',
catalog: BIOPSY, catalog: BIOPSY,
center: 'con biopsia', center: 'con biopsia',
@@ -148,238 +316,3 @@ export const PAGES: Record<string, Page> = {
], ],
}, },
}; };
const count = (n: number) => n.toLocaleString('es-MX');
const percent = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
function rgba(hex: string, alpha: number): string {
const v = parseInt(hex.slice(1), 16);
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
}
/** The screening route: each step's median days from the sample, with Q1–Q3. */
export function routeFigure(steps: { label: string; r: Reading | undefined }[]): Figure {
const shown = steps.filter((s) => s.r?.score !== undefined);
return {
data: [
{
type: 'bar',
orientation: 'h',
y: shown.map(
(s) => `${s.label}<br>n = ${count(s.r!.populations['measure-observation'] ?? 0)}`,
),
x: shown.map((s) => s.r!.score!),
marker: { color: OLIVE },
error_x: {
type: 'data',
symmetric: false,
thickness: 1.5,
width: 6,
array: shown.map((s) => (s.r!.high ?? s.r!.score!) - s.r!.score!),
arrayminus: shown.map((s) => s.r!.score! - (s.r!.low ?? s.r!.score!)),
},
hovertemplate: '%{y}<br>mediana %{x} días<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: { title: { text: 'Días' }, rangemode: 'tozero', zeroline: false },
yaxis: { autorange: 'reversed', type: 'category', automargin: true },
},
};
}
/** A category's count in the report (the composition's `category` stratum). */
function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0;
}
/** Groups inside, their categories outside, the total in the centre. */
export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
const groups = catalog.groups.map((g) =>
catalog.categories.reduce((n, c, i) => n + (c.group === g.id ? values[i] : 0), 0),
);
const faded = new Set(catalog.faded ?? []);
const share = (n: number) => (total ? `${percent((100 * n) / total)} %` : '');
const common = {
type: 'pie',
sort: false,
direction: 'clockwise',
rotation: 0,
showlegend: false,
textinfo: 'text',
textposition: 'inside',
insidetextorientation: 'horizontal',
};
return {
data: [
{
...common,
name: 'centro',
values: [1],
labels: ['centro'],
domain: { x: [0.32, 0.68], y: [0.32, 0.68] },
text: [`<b>${count(total)}</b><br>${center}`],
marker: { colors: ['#FFFFFF'] },
hoverinfo: 'skip',
},
{
...common,
name: 'grupos',
values: groups,
labels: catalog.groups.map((g) => g.label),
hole: 0.62,
domain: { x: [0.16, 0.84], y: [0.16, 0.84] },
text: groups.map((n, i) =>
total && n / total >= 0.05 ? `${catalog.groups[i].label}<br>${share(n)}` : '',
),
marker: {
colors: catalog.groups.map((g) =>
rgba(
g.color,
catalog.categories.some((c) => c.group === g.id && !faded.has(c.code)) ? 1 : 0.3,
),
),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
},
{
...common,
name: 'categorias',
values,
labels: catalog.categories.map((c) => c.label),
hole: 0.74,
domain: { x: [0, 1], y: [0, 1] },
text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')),
marker: {
colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
},
] as Partial<Plotly.Data>[],
layout: { margin: { t: 10, l: 10, r: 10, b: 10 } },
};
}
/** Each clinical scenario's results as shares of its patients, one stacked bar each. */
export function scenarioBars(
r: Reading,
catalog: Catalog,
stratum: string,
label: (code: string) => string,
): Figure {
const cells = r.strata[`${stratum}-category`] ?? {};
const scenarios = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))].sort((a, b) =>
label(a).localeCompare(label(b), 'es'),
);
const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0;
const totals = scenarios.map((s) => catalog.categories.reduce((t, c) => t + n(s, c.code), 0));
const y = scenarios.map(label);
return {
data: catalog.categories.map((c) => ({
type: 'bar',
orientation: 'h',
name: c.label,
y,
x: scenarios.map((s, i) => (totals[i] ? (100 * n(s, c.code)) / totals[i] : 0)),
customdata: scenarios.map((s) => n(s, c.code)),
marker: { color: c.color },
hovertemplate: `${c.label}<br>%{y}: %{customdata} (%{x:.1f} %)<extra></extra>`,
})) as Partial<Plotly.Data>[],
layout: {
barmode: 'stack',
xaxis: {
title: { text: '% de pacientes del escenario con resultado' },
ticksuffix: ' %',
range: [0, 100],
},
yaxis: {
type: 'category',
autorange: 'reversed',
categoryorder: 'array',
categoryarray: y,
automargin: true,
},
legend: { orientation: 'h', y: -0.25 },
},
};
}
/** Wilson score interval at 95 %, in percent. */
export function wilson(k: number, n: number): [number, number] {
const z = 1.959963984540054;
const p = k / n;
const d = 1 + (z * z) / n;
const c = (p + (z * z) / (2 * n)) / d;
const h = (z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n))) / d;
return [100 * (c - h), 100 * (c + h)];
}
/** Per cytology result: of the women with a biopsy, the share whose biopsy is a positive,
* with its 95 % interval; a result nobody had a biopsy for is named, not drawn. */
export function rateDots(
r: Reading,
spec: { stratum: string; rows: Category[]; positive: string[]; axis: string },
): Figure {
const cells = r.strata[`${spec.stratum}-category`] ?? {};
const rows = spec.rows.map((row) => {
const of = Object.entries(cells).filter(([k]) => k.split('|')[0] === row.code);
const biopsied = of.filter(([k]) => !['no_biopsy', 'no_data'].includes(k.split('|')[1]));
const den = biopsied.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const k = biopsied
.filter(([key]) => spec.positive.includes(key.split('|')[1]))
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const rate = den ? (100 * k) / den : null;
const [low, high] = den ? wilson(k, den) : [null, null];
return { row, k, den, rate, low, high };
});
const y = rows.map((x) => x.row.label);
return {
data: [
{
type: 'scatter',
mode: 'markers',
name: 'tasas',
y,
x: rows.map((x) => x.rate),
marker: { size: 12, color: ROSE },
cliponaxis: false,
error_x: {
type: 'data',
symmetric: false,
color: ROSE,
thickness: 2,
width: 6,
array: rows.map((x) => (x.rate === null ? 0 : x.high! - x.rate)),
arrayminus: rows.map((x) => (x.rate === null ? 0 : x.rate - x.low!)),
},
hovertemplate: '%{y}: %{x:.1f} %<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
margin: { t: 24, r: 110, b: 56, l: 56 },
yaxis: {
type: 'category',
categoryorder: 'array',
categoryarray: [...y].reverse(),
automargin: true,
},
xaxis: { range: [0, 100], ticksuffix: ' %', zeroline: false, title: { text: spec.axis } },
annotations: rows.map((x) => ({
x: 1,
xref: 'paper',
xanchor: 'left',
xshift: 8,
y: x.row.label,
yref: 'y',
showarrow: false,
align: 'left',
text: x.den ? `<b>${percent(x.rate!)} %</b><br>${x.k}/${x.den}` : 'Sin biopsias',
})),
},
};
}
+67 -11
View File
@@ -40,26 +40,40 @@
<span class="period">Periodo {{ period }}</span> <span class="period">Periodo {{ period }}</span>
</div> </div>
<div class="kpis"> <div class="kpis">
@for (k of pg.kpis; track k.measure) { @for (k of pg.kpis; track k.title) {
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure"> <mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null">
<mat-card-content> <mat-card-content>
<h3 class="kpi-title">{{ k.title }}</h3> <h3 class="kpi-title">{{ k.title }}</h3>
@if (reports.isLoading()) { @if (reports.isLoading() && k.measure) {
<app-loading [what]="k.title.toLowerCase()" /> <app-loading [what]="k.title.toLowerCase()" />
} @else { } @else {
<div class="kpi-value">{{ kpiValue(k.measure) }}</div> <div class="kpi-value" [class.pending]="!k.measure">{{ kpiValue(k) }}</div>
<div class="kpi-detail">{{ kpiNote(k.measure, k.note) }}</div> <div class="kpi-detail">{{ kpiNote(k) }}</div>
} }
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
} }
</div> </div>
@for (section of pg.opportunity ?? []; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section> </section>
<section class="card clinical-page" aria-labelledby="clinical-title"> <section class="card clinical-page" aria-labelledby="clinical-title">
<h2 id="clinical-title">Indicadores clínicos</h2> <h2 id="clinical-title">Indicadores clínicos</h2>
@for (section of pg.clinical; track section.title) { @for (section of pg.clinical; track $index) {
@if (section.kind === 'route') { <ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section>
}
<ng-template #sectionView let-section let-period="period">
@switch (section.kind) {
@case ('route') {
<h3 class="route-title">{{ section.title }}</h3> <h3 class="route-title">{{ section.title }}</h3>
@if (reports.isLoading()) { @if (reports.isLoading()) {
<app-loading what="los tiempos de la ruta" [figure]="true" /> <app-loading what="los tiempos de la ruta" [figure]="true" />
@@ -68,18 +82,61 @@
} @else { } @else {
<p class="state">Sin tiempos publicados en el periodo.</p> <p class="state">Sin tiempos publicados en el periodo.</p>
} }
}
@case ('boxes') {
<h3 class="boxes-title">{{ section.title }}</h3>
<div class="box-grid">
@for (b of section.cards; track b.title) {
<mat-card
appearance="outlined"
class="box-card"
[attr.data-measure]="b.measure ?? null"
>
<mat-card-content>
<h2 class="box-title">{{ b.title }}</h2>
@if (!b.measure) {
<p class="state"><strong>Integración pendiente.</strong> {{ pending }}</p>
<div class="empty-figure">Sin datos publicados</div>
} @else { } @else {
<p class="state">Filtro general aplicado: {{ period }}</p>
<h2 class="box-subtitle">{{ measureTitle(b.measure) }}</h2>
<p class="state">Figura: Caja de cuartiles</p>
@if (reports.isLoading()) {
<app-loading what="la figura" [figure]="true" />
} @else if (boxOf(b.measure); as fig) {
<app-plot [figure]="fig" [height]="320" />
} @else {
<div class="empty-figure">Sin datos publicados</div>
}
}
</mat-card-content>
</mat-card>
}
</div>
}
@case ('card') {
<mat-card appearance="outlined" class="kpi closing" [attr.data-measure]="section.measure">
<mat-card-content>
<h3 class="kpi-title">{{ section.title }}</h3>
<div class="kpi-value">{{ kpiValue(section) }}</div>
<div class="kpi-detail">{{ kpiNote(section) }}</div>
</mat-card-content>
</mat-card>
}
@default {
<mat-card appearance="outlined" class="figure-card"> <mat-card appearance="outlined" class="figure-card">
<mat-card-content> <mat-card-content>
@if (section.title) {
<h2 class="figure-card-title">{{ section.title }}</h2> <h2 class="figure-card-title">{{ section.title }}</h2>
}
<div class="figure-row"> <div class="figure-row">
@for (f of section.figures; track f.title) { @for (f of section.figures; track f.title) {
<div class="figure" [attr.data-figure]="f.kind"> <div class="figure" [attr.data-figure]="f.kind">
<h3>{{ f.title }}, {{ period }}</h3> <h3 [class.light]="f.kind === 'share-donut'">{{ titled(f.title) }}</h3>
@if (reports.isLoading()) { @if (reports.isLoading()) {
<app-loading what="la figura" [figure]="true" /> <app-loading what="la figura" [figure]="true" />
} @else if (figureOf(f); as fig) { } @else if (figureOf(f); as fig) {
<app-plot [figure]="fig" [height]="f.kind === 'donut' ? 360 : 380" /> <app-plot [figure]="fig" [height]="360" />
} @else { } @else {
<p class="state">Sin datos en el periodo.</p> <p class="state">Sin datos en el periodo.</p>
} }
@@ -90,8 +147,7 @@
</mat-card> </mat-card>
} }
} }
</section> </ng-template>
}
} @else { } @else {
@if (kpis().length) { @if (kpis().length) {
<h2>Indicadores de oportunidad</h2> <h2>Indicadores de oportunidad</h2>
+53
View File
@@ -188,3 +188,56 @@ h2.filters-title {
font-weight: 500; font-weight: 500;
margin: 0; margin: 0;
} }
h3.boxes-title {
font-size: 18px;
font-weight: 500;
margin: 24px 0 12px;
}
.box-grid {
display: grid;
gap: 16px;
grid-template-columns: 1fr;
}
@media (min-width: 1000px) {
.box-grid {
grid-template-columns: 1fr 1fr;
}
}
h2.box-title {
font-size: 18px;
font-weight: 500;
margin: 0 0 4px;
}
h2.box-subtitle {
font-size: 16px;
font-weight: 500;
margin: 8px 0 0;
}
.empty-figure {
align-items: center;
border: 1px solid var(--color-border);
border-radius: 8px;
color: var(--color-text-secondary);
display: flex;
justify-content: center;
min-height: 120px;
}
.kpi-value.pending {
font-size: 14px;
font-weight: 400;
}
.figure h3.light {
font-weight: 500;
}
.kpi.closing {
margin-top: 24px;
}
+32 -21
View File
@@ -1,4 +1,5 @@
import { Component, computed, effect, inject, input, resource, signal } from '@angular/core'; import { Component, computed, effect, inject, input, resource, signal } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatButtonToggleModule } from '@angular/material/button-toggle';
@@ -9,14 +10,15 @@ import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot'; import { Figure, Plot } from '../plot';
import { LAYOUTS } from './layout'; import { LAYOUTS } from './layout';
import { import {
FigureSpec, boxFigure,
fill,
nestedDonut, nestedDonut,
PAGES,
rateDots, rateDots,
routeFigure, routeFigure,
scenarioBars, scenarioBars,
Section, shareDonut,
} from './pages'; } from './figures';
import { FigureSpec, Kpi, PAGES, Section } from './pages';
import { import {
detail, detail,
donut, donut,
@@ -41,6 +43,7 @@ import { Loading } from '../loading';
imports: [ imports: [
Loading, Loading,
FormsModule, FormsModule,
NgTemplateOutlet,
MatButtonModule, MatButtonModule,
MatButtonToggleModule, MatButtonToggleModule,
MatCardModule, MatCardModule,
@@ -65,6 +68,8 @@ export class TabIndicadores {
protected readonly layout = computed( protected readonly layout = computed(
() => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' }, () => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' },
); );
protected readonly pending =
'Este indicador aún no está publicado por el catálogo institucional.';
/** The old app's page for this domain, when it is rebuilt as it was (else today's). */ /** The old app's page for this domain, when it is rebuilt as it was (else today's). */
protected readonly page = computed(() => PAGES[this.domain()]); protected readonly page = computed(() => PAGES[this.domain()]);
private readonly byName = computed(() => new Map(this.measures().map((m) => [m.name!, m]))); private readonly byName = computed(() => new Map(this.measures().map((m) => [m.name!, m])));
@@ -189,25 +194,29 @@ export class TabIndicadores {
protected kpi(code: string): Measure | undefined { protected kpi(code: string): Measure | undefined {
return this.byName().get(code); return this.byName().get(code);
} }
/** A KPI card's value as the old cards wrote it. */ /** A card's value and note, from its templates (a card with no measure: its words). */
protected kpiValue(code: string): string { protected kpiValue(k: Kpi): string {
const m = this.kpi(code); if (!k.measure) return k.value ?? '';
const r = this.rd(code); const r = this.rd(k.measure);
if (!m || !r || r.score === undefined) return ''; return r && r.score !== undefined && k.value ? fill(k.value, r) : '';
if (scoring(m) === 'continuous-variable') return `${Math.round(r.score)} días (mediana)`;
if (scoring(m) === 'proportion') return `${(r.score * 100).toFixed(1)} %`;
const n = r.populations['initial-population'] ?? 0;
return `${n.toLocaleString('es-MX')} pacientes`;
} }
protected kpiNote(code: string, note?: string): string { protected kpiNote(k: Kpi): string {
const m = this.kpi(code); if (!k.measure) return k.note ?? '';
const r = this.rd(code); const r = this.rd(k.measure);
if (!m || !r || r.score === undefined) return 'Sin valor disponible'; if (!r || r.score === undefined) return 'Sin valor disponible';
if (scoring(m) === 'continuous-variable') { return k.note ? fill(k.note, r) : '';
const n = (r.populations['measure-observation'] ?? 0).toLocaleString('es-MX');
return `${n} citologías; primer cuartil: ${Math.round(r.low ?? r.score)} días; tercer cuartil: ${Math.round(r.high ?? r.score)} días.`;
} }
return note ?? detail(m, r); /** A figure's title, with the applied period in it. */
protected titled(title: string): string {
return title.replace('{p}', this.applied() ?? '');
}
/** A duration's box, or nothing to draw. */
protected boxOf(measure: string | undefined): Figure | undefined {
const r = measure ? this.rd(measure) : undefined;
return r && r.score !== undefined ? boxFigure(r, this.applied() ?? '') : undefined;
}
protected measureTitle(code: string | undefined): string {
return (code && this.byName().get(code)?.title) || '';
} }
/** A clinical section's route or figures, drawn from the applied period's reports. */ /** A clinical section's route or figures, drawn from the applied period's reports. */
protected routeOf(section: Section): Figure | undefined { protected routeOf(section: Section): Figure | undefined {
@@ -221,6 +230,8 @@ export class TabIndicadores {
switch (spec.kind) { switch (spec.kind) {
case 'donut': case 'donut':
return nestedDonut(r, spec.catalog, spec.center); return nestedDonut(r, spec.catalog, spec.center);
case 'share-donut':
return shareDonut(r, spec.catalog, spec.center);
case 'scenario-bars': case 'scenario-bars':
return scenarioBars(r, spec.catalog, spec.stratum, name); return scenarioBars(r, spec.catalog, spec.stratum, name);
case 'rates': case 'rates':