diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index bc316fa..21b5010 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -186,12 +186,15 @@ function captured(domain: string) { const path = `../tests/fixtures/reference/${domain}/ui/pages.json`; const items = JSON.parse(readFileSync(path, 'utf8')).tabs['Indicadores'] as any[]; 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})$/, ', '); 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 ({ page, }) => { diff --git a/src/app/indicadores/figures.ts b/src/app/indicadores/figures.ts new file mode 100644 index 0000000..de4690b --- /dev/null +++ b/src/app/indicadores/figures.ts @@ -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}
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}
mediana %{x} días', + } as Partial, + ], + 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: [`${count(total)}
${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}
${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}
%{value} (%{percent})', + }, + { + ...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}
%{value} (%{percent})', + }, + ] as Partial[], + 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}
%{y}: %{customdata} (%{x:.1f} %)`, + })) as Partial[], + 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} %', + } as Partial, + ], + 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 + ? `${percent(x.rate!)} %
${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 = { + 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`, + } as Partial, + ], + 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}
%{percent}' : '')), + textposition: 'outside', + hovertemplate: '%{label}
%{value} (%{percent})', + } as Partial, + ], + layout: { + showlegend: false, + margin: { t: 30, l: 60, r: 60, b: 30 }, + annotations: [ + { + text: `${count(total)}
${center}`, + showarrow: false, + x: 0.5, + y: 0.5, + xref: 'paper', + yref: 'paper', + }, + ], + }, + }; +} diff --git a/src/app/indicadores/pages.ts b/src/app/indicadores/pages.ts index 490421e..9e75e3e 100644 --- a/src/app/indicadores/pages.ts +++ b/src/app/indicadores/pages.ts @@ -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//ui): * the timeliness cards with their own words, then the clinical sections and their figures. * Measures are named by their code (`Measure.name`). */ 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[]; /** The measure whose data decides the default period. */ 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 = | { 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 = - | { 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: 'rates'; @@ -22,6 +38,8 @@ export type FigureSpec = measure: string; stratum: string; rows: Category[]; + /** each row in its category's colour (else all rose) */ + colored?: boolean; /** the categories (of the measure) that count as a positive */ positive: string[]; axis: string; @@ -75,21 +93,171 @@ const BIOPSY: Catalog = { 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 = { + 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: { anchor: 'CACU_EU7', kpis: [ { measure: 'CACU_EU7', title: 'Pacientes evaluadas', + value: '{n} pacientes', 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_DIAS_TOMA_TRATAMIENTO', title: 'Tiempo de tamizaje a tratamiento' }, + { + measure: 'CACU_EU_TIEMPO_REPORTE', + 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', title: 'Tiempo de diagnóstico a tratamiento', + ...CACU_DAYS, }, ], clinical: [ @@ -109,14 +277,14 @@ export const PAGES: Record = { figures: [ { kind: 'donut', - title: 'Distribución de resultados', + title: 'Distribución de resultados, {p}', measure: 'CACU_EU7', catalog: CYTOLOGY, center: 'pacientes', }, { kind: 'scenario-bars', - title: 'TOTAL por escenario clínico', + title: 'TOTAL por escenario clínico, {p}', measure: 'CACU_EU7', catalog: CYTOLOGY, stratum: 'follow_up_status', @@ -129,7 +297,7 @@ export const PAGES: Record = { figures: [ { kind: 'rates', - title: 'Por resultado de la citología', + title: 'Por resultado de la citología, {p}', measure: 'CACU_CONFIRMACION_CITOLOGIA', stratum: 'result', rows: CYTOLOGY.categories.filter((c) => ['ASC-H', 'HSIL', 'CIS'].includes(c.code)), @@ -138,7 +306,7 @@ export const PAGES: Record = { }, { kind: 'donut', - title: 'Resultado de la biopsia', + title: 'Resultado de la biopsia, {p}', measure: 'CACU_CONFIRMACION_CITOLOGIA', catalog: BIOPSY, center: 'con biopsia', @@ -148,238 +316,3 @@ export const PAGES: Record = { ], }, }; - -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}
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}
mediana %{x} días', - } as Partial, - ], - 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: [`${count(total)}
${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}
${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}
%{value} (%{percent})', - }, - { - ...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}
%{value} (%{percent})', - }, - ] as Partial[], - 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}
%{y}: %{customdata} (%{x:.1f} %)`, - })) as Partial[], - 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} %', - } as Partial, - ], - 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 ? `${percent(x.rate!)} %
${x.k}/${x.den}` : 'Sin biopsias', - })), - }, - }; -} diff --git a/src/app/indicadores/tab-indicadores.html b/src/app/indicadores/tab-indicadores.html index 8ccf2d0..f52e2a9 100644 --- a/src/app/indicadores/tab-indicadores.html +++ b/src/app/indicadores/tab-indicadores.html @@ -40,58 +40,114 @@ Periodo {{ period }}
- @for (k of pg.kpis; track k.measure) { - + @for (k of pg.kpis; track k.title) { +

{{ k.title }}

- @if (reports.isLoading()) { + @if (reports.isLoading() && k.measure) { } @else { -
{{ kpiValue(k.measure) }}
-
{{ kpiNote(k.measure, k.note) }}
+
{{ kpiValue(k) }}
+
{{ kpiNote(k) }}
}
}
+ @for (section of pg.opportunity ?? []; track $index) { + + }

Indicadores clínicos

- @for (section of pg.clinical; track section.title) { - @if (section.kind === 'route') { -

{{ section.title }}

- @if (reports.isLoading()) { - - } @else if (routeOf(section); as fig) { - - } @else { -

Sin tiempos publicados en el periodo.

- } - } @else { - - -

{{ section.title }}

-
- @for (f of section.figures; track f.title) { -
-

{{ f.title }}, {{ period }}

- @if (reports.isLoading()) { - - } @else if (figureOf(f); as fig) { - - } @else { -

Sin datos en el periodo.

- } -
- } -
-
-
- } + @for (section of pg.clinical; track $index) { + }
} + + + @switch (section.kind) { + @case ('route') { +

{{ section.title }}

+ @if (reports.isLoading()) { + + } @else if (routeOf(section); as fig) { + + } @else { +

Sin tiempos publicados en el periodo.

+ } + } + @case ('boxes') { +

{{ section.title }}

+
+ @for (b of section.cards; track b.title) { + + +

{{ b.title }}

+ @if (!b.measure) { +

Integración pendiente. {{ pending }}

+
Sin datos publicados
+ } @else { +

Filtro general aplicado: {{ period }}

+

{{ measureTitle(b.measure) }}

+

Figura: Caja de cuartiles

+ @if (reports.isLoading()) { + + } @else if (boxOf(b.measure); as fig) { + + } @else { +
Sin datos publicados
+ } + } +
+
+ } +
+ } + @case ('card') { + + +

{{ section.title }}

+
{{ kpiValue(section) }}
+
{{ kpiNote(section) }}
+
+
+ } + @default { + + + @if (section.title) { +

{{ section.title }}

+ } +
+ @for (f of section.figures; track f.title) { +
+

{{ titled(f.title) }}

+ @if (reports.isLoading()) { + + } @else if (figureOf(f); as fig) { + + } @else { +

Sin datos en el periodo.

+ } +
+ } +
+
+
+ } + } +
} @else { @if (kpis().length) {

Indicadores de oportunidad

diff --git a/src/app/indicadores/tab-indicadores.scss b/src/app/indicadores/tab-indicadores.scss index e8bf85d..dc3d8b7 100644 --- a/src/app/indicadores/tab-indicadores.scss +++ b/src/app/indicadores/tab-indicadores.scss @@ -188,3 +188,56 @@ h2.filters-title { font-weight: 500; 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; +} diff --git a/src/app/indicadores/tab-indicadores.ts b/src/app/indicadores/tab-indicadores.ts index a76f86e..f2aacd9 100644 --- a/src/app/indicadores/tab-indicadores.ts +++ b/src/app/indicadores/tab-indicadores.ts @@ -1,4 +1,5 @@ import { Component, computed, effect, inject, input, resource, signal } from '@angular/core'; +import { NgTemplateOutlet } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; @@ -9,14 +10,15 @@ import { Fhir, resources } from '../fhir'; import { Figure, Plot } from '../plot'; import { LAYOUTS } from './layout'; import { - FigureSpec, + boxFigure, + fill, nestedDonut, - PAGES, rateDots, routeFigure, scenarioBars, - Section, -} from './pages'; + shareDonut, +} from './figures'; +import { FigureSpec, Kpi, PAGES, Section } from './pages'; import { detail, donut, @@ -41,6 +43,7 @@ import { Loading } from '../loading'; imports: [ Loading, FormsModule, + NgTemplateOutlet, MatButtonModule, MatButtonToggleModule, MatCardModule, @@ -65,6 +68,8 @@ export class TabIndicadores { protected readonly layout = computed( () => 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). */ protected readonly page = computed(() => PAGES[this.domain()]); 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 { return this.byName().get(code); } - /** A KPI card's value as the old cards wrote it. */ - protected kpiValue(code: string): string { - const m = this.kpi(code); - const r = this.rd(code); - if (!m || !r || r.score === undefined) return ''; - 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`; + /** A card's value and note, from its templates (a card with no measure: its words). */ + protected kpiValue(k: Kpi): string { + if (!k.measure) return k.value ?? ''; + const r = this.rd(k.measure); + return r && r.score !== undefined && k.value ? fill(k.value, r) : ''; } - protected kpiNote(code: string, note?: string): string { - const m = this.kpi(code); - const r = this.rd(code); - if (!m || !r || r.score === undefined) return 'Sin valor disponible'; - if (scoring(m) === 'continuous-variable') { - 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); + protected kpiNote(k: Kpi): string { + if (!k.measure) return k.note ?? ''; + const r = this.rd(k.measure); + if (!r || r.score === undefined) return 'Sin valor disponible'; + return k.note ? fill(k.note, 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. */ protected routeOf(section: Section): Figure | undefined { @@ -221,6 +230,8 @@ export class TabIndicadores { switch (spec.kind) { case 'donut': return nestedDonut(r, spec.catalog, spec.center); + case 'share-donut': + return shareDonut(r, spec.catalog, spec.center); case 'scenario-bars': return scenarioBars(r, spec.catalog, spec.stratum, name); case 'rates':