From 9a15ac6fcb70e6372d8cee651b679dd690ce2ab9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?= Date: Sat, 28 Nov 2026 10:03:31 -0600 Subject: [PATCH] CaCu Indicadores as the old page: its cards and words, the route, cytology and biopsy donuts, results by clinical scenario, confirmation rates; the page test compares with the capture; the guard injects before it waits --- e2e/pages.spec.ts | 47 ++- src/app/auth/auth.ts | 5 +- src/app/indicadores/indicadores.ts | 26 +- src/app/indicadores/measures.ts | 10 +- src/app/indicadores/pages.ts | 385 +++++++++++++++++++++++ src/app/indicadores/tab-indicadores.html | 162 +++++++--- src/app/indicadores/tab-indicadores.scss | 91 ++++++ src/app/indicadores/tab-indicadores.ts | 61 +++- 8 files changed, 720 insertions(+), 67 deletions(-) create mode 100644 src/app/indicadores/pages.ts diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index f6d3651..bc316fa 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -1,3 +1,4 @@ +import { readFileSync } from 'node:fs'; import { expect, Page, test } from '@playwright/test'; /** Every page loads from the API with no failed request and no console error. */ @@ -12,7 +13,7 @@ function watch(page: Page): string[] { // The pages show only to someone signed in (the API itself answers everyone). test.beforeEach(async ({ page }) => { const signed = await page.request.post('/api/auth/login', { - form: { username: 'admin@isssteleon.test', password: 'solo-para-pruebas' }, + form: { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' }, }); expect(signed.status()).toBe(204); }); @@ -22,7 +23,7 @@ test('login: the pages wait for a sign-in, and a wrong password says so', async await page.goto('/conectar'); await expect(page).toHaveURL(/\/login\?next=%2Fconectar/); await expect(page.getByRole('heading', { name: 'Inicio de sesión' })).toBeVisible(); - await page.getByRole('textbox', { name: 'Usuario' }).fill('admin@isssteleon.test'); + await page.getByRole('textbox', { name: 'Usuario' }).fill('admin@isssteleon.mx'); await page.getByRole('textbox', { name: 'Contraseña' }).fill('otra'); await page.getByRole('button', { name: 'Ingresar' }).click(); await expect(page.getByText('Usuario o contraseña incorrectos.')).toBeVisible(); @@ -80,7 +81,7 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie await page.goto('/indicadores/cama'); await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible(); - await page.getByRole('tab', { name: 'Seguimiento' }).click(); + await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.locator('mat-form-field', { hasText: 'Ventana' }).click(); await page.getByRole('option', { name: '12 meses' }).click(); const camaRows = page.locator('table.worklist tbody tr'); @@ -178,3 +179,43 @@ test('conectar: someone who knows nothing of databases connects the SQL Server w await expect(page.getByText('Versión 1 guardada.')).toBeVisible(); expect(problems).toEqual([]); }); + +/** The old app's Indicadores tab as captured (tools/capture_pages.py): its headings from the + * opportunity section on, in order, and the kind of each plot (its traces' types). */ +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)); +} +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']) { + test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({ + page, + }) => { + const old = captured(domain); + await page.goto(`/indicadores/${domain}`); + const tab = page.locator('app-tab-indicadores'); + await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible(); + await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 }); + const headings = await tab + .locator('h2, h3') + .evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim())); + const from = headings.indexOf('Indicadores de oportunidad'); + expect(headings.slice(from).map(period)).toEqual( + old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)), + ); + // Each figure drawn is one of the old kinds (a figure with no data in the period is named). + const drawn = await tab + .locator('.js-plotly-plot') + .evaluateAll((els) => + els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')), + ); + const kinds = new Set( + old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))), + ); + for (const types of drawn) expect(kinds).toContain(kindOf(types)); + }); +} diff --git a/src/app/auth/auth.ts b/src/app/auth/auth.ts index 1e04c52..5050416 100644 --- a/src/app/auth/auth.ts +++ b/src/app/auth/auth.ts @@ -67,10 +67,9 @@ export class Auth { /** Pages show only to someone signed in; the others go to the sign-in page and come back. */ export const signedIn: CanActivateFn = async (_route, state) => { const auth = inject(Auth); + const router = inject(Router); // before any await: inject works only in the guard's first turn const user = auth.user() === undefined ? await auth.load() : auth.user(); - return user - ? true - : inject(Router).createUrlTree(['/login'], { queryParams: { next: state.url } }); + return user ? true : router.createUrlTree(['/login'], { queryParams: { next: state.url } }); }; /** A domain's pages show only to whom may see it. */ diff --git a/src/app/indicadores/indicadores.ts b/src/app/indicadores/indicadores.ts index 0f51870..58ce1ad 100644 --- a/src/app/indicadores/indicadores.ts +++ b/src/app/indicadores/indicadores.ts @@ -25,9 +25,7 @@ import { Loading } from '../loading'; template: `

{{ title() }}

-

- Indicadores de calidad y oportunidad del tamizaje, a partir de los datos cargados. -

+

Explora los indicadores de {{ title().toLowerCase() }}.

@if (measures.isLoading()) { } @else if (measures.error()) { @@ -51,7 +49,7 @@ import { Loading } from '../loading'; } @else if (domain() === 'cama') { - + @@ -70,11 +68,27 @@ import { Loading } from '../loading'; :host { display: block; } + /* As the old page: the domain's name and a line under it, then a white tab bar under + an olive rule. */ h1 { - text-align: center; + font-size: 28px; + font-weight: 500; + margin: 16px 0 8px; } .subtitle { - text-align: center; + font-size: 16px; + margin: 0 0 24px; + } + ::ng-deep .mat-mdc-tab-header { + background: var(--color-surface); + border-top: 2px solid var(--color-primary); + } + ::ng-deep .mat-mdc-tab .mdc-tab__text-label { + font-size: 16px; + font-weight: 400; + } + ::ng-deep .mat-mdc-tab.mdc-tab--active .mdc-tab__text-label { + font-weight: 700; } .empty { padding: 48px 0; diff --git a/src/app/indicadores/measures.ts b/src/app/indicadores/measures.ts index 3c87e87..dd9e47a 100644 --- a/src/app/indicadores/measures.ts +++ b/src/app/indicadores/measures.ts @@ -66,9 +66,15 @@ export function reading(report: MeasureReport | undefined): Reading | undefined const score = group.measureScore; const strata: Reading['strata'] = {}; for (const s of group.stratifier ?? []) { - const name = code(s.code?.[0]) ?? s.code?.[0]?.text ?? ''; + // A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`. + const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-'); strata[name] = Object.fromEntries( - (s.stratum ?? []).map((x) => [x.value?.text ?? '', counts(x)]), + (s.stratum ?? []).map((x) => [ + x.component?.length + ? x.component.map((c) => c.value?.text ?? '').join('|') + : (x.value?.text ?? ''), + counts(x), + ]), ); } return { diff --git a/src/app/indicadores/pages.ts b/src/app/indicadores/pages.ts new file mode 100644 index 0000000..490421e --- /dev/null +++ b/src/app/indicadores/pages.ts @@ -0,0 +1,385 @@ +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 }[]; + clinical: Section[]; + /** The measure whose data decides the default period. */ + anchor: string; +} +export type Section = + | { kind: 'route'; title: string; steps: { label: string; measure: string }[] } + | { kind: 'figures'; title: string; figures: FigureSpec[] }; +export type FigureSpec = + | { kind: 'donut'; title: string; measure: string; catalog: Catalog; center: string } + | { kind: 'scenario-bars'; title: string; measure: string; catalog: Catalog; stratum: string } + | { + kind: 'rates'; + title: string; + measure: string; + stratum: string; + rows: Category[]; + /** the categories (of the measure) that count as a positive */ + positive: string[]; + axis: string; + }; + +export interface Category { + code: string; + label: string; + color: string; + group: string; +} +export interface Catalog { + groups: { id: string; label: string; color: string }[]; + categories: Category[]; + /** categories drawn faded (not the ones the figure is about) */ + faded?: string[]; +} + +const OLIVE = '#A8C243'; +const ROSE = '#C24269'; + +/** Bethesda results as the old app grouped and coloured them. */ +const CYTOLOGY: Catalog = { + groups: [ + { id: 'normal', label: 'Sin anomalía', color: OLIVE }, + { id: 'abnormal', label: 'Anormal', color: ROSE }, + ], + categories: [ + { code: 'NILM', label: 'Normal', color: '#A8C243', group: 'normal' }, + { code: 'ASC-US', label: 'ASC-US', color: '#92324F', group: 'abnormal' }, + { code: 'LSIL', label: 'LIEBG', color: '#AA3A5C', group: 'abnormal' }, + { code: 'ASC-H', label: 'ASC-H', color: '#C24269', group: 'abnormal' }, + { code: 'HSIL', label: 'LIEAG', color: '#C54C71', group: 'abnormal' }, + { code: 'CIS', label: 'Carcinoma in situ', color: '#C9577A', group: 'abnormal' }, + ], +}; + +/** Biopsy grades: below high grade, and high grade or worse (what confirmation counts). */ +const BIOPSY: Catalog = { + groups: [ + { id: 'low', label: 'Menor que LIEAG', color: OLIVE }, + { id: 'high', label: 'LIEAG o más', color: ROSE }, + ], + categories: [ + { code: 'normal', label: 'Normal', color: '#7E9232', group: 'low' }, + { code: 'LSIL', label: 'LIEBG (CIN 1)', color: '#B2C958', group: 'low' }, + { code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: '#92324F', group: 'high' }, + { code: 'CIS', label: 'Carcinoma in situ', color: '#C24269', group: 'high' }, + { code: 'carcinoma', label: 'Carcinoma invasor', color: '#C9577A', group: 'high' }, + ], + faded: ['normal', 'LSIL'], +}; + +export const PAGES: Record = { + cacu: { + anchor: 'CACU_EU7', + kpis: [ + { + measure: 'CACU_EU7', + title: 'Pacientes evaluadas', + 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_DIAS_DIAGNOSTICO_TRATAMIENTO', + title: 'Tiempo de diagnóstico a tratamiento', + }, + ], + clinical: [ + { + kind: 'route', + title: 'Tiempos de la ruta del tamizaje', + steps: [ + { label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' }, + { label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' }, + { label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' }, + { label: 'Diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' }, + ], + }, + { + kind: 'figures', + title: 'Distribución de resultados citológicos', + figures: [ + { + kind: 'donut', + title: 'Distribución de resultados', + measure: 'CACU_EU7', + catalog: CYTOLOGY, + center: 'pacientes', + }, + { + kind: 'scenario-bars', + title: 'TOTAL por escenario clínico', + measure: 'CACU_EU7', + catalog: CYTOLOGY, + stratum: 'follow_up_status', + }, + ], + }, + { + kind: 'figures', + title: 'Tasa de confirmación histopatológica', + figures: [ + { + kind: 'rates', + title: 'Por resultado de la citología', + measure: 'CACU_CONFIRMACION_CITOLOGIA', + stratum: 'result', + rows: CYTOLOGY.categories.filter((c) => ['ASC-H', 'HSIL', 'CIS'].includes(c.code)), + positive: ['HSIL', 'CIS', 'carcinoma'], + axis: 'Verdaderos positivos (valor predictivo positivo)', + }, + { + kind: 'donut', + title: 'Resultado de la biopsia', + measure: 'CACU_CONFIRMACION_CITOLOGIA', + catalog: BIOPSY, + center: 'con biopsia', + }, + ], + }, + ], + }, +}; + +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 017a9da..8ccf2d0 100644 --- a/src/app/indicadores/tab-indicadores.html +++ b/src/app/indicadores/tab-indicadores.html @@ -1,4 +1,5 @@
+

Filtros

Intervalo de análisis Periodo seleccionado @for (p of options(); track p) { - {{ label(p) }} + {{ p }} } @@ -25,65 +26,124 @@ > Aplicar - @if (applied(); as p) { - Mostrando {{ label(p) }} - }
@if (reports.isLoading()) { } -@if (kpis().length) { -

Indicadores de oportunidad

-
- @for (m of kpis(); track m.id) { - +@if (page(); as pg) { + @if (applied(); as period) { +
+
+

Indicadores de oportunidad

+ Periodo {{ period }} +
+
+ @for (k of pg.kpis; track k.measure) { + + +

{{ k.title }}

+ @if (reports.isLoading()) { + + } @else { +
{{ kpiValue(k.measure) }}
+
{{ kpiNote(k.measure, k.note) }}
+ } +
+
+ } +
+
+ +
+

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.

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

Indicadores de oportunidad

+
+ @for (m of kpis(); track m.id) { + + +
{{ m.title }}
+
{{ score(m) }}
+
{{ detail(m) }}
+
+
+ } +
+ } + + @if (layout().route.length) { + + + Ruta del tamizaje + + Acumulado desde la toma + Por pasos + + + + + + + } + +

Indicadores clínicos

+
+ @for (m of clinical(); track m.id) { + + + {{ m.title }} + {{ score(m) }} · {{ detail(m) }} + -
{{ m.title }}
-
{{ score(m) }}
-
{{ detail(m) }}
+ @for (f of figureSets().get(m.name!) ?? []; track f.title) { +

{{ f.title }}

+ + } @empty { +

Sin datos en el periodo.

+ }
}
} - -@if (layout().route.length) { - - - Ruta del tamizaje - - Acumulado desde la toma - Por pasos - - - - - - -} - -

Indicadores clínicos

-
- @for (m of clinical(); track m.id) { - - - {{ m.title }} - {{ score(m) }} · {{ detail(m) }} - - - @for (f of figureSets().get(m.name!) ?? []; track f.title) { -

{{ f.title }}

- - } @empty { -

Sin datos en el periodo.

- } -
-
- } -
diff --git a/src/app/indicadores/tab-indicadores.scss b/src/app/indicadores/tab-indicadores.scss index cdebd88..e8bf85d 100644 --- a/src/app/indicadores/tab-indicadores.scss +++ b/src/app/indicadores/tab-indicadores.scss @@ -97,3 +97,94 @@ h2 { font-weight: 500; margin: var(--space-3) 0 0; } + +/* The old app's page: white sections with a title, cards inside. */ +.card.opportunity, +.card.clinical-page { + background: var(--color-surface); + border: 1px solid var(--color-border); + border-radius: 8px; + margin-bottom: 24px; + padding: 20px; +} + +.section-head { + align-items: baseline; + display: flex; + justify-content: space-between; + + .period { + color: var(--color-text-secondary); + font-size: 12px; + } +} + +.card h2 { + font-size: 20px; + font-weight: 500; + margin: 0 0 20px; +} + +h3.kpi-title { + font-size: 16px; + font-weight: 500; + margin: 0; + min-height: 2.6em; +} + +.kpi-detail { + color: var(--color-text-secondary); +} + +h3.route-title { + font-size: 16px; + font-weight: 700; + margin: 24px 0 8px; +} + +.figure-card { + margin-top: 24px; +} + +h2.figure-card-title { + font-size: 18px; + font-weight: 500; + margin: 0 0 12px; +} + +.figure-row { + display: grid; + gap: 24px; + grid-template-columns: 1fr; +} + +@media (min-width: 1100px) { + .figure-row { + grid-template-columns: 1fr 1fr; + } +} + +.figure h3 { + font-size: 16px; + font-weight: 700; + margin: 0 0 8px; +} + +.state { + color: var(--color-text-secondary); + font-size: 14px; +} + +.filters { + background: var(--color-surface); + border: 1px solid var(--color-border); + border-radius: 8px; + padding: 16px; +} + +h2.filters-title { + flex-basis: 100%; + font-size: 16px; + font-weight: 500; + margin: 0; +} diff --git a/src/app/indicadores/tab-indicadores.ts b/src/app/indicadores/tab-indicadores.ts index c36d9c0..a76f86e 100644 --- a/src/app/indicadores/tab-indicadores.ts +++ b/src/app/indicadores/tab-indicadores.ts @@ -8,6 +8,15 @@ import type { Measure, MeasureReport } from 'fhir/r4'; import { Fhir, resources } from '../fhir'; import { Figure, Plot } from '../plot'; import { LAYOUTS } from './layout'; +import { + FigureSpec, + nestedDonut, + PAGES, + rateDots, + routeFigure, + scenarioBars, + Section, +} from './pages'; import { detail, donut, @@ -56,6 +65,8 @@ export class TabIndicadores { protected readonly layout = computed( () => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' }, ); + /** 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]))); protected readonly kpis = computed(() => this.layout() @@ -74,7 +85,7 @@ export class TabIndicadores { private readonly latest = resource({ params: () => ({ domain: this.domain(), - anchor: this.byName().get(this.layout().anchor) ?? this.measures()[0], + anchor: this.byName().get(this.page()?.anchor ?? this.layout().anchor) ?? this.measures()[0], all: this.options(), }), loader: async ({ params }) => { @@ -156,7 +167,7 @@ export class TabIndicadores { private build(m: Measure, r: Reading | undefined): { title: string; figure: Figure }[] { if (!r || !(r.populations['initial-population'] ?? 0)) return []; const strata = Object.keys(r.strata).filter( - (s) => s !== 'category' && Object.keys(r.strata[s]).length, + (s) => s !== 'category' && !s.includes('-') && Object.keys(r.strata[s]).length, ); const kind = scoring(m); if (kind === 'continuous-variable') @@ -170,4 +181,50 @@ export class TabIndicadores { ]; } protected readonly name = name; + + /** A measure's reading in the applied period, by code. */ + protected rd(code: string): Reading | undefined { + return this.reports.value()?.get(code); + } + 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`; + } + 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); + } + /** A clinical section's route or figures, drawn from the applied period's reports. */ + protected routeOf(section: Section): Figure | undefined { + if (section.kind !== 'route') return undefined; + const steps = section.steps.map((s) => ({ label: s.label, r: this.rd(s.measure) })); + return steps.some((s) => s.r?.score !== undefined) ? routeFigure(steps) : undefined; + } + protected figureOf(spec: FigureSpec): Figure | undefined { + const r = this.rd(spec.measure); + if (!r || !(r.populations['initial-population'] ?? 0)) return undefined; + switch (spec.kind) { + case 'donut': + return nestedDonut(r, spec.catalog, spec.center); + case 'scenario-bars': + return scenarioBars(r, spec.catalog, spec.stratum, name); + case 'rates': + return rateDots(r, spec); + } + } }