Compare commits

..

1 Commits

Author SHA1 Message Date
Angel Capetillo Zavala 81894a3777 CaCu: show screening rounds and restore category palettes 2026-12-01 14:22:23 -06:00
18 changed files with 988 additions and 818 deletions
+162 -1
View File
@@ -1,4 +1,6 @@
import { expect, test } from '@playwright/test'; import { expect, type Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
import { type Simulation, simulateRounds } from './simulated-rounds';
test.beforeEach(async ({ page }) => { test.beforeEach(async ({ page }) => {
const form = { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' }; const form = { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' };
@@ -34,7 +36,41 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')), route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
).toBeVisible(); ).toBeVisible();
} }
// the screening round replaces the clinical scenario: the same tab, label and order on four cards
const round = { name: 'Por detección inicial y subsecuente' };
await expect(tab.getByRole('radio', { name: 'Por escenario clínico' })).toHaveCount(0);
for (const card of [
'Distribución de resultados citológicos',
'Pacientes evaluadas por resultado de VPH',
'Valor predictivo positivo de la colposcopía',
]) {
const readings = tab.locator('app-readings', {
has: page.getByRole('heading', { name: card }),
});
await readings.getByRole('radio', round).click();
// rows in the order of the contract, "no disponible", or no patients in the period
await expect(
readings
.getByRole('table', round)
.or(readings.locator('app-plot'))
.or(readings.getByText(/No disponible|Sin datos en el periodo/)),
).toBeVisible();
if (await readings.getByRole('table', round).count()) {
const labels = await readings.getByRole('rowheader').allInnerTexts();
expect(labels.map((l) => l.trim().split(/\s{2,}|\n/)[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
}
}
await tab.getByRole('radio', { name: 'Biopsia', exact: true }).click(); await tab.getByRole('radio', { name: 'Biopsia', exact: true }).click();
await tab
.locator('app-readings', {
has: page.getByRole('heading', { name: 'Valor predictivo positivo de la biopsia' }),
})
.getByRole('radio', round)
.click();
await expect( await expect(
tab.getByRole('heading', { name: 'Valor predictivo positivo de la biopsia' }), tab.getByRole('heading', { name: 'Valor predictivo positivo de la biopsia' }),
).toBeVisible(); ).toBeVisible();
@@ -67,3 +103,128 @@ test('riesgos cacu: ages filter the whole list and a row opens its stages', asyn
await page.getByRole('button', { name: 'Exportar PDF' }).click(); await page.getByRole('button', { name: 'Exportar PDF' }).click();
expect((await record).suggestedFilename()).toBe('expediente-cacu.pdf'); expect((await record).suggestedFilename()).toBe('expediente-cacu.pdf');
}); });
// ---- Screening rounds on SIMULATED answers (see simulated-rounds.ts): the groups the contract of
// `rebuild` allows, tried without loading data. They show how the page draws them, not the backend.
const ROUND = { name: 'Por detección inicial y subsecuente' };
const TITLES = {
cytology: 'Distribución de resultados citológicos',
vph: 'Pacientes evaluadas por resultado de VPH',
colposcopy: 'Valor predictivo positivo de la colposcopía',
biopsy: 'Valor predictivo positivo de la biopsia',
};
const BAR = {
initial: 'rgb(95, 127, 154)',
subsequent: 'rgb(143, 167, 187)',
no_data: 'rgb(201, 205, 210)',
};
async function withRounds(page: Page, how: Simulation) {
await simulateRounds(page, how);
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible({
timeout: 3 * 60_000,
});
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const card = (title: string) =>
tab.locator('app-readings', { has: page.getByRole('heading', { name: title }) }).first();
const open = async (key: keyof typeof TITLES) => {
if (key === 'biopsy') await tab.getByRole('radio', { name: 'Biopsia', exact: true }).click();
if (key === 'colposcopy')
await tab.getByRole('radio', { name: 'Colposcopía', exact: true }).click();
const readings = card(TITLES[key]);
await readings.getByRole('radio', ROUND).click();
return readings;
};
return { tab, open };
}
for (const key of ['vph', 'colposcopy', 'biopsy'] as const) {
test(`rondas (simulado) ${key}: three groups in order, each with its own colour`, async ({
page,
}) => {
const { open } = await withRounds(page, 'as-is');
const readings = await open(key);
const rows = readings.getByRole('row').filter({ has: page.getByRole('rowheader') });
await expect(rows).toHaveCount(3);
const names = await readings.getByRole('rowheader').allInnerTexts();
expect(names.map((n) => n.trim().split(/\s*\n\s*/)[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
const colours = await readings
.locator('tbody .bar')
.evaluateAll((els) => els.map((e) => getComputedStyle(e).backgroundColor));
expect(colours).toEqual([BAR.initial, BAR.subsequent, BAR.no_data]);
});
test(`rondas (simulado) ${key}: an empty initial group is zero patients, not hidden`, async ({
page,
}) => {
const { open } = await withRounds(page, 'no-initial');
const readings = await open(key);
const initial = readings.getByRole('row').filter({ hasText: 'Detección inicial' });
await expect(initial).toContainText('Sin pacientes en el periodo');
await expect(initial).toContainText('0/0');
});
test(`rondas (simulado) ${key}: without the stratum the card says it is not available`, async ({
page,
}) => {
const { open } = await withRounds(page, 'unpublished');
const readings = await open(key);
await expect(readings).toContainText('No disponible');
await expect(readings.getByRole('table', ROUND)).toHaveCount(0);
});
}
test('rondas (simulado) cytology: the bars follow the round and the cytology colours', async ({
page,
}) => {
const { open } = await withRounds(page, 'as-is');
const readings = await open('cytology');
const plot = readings.locator('.js-plotly-plot');
await expect(plot).toBeVisible();
const { y, colours } = await plot.evaluate((e: any) => ({
y: e.data[0].y as string[],
colours: Object.fromEntries(e.data.map((t: any) => [t.name, t.marker.color])),
}));
expect(y.map((s) => s.split('<br>')[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
expect(colours).toMatchObject({
Normal: '#408651',
'ASC-US': '#2778B8',
LIEBG: '#B19525',
'ASC-H': '#7955B1',
LIEAG: '#CE4778',
'Carcinoma in situ': '#AA394D',
});
});
test('rondas (simulado): an initial group folded into "Sin dato" keeps its counts there', async ({
page,
}) => {
const { open } = await withRounds(page, 'unclassified');
const readings = await open('vph');
const rows = readings.getByRole('row').filter({ has: page.getByRole('rowheader') });
await expect(rows.filter({ hasText: 'Detección inicial' })).toContainText('0/0');
await expect(rows.filter({ hasText: 'Sin dato' })).not.toContainText('0/0');
await expect(readings).toContainText('una categoría en cero significa');
});
for (const width of [1440, 480]) {
test(`rondas (simulado) at ${width} px: the four cards open on their rounds lay out cleanly`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { open } = await withRounds(page, 'as-is');
for (const key of ['cytology', 'vph', 'colposcopy', 'biopsy'] as const) await open(key);
await page.waitForTimeout(1500);
expect(await layoutProblems(page)).toEqual([]);
});
}
+1 -23
View File
@@ -210,29 +210,7 @@ for (const domain of ['cama', 'tea']) {
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,
}) => { }) => {
const all = captured(domain); const old = captured(domain);
// CaMa's five timeliness boxes are one route card now: its heading stands for them.
const route = all.findIndex(
(i) => i.kind === 'h3' && i.text === 'Tiempo de tamizaje a diagnóstico',
);
const clinical = all.findIndex((i) => i.text === 'Indicadores clínicos');
// Lote 2: the detection rate has its own title, and the histopathology figures are two
// cards (the result by BI-RADS; the confirmation in two readings).
const detection = (i: { text?: string }) =>
i.text === 'Tasa de confirmación histopatológica'
? { ...i, text: 'Tasa de detección histopatológica' }
: i;
const results = all.findIndex(
(i) => i.text === 'Resultado histopatológico por categoría BI-RADS',
);
const cards = [
{ kind: 'h3', text: 'Resultado histopatológico por categoría BI-RADS' },
{ kind: 'h3', text: 'Confirmación histopatológica' }, // one card: title, tabs and reading
];
const old =
domain === 'cama'
? [...all.slice(0, route + 1).map(detection), ...all.slice(clinical, results), ...cards]
: all;
await page.goto(`/indicadores/${domain}`); await page.goto(`/indicadores/${domain}`);
const tab = page.locator('app-tab-indicadores'); const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible(); await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
+88
View File
@@ -0,0 +1,88 @@
import type { Page } from '@playwright/test';
/** SIMULATED answers. The pages read the API's aggregated MeasureReports; these helpers pass them
* through the browser and rewrite the screening-round strata, so the cards can be tried with the
* groups the contract of `rebuild` allows (stratum `round`, crossed `round-category`) without
* loading data. They prove how the page draws such answers, not what the backend computes.
*
* - `as-is`: the answers untouched, but the old candidate's `screening_round` is named `round`.
* - `no-initial`: nobody is in the initial group (the group is absent and the totals drop).
* - `unclassified`: the initial group folds into "Sin dato" (what 5740's answers look like).
* - `unpublished`: the round strata are not in the answers. */
export type Simulation = 'as-is' | 'no-initial' | 'unclassified' | 'unpublished';
type Stratum = {
value?: { text?: string };
component?: { value?: { text?: string } }[];
population?: { code?: { coding?: { code?: string }[] }; count: number }[];
};
type Stratifier = { code?: { coding?: { code?: string }[] }[]; stratum?: Stratum[] };
const named = (s: Stratifier) => (s.code ?? []).map((c) => c.coding?.[0]?.code).join('-');
const label = (x: Stratum) => x.component?.[0]?.value?.text ?? x.value?.text;
const pop = (o: { population?: Stratum['population'] }, code: string) =>
o.population?.find((p) => p.code?.coding?.[0]?.code === code);
function fold(into: Stratum, from: Stratum) {
for (const p of from.population ?? []) {
const q = pop(into, p.code!.coding![0].code!);
if (q) q.count += p.count;
else (into.population ??= []).push(structuredClone(p));
}
}
export function simulate(report: any, how: Simulation) {
const group = report?.group?.[0];
if (!group) return report;
for (const s of group.stratifier ?? ([] as Stratifier[]))
for (const c of s.code ?? []) {
const k = c.coding?.[0];
if (k?.code === 'screening_round') k.code = 'round';
}
const rounds: Stratifier[] = (group.stratifier ?? []).filter((s: Stratifier) =>
['round', 'round-category'].includes(named(s)),
);
if (how === 'unpublished')
group.stratifier = (group.stratifier ?? []).filter((s: Stratifier) => !rounds.includes(s));
if (how === 'no-initial' || how === 'unclassified')
for (const s of rounds) {
const initial = (s.stratum ?? []).filter((x) => label(x) === 'initial');
const rest = (s.stratum ?? []).filter((x) => label(x) !== 'initial');
for (const x of initial) {
if (how === 'unclassified') {
const other = x.component?.[1]?.value?.text;
const target = rest.find(
(y) => label(y) === 'no_data' && (!other || y.component?.[1]?.value?.text === other),
);
if (target) fold(target, x);
else {
(x.component ? x.component[0].value! : x.value!).text = 'no_data';
rest.push(x);
}
} else if (named(s) === 'round') {
// the group vanishes and the period's total drops by its patients: a real zero
for (const p of x.population ?? []) {
const total = pop(group, p.code!.coding![0].code!);
if (total && p.code!.coding![0].code !== 'numerator')
total.count = Math.max(0, total.count - p.count);
}
}
}
s.stratum = rest;
}
return report;
}
/** Answers every CaCu MeasureReport search through `simulate`. */
export async function simulateRounds(page: Page, how: Simulation) {
await page.route('**/api/cacu/fhir/MeasureReport**', async (route) => {
const response = await route.fetch();
const body = await response.json();
for (const entry of body.entry ?? []) simulate(entry.resource, how);
await route.fulfill({
response,
body: JSON.stringify(body),
contentType: 'application/fhir+json',
});
});
}
+140 -84
View File
@@ -1,4 +1,5 @@
import { bars } from './bars'; import { bars, unavailable } from './bars';
import { scenarioBars } from './figures';
import { Reading } from './measures'; import { Reading } from './measures';
describe('bars', () => { describe('bars', () => {
@@ -24,91 +25,146 @@ describe('bars', () => {
const mode = { kind: 'shares', label: 'x', measure: 'M', stratum: 's', order: ['initial'] }; const mode = { kind: 'shares', label: 'x', measure: 'M', stratum: 's', order: ['initial'] };
expect(bars(mode as any, () => r)!.rows[0].cells).toEqual(['0/0', '—']); expect(bars(mode as any, () => r)!.rows[0].cells).toEqual(['0/0', '—']);
}); });
it('a proportion split into its parts shows both in units and shares', () => {
const r: Reading = { populations: { numerator: 1, denominator: 4 }, strata: {} }; describe('screening rounds (complete)', () => {
const t = bars({ kind: 'split', label: 'x', measure: 'M', yes: 'Con', no: 'Sin' }, () => r)!; const ORDER = ['initial', 'subsequent', 'no_data'];
expect(t.rows.map((x) => [x.label, ...x.cells])).toEqual([ const cell = (numerator: number, denominator: number) => ({ numerator, denominator });
['Con', '1', '25.0 %'], const ppv = (strata: Record<string, any>, total: number): Reading => ({
['Sin', '3', '75.0 %'], populations: { 'initial-population': total, denominator: total },
]); strata: { round: strata },
});
const mode = {
kind: 'shares',
label: 'x',
measure: 'M',
stratum: 'round',
order: ORDER,
complete: true,
} as const;
it('lists the three groups in order with their own counts', () => {
const r = ppv({ no_data: cell(1, 4), subsequent: cell(6, 10), initial: cell(0, 6) }, 20);
const t = bars(mode, () => r)!;
expect(t.rows.map((x) => x.label)).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
expect(t.rows.map((x) => x.cells)).toEqual([
['0/6', '0.0 %'],
['6/10', '60.0 %'],
['1/4', '25.0 %'],
]);
expect(t.note).toBeUndefined();
});
it('a group the report leaves out is zero patients when the counts add up', () => {
const r = ppv({ no_data: cell(0, 3), subsequent: cell(6, 10) }, 13);
const initial = bars(mode, () => r)!.rows[0];
expect(initial.cells).toEqual(['0/0', '—']);
expect(initial.hint).toBe('Sin pacientes en el periodo');
});
it('a group left out is not available when the counts do not add up', () => {
const r = ppv({ subsequent: cell(6, 10) }, 13);
const t = bars(mode, () => r)!;
expect(t.rows[0].cells).toEqual(['—', '—']);
expect(t.rows[0].hint).toBe('No disponible');
expect(t.note).toContain('no concilian');
});
it('a zero numerator over a positive denominator is 0 %, a zero denominator has no rate', () => {
const r = ppv({ initial: cell(0, 5), subsequent: cell(0, 0), no_data: cell(2, 3) }, 8);
const t = bars(mode, () => r)!;
expect(t.rows[0].cells).toEqual(['0/5', '0.0 %']);
expect(t.rows[1].cells).toEqual(['0/0', '—']);
expect(t.rows[1].hint).toBe('Sin pacientes en el periodo');
});
it('warns when only "Sin dato" holds patients', () => {
const r = ppv({ no_data: cell(3, 7) }, 7);
const t = bars(mode, () => r)!;
expect(t.rows[2].cells).toEqual(['3/7', '42.9 %']);
expect(t.note).toContain('información no registrada');
});
it('draws nothing without patients and says "No disponible" without the stratifier', () => {
expect(bars(mode, () => ppv({}, 0))).toBeUndefined();
expect(unavailable(mode, () => ppv({}, 0))).toBeUndefined();
expect(unavailable(mode, () => ppv({}, 9))).toContain('No disponible');
expect(bars(mode, () => ppv({}, 9))).toBeUndefined();
});
it('a cell that is not whole or has a numerator above its denominator is not available', () => {
const r = ppv({ initial: cell(5, 3), subsequent: cell(1, 2), no_data: cell(0, 1) }, 6);
expect(bars(mode, () => r)!.rows[0].hint).toBe('No disponible');
});
it('VPH positives: groups from the crossed cells, absent ones reconciled', () => {
const r: Reading = {
populations: { 'initial-population': 12 },
strata: {
'round-category': {
'subsequent|positive': { 'initial-population': 3 },
'subsequent|negative': { 'initial-population': 7 },
'no_data|negative': { 'initial-population': 2 },
},
},
};
const t = bars(
{
kind: 'positives',
label: 'x',
measure: 'M',
stratum: 'round',
order: ORDER,
complete: true,
},
() => r,
)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['0/0', '—'],
['3/10', '30.0 %'],
['0/2', '0.0 %'],
]);
});
}); });
it('rows with patients and no biopsy are not rows with no patients; malignant counts only graded', () => {
const r: Reading = { describe('cytology by round', () => {
populations: {}, const cats = [
{ code: 'NILM', label: 'Normal', color: '#0a0', group: '' },
{ code: 'HSIL', label: 'LIEAG', color: '#a00', group: '' },
];
const reading = (cells: Record<string, number>, total: number): Reading => ({
populations: { 'initial-population': total },
strata: { strata: {
birads: { 'round-category': Object.fromEntries(
'4A': { 'initial-population': 3 }, Object.entries(cells).map(([k, n]) => [k, { 'initial-population': n }]),
'5': { 'initial-population': 4 }, ),
'6': { 'initial-population': 2 },
},
'birads-category': {
'4A|no_biopsy': { 'initial-population': 3 },
'5|benign': { 'initial-population': 1 },
'5|invasive': { 'initial-population': 1 },
'5|no_data': { 'initial-population': 2 },
'6|no_data': { 'initial-population': 2 },
},
}, },
}; });
const results = [ const draw = (r: Reading) =>
{ code: 'benign', label: 'Benigno', color: '#1' }, scenarioBars(
{ code: 'invasive', label: 'Invasor', color: '#2' }, r,
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#3' }, { groups: [], categories: cats },
{ code: 'no_data', label: 'Sin dato', color: '#4' }, 'round',
]; (c) =>
const rows = ['4A', '5', '6', '4B'].map((code) => ({ code, label: code, color: '#0' })); c === 'initial'
const mode = { ? 'Detección inicial'
kind: 'outcomes', : c === 'subsequent'
label: 'x', ? 'Detección subsecuente'
measure: 'M', : 'Sin dato',
stratum: 'birads', ['initial', 'subsequent', 'no_data'],
rows, );
results,
malignant: ['invasive'], it('keeps the order and shows each bar with its n, an empty one included', () => {
}; const f = draw(
const t = bars(mode as any, () => r)!; reading({ 'subsequent|NILM': 6, 'subsequent|HSIL': 2, 'no_data|NILM': 2 }, 10),
expect(t.rows.map((x) => x.cells)).toEqual([ );
['3', '0', '0', '3', '0', 'Sin biopsias'], const y = (f.data[0] as any).y;
['4', '1', '1', '0', '2', '1/2 (50.0 %)'], expect(y).toEqual([
['2', '0', '0', '0', '2', 'Sin biopsias clasificables'], 'Detección inicial<br>n = 0',
['0', '—', '—', '—', '—', '—'], 'Detección subsecuente<br>n = 8',
]); 'Sin dato<br>n = 2',
expect(t.rows.map((x) => x.none)).toEqual([ ]);
undefined, expect((f.data[0] as any).x).toEqual([0, 75, 100]);
undefined, });
undefined, it('leaves out a group that does not reconcile', () => {
'Sin pacientes en el periodo', const f = draw(reading({ 'subsequent|NILM': 6 }, 10));
]); expect((f.data[0] as any).y).toEqual(['Detección subsecuente<br>n = 6']);
expect(t.rows[1].segments!.map((x) => x.width)).toEqual([25, 25, 0, 50]); });
});
it('bars on a percent scale are as long as the shares shown', () => {
const r: Reading = {
populations: {},
strata: { category: { a: { 'initial-population': 1 }, b: { 'initial-population': 3 } } },
};
const catalog = [
{ code: 'a', label: 'A', color: '#0' },
{ code: 'b', label: 'B', color: '#1' },
{ code: 'c', label: 'C', color: '#2' },
];
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog, percent: true }, () => r)!;
expect(t.rows.map((x) => x.width)).toEqual([25, 75, 0]);
expect(t.rows.map((x) => x.cells)).toEqual([
['1', '25.0 %'],
['3', '75.0 %'],
['0', '0.0 %'],
]);
});
it('a split takes the colours it is given', () => {
const r: Reading = { populations: { numerator: 1, denominator: 4 }, strata: {} };
const mode = {
kind: 'split',
label: 'x',
measure: 'M',
yes: 'Con',
no: 'Sin',
colors: ['#a', '#b'],
};
expect(bars(mode as any, () => r)!.rows.map((x) => x.color)).toEqual(['#a', '#b']);
}); });
}); });
+197 -113
View File
@@ -1,56 +1,103 @@
import { CIE10 } from './cie10'; import { CIE10 } from './cie10';
import { NEUTRAL_DARK } from './cacu-palette';
import { name, Reading } from './measures'; import { name, Reading } from './measures';
/** A category as drawn: its code in the report, its name and its colour. */ /** A category as drawn: its code in the report, its name and its colour. */
export type Category = { code: string; label: string; color: string }; export type Category = { code: string; label: string; color: string };
/** One way of reading a card, as bars from the reports, or a figure. */ /** One way of reading a card, as bars from the reports, or a figure. */
export type Mode = { export type Mode = { label: string; caption?: string } & (
label: string; | { kind: 'counts'; measure: string; catalog: Category[] }
caption?: string; | {
/** said above the table: what its rows count (patients, reported biopsies…) */ kind: 'shares';
heading?: string; measure: string;
} & stratum: string;
/** `percent`: every bar on a fixed scale of 0 to 100 %, so its length is the share shown */ order: string[];
( complete?: boolean;
| { kind: 'counts'; measure: string; catalog: Category[]; percent?: boolean } colors?: Colors;
| { kind: 'shares'; measure: string; stratum: string; order: string[] } }
| { kind: 'positives'; measure: string; stratum: string; order: string[] } | {
| { kind: 'signs'; measure: string; strata: string[] } kind: 'positives';
| { kind: 'days'; steps: { label: string; measure: string }[] } measure: string;
| { kind: 'days-by'; measure: string; stratum: string } stratum: string;
/** A proportion as its two parts (what counted and what did not), in units, with the shares */ order: string[];
| { kind: 'split'; measure: string; yes: string; no: string; colors?: [string, string] } complete?: boolean;
/** Each row's units by result (a bar in segments), and the share of the row's units with a colors?: Colors;
* result that are `malignant`; a row with units and no result is not a row with none */ }
| { | { kind: 'signs'; measure: string; strata: string[]; colors?: Colors }
kind: 'outcomes'; | { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint }
measure: string; | { kind: 'days-by'; measure: string; stratum: string; tint?: Tint }
stratum: string; | {
rows: Category[]; kind: 'figure';
results: Category[]; measure: string;
malignant: string[]; figure: 'donut' | 'scenarios';
} /** a donut's colour by part (a category, or numerator and rest); none: the page's palette */
| { kind: 'figure'; measure: string; figure: 'donut' | 'scenarios'; catalog?: Category[] } colors?: Colors;
); catalog?: Category[];
/** the stratifier a scenarios figure crosses with the category (default: the follow-up status) */
stratum?: string;
order?: string[];
complete?: boolean;
}
);
/** A colour by category code (the category decides it, not its place in the report). */
export type Colors = Record<string, string>;
/** The colours of a median bar and of the marks of its quartiles. */
export type Tint = { bar: string; mark: string };
/** One bar: its length and quartile marks in % of the scale, and its cells of text. */ /** One bar: its length and quartile marks in % of the scale, and its cells of text. */
export interface Bar { export interface Bar {
label: string; label: string;
/** why the row has no figures: no patients in the group, or not available */
hint?: string;
color?: string; color?: string;
width: number; width: number;
marks: number[]; marks: number[];
cells: string[]; cells: string[];
/** the bar in parts (in % of the bar), each with what it says when hovered */
segments?: { width: number; color: string; title: string }[];
/** said in place of the bar (a row with nothing to draw) */
none?: string;
} }
export interface Bars { export interface Bars {
head: string[]; head: string[];
rows: Bar[]; rows: Bar[];
/** the colours of the segments */ /** the colour of the quartile marks, when the card has its own */
legend?: { label: string; color: string }[]; markColor?: string;
/** what the reader must know to take the rows right */
note?: string;
}
export const NOT_AVAILABLE = 'No disponible';
export const NO_PATIENTS = 'Sin pacientes en el periodo';
const EMPTY_ROUND =
'Hay pacientes sin clasificación de ronda («Sin dato»): una categoría en cero significa que no hay pacientes clasificadas en esa ronda según la información disponible.';
const NO_ROUND =
'Ninguna paciente del periodo tiene clasificación de detección inicial o subsecuente: los grupos en cero reflejan información no registrada, no ausencia de pacientes.';
const whole = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0;
/** A group the report does not list is zero patients only when the groups it lists add up to every
* patient of the period (the report leaves out empty groups); otherwise it is not available. */
export function reconciles(listed: number[], total: number): boolean {
return listed.every(whole) && whole(total) && listed.reduce((t, n) => t + n, 0) === total;
}
/** The patients of a reading: its cohort, or the denominator of a proportion. */
export const patients = (r?: Reading) =>
r?.populations['initial-population'] ?? r?.populations['denominator'] ?? 0;
/** Why a card of a "complete" mode has nothing to draw though its period has patients: the report
* does not publish the stratifier. Undefined when there is nothing to say. */
export function unavailable(
mode: Mode,
of: (measure: string) => Reading | undefined,
): string | undefined {
if (!('complete' in mode) || !mode.complete || !('stratum' in mode) || !mode.stratum)
return undefined;
const r = of(mode.measure);
if (!patients(r)) return undefined;
const key = mode.kind === 'shares' ? mode.stratum : `${mode.stratum}-category`;
return Object.keys(r?.strata[key] ?? {}).length
? undefined
: `${NOT_AVAILABLE}: el informe de este periodo no publica la clasificación por detección inicial o subsecuente.`;
} }
const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—'); const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—');
@@ -69,9 +116,9 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
const rest = Object.keys(cells).filter((c) => !named.includes(c)); const rest = Object.keys(cells).filter((c) => !named.includes(c));
const all = [ const all = [
...mode.catalog, ...mode.catalog,
...rest.map((code) => ({ code, label: name(code), color: '#9AA3AB' })), ...rest.map((code) => ({ code, label: name(code), color: NEUTRAL_DARK })),
]; ];
const most = mode.percent ? total : Math.max(...Object.values(cells).map(size)); const most = Math.max(...Object.values(cells).map(size));
return { return {
head: ['n', '%'], head: ['n', '%'],
rows: all.map(({ code, label, color }) => { rows: all.map(({ code, label, color }) => {
@@ -82,23 +129,63 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
}; };
} }
case 'shares': { case 'shares': {
const cells = of(mode.measure)?.strata[mode.stratum] ?? {}; const r = of(mode.measure);
return ratios( const cells = r?.strata[mode.stratum] ?? {};
mode.order if (!mode.complete)
.filter((c) => cells[c]) return ratios(
.map((c) => [name(c), cells[c]['numerator'] ?? 0, cells[c]['denominator'] ?? 0]), mode.order
.filter((c) => cells[c])
.map((c) => [
name(c),
cells[c]['numerator'] ?? 0,
cells[c]['denominator'] ?? 0,
mode.colors?.[c],
]),
);
if (!patients(r) || !Object.keys(cells).length) return undefined;
const sound = (c: string) =>
whole(cells[c]?.['numerator']) &&
whole(cells[c]?.['denominator']) &&
cells[c]['numerator'] <= cells[c]['denominator'];
const ok = reconciles(
Object.keys(cells).map((c) => cells[c]['denominator']),
patients(r),
);
return complete(
mode.order,
Object.keys(cells),
ok,
(c) => (sound(c) ? [cells[c]['numerator'], cells[c]['denominator']] : undefined),
mode.colors,
); );
} }
case 'positives': { case 'positives': {
const cells = of(mode.measure)?.strata[`${mode.stratum}-category`] ?? {}; const r = of(mode.measure);
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
const found = new Set(Object.keys(cells).map((k) => k.split('|')[0])); const found = new Set(Object.keys(cells).map((k) => k.split('|')[0]));
return ratios( if (!mode.complete)
mode.order return ratios(
.filter((c) => found.has(c)) mode.order
.map((c) => { .filter((c) => found.has(c))
const positive = size(cells[`${c}|positive`]); .map((c) => {
return [name(c), positive, positive + size(cells[`${c}|negative`])]; const positive = size(cells[`${c}|positive`]);
}), return [name(c), positive, positive + size(cells[`${c}|negative`]), mode.colors?.[c]];
}),
);
if (!patients(r) || !found.size) return undefined;
const ok = reconciles(
Object.values(cells).map((c) => c['initial-population']),
patients(r),
);
return complete(
mode.order,
[...found],
ok,
(c) => {
const positive = size(cells[`${c}|positive`]);
return [positive, positive + size(cells[`${c}|negative`])];
},
mode.colors,
); );
} }
case 'signs': { case 'signs': {
@@ -108,7 +195,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
.filter((s) => Object.keys(strata[s] ?? {}).length) .filter((s) => Object.keys(strata[s] ?? {}).length)
.map((s) => { .map((s) => {
const positive = size(strata[s]['positive']); const positive = size(strata[s]['positive']);
return [name(s), positive, positive + size(strata[s]['negative'])]; return [name(s), positive, positive + size(strata[s]['negative']), mode.colors?.[s]];
}), }),
); );
} }
@@ -118,6 +205,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
const r = of(measure); const r = of(measure);
return { label, n: r?.populations['measure-observation'] ?? 0, score: r }; return { label, n: r?.populations['measure-observation'] ?? 0, score: r };
}), }),
mode.tint,
); );
case 'days-by': { case 'days-by': {
const r = of(mode.measure); const r = of(mode.measure);
@@ -130,79 +218,70 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
score: r?.scores?.[mode.stratum]?.[c], score: r?.scores?.[mode.stratum]?.[c],
})) }))
.sort((a, b) => b.n - a.n), .sort((a, b) => b.n - a.n),
mode.tint,
); );
} }
case 'split': {
const { numerator = 0, denominator = 0 } = of(mode.measure)?.populations ?? {};
if (!denominator) return undefined;
const parts: [string, number][] = [
[mode.yes, numerator],
[mode.no, denominator - numerator],
];
return {
head: ['n', '%'],
rows: parts.map(([label, n], i) => ({
label,
color: mode.colors?.[i],
width: (100 * n) / denominator,
marks: [],
cells: [`${n}`, pct(n, denominator)],
})),
};
}
case 'outcomes': {
const r = of(mode.measure);
const units = r?.strata[mode.stratum] ?? {};
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
if (!Object.keys(units).length) return undefined;
const graded = (i: number) => !['no_biopsy', 'no_data'].includes(mode.results[i].code);
return {
head: ['Pacientes', ...mode.results.map((x) => x.label), '% maligno'],
legend: mode.results.map(({ label, color }) => ({ label, color })),
rows: mode.rows.map(({ code, label }) => {
const n = size(units[code]);
const by = mode.results.map((x) => size(cells[`${code}|${x.code}`]));
const den = by.reduce((t, k, i) => t + (graded(i) ? k : 0), 0);
const bad = by.reduce(
(t, k, i) => t + (mode.malignant.includes(mode.results[i].code) ? k : 0),
0,
);
return {
label,
width: 100,
marks: [],
none: n ? undefined : 'Sin pacientes en el periodo',
segments: mode.results.map((x, i) => ({
width: n ? (100 * by[i]) / n : 0,
color: x.color,
title: `${x.label}: ${by[i]} de ${n} (${pct(by[i], n)})`,
})),
cells: [
`${n}`,
...by.map((k) => (n ? `${k}` : '—')),
n
? den
? `${bad}/${den} (${pct(bad, den)})`
: by[mode.results.findIndex((x) => x.code === 'no_data')]
? 'Sin biopsias clasificables'
: 'Sin biopsias'
: '—',
],
};
}),
};
}
default: default:
return undefined; return undefined;
} }
} }
function ratios(rows: [string, number, number][]): Bars | undefined { /** Every group of a stratifier the card names, in its order: those the report lists with their
* counts; those it leaves out as no patients when the counts add up to the period's patients,
* else as not available. "Sin dato" keeps its own counts. */
function complete(
order: string[],
listed: string[],
reconciled: boolean,
counts: (code: string) => [number, number] | undefined,
colors: Colors = {},
): Bars {
const extra = listed.filter((c) => !order.includes(c));
const rows: Bar[] = [...order, ...extra].map((code) => {
const label = name(code);
const color = colors[code];
if (!listed.includes(code))
return reconciled
? { label, color, hint: NO_PATIENTS, width: 0, marks: [], cells: ['0/0', '—'] }
: { label, color, hint: NOT_AVAILABLE, width: 0, marks: [], cells: ['—', '—'] };
const found = counts(code);
if (!found)
return { label, color, hint: NOT_AVAILABLE, width: 0, marks: [], cells: ['—', '—'] };
const [n, total] = found;
return {
label,
color,
hint: total ? undefined : NO_PATIENTS,
width: total ? (100 * n) / total : 0,
marks: [],
cells: [`${n}/${total}`, pct(n, total)],
};
});
const classified = order.filter((c) => c !== 'no_data' && listed.includes(c));
const empty = classified.filter((c) => !(counts(c)?.[1] ?? 0));
const none = empty.length === classified.length;
const unclassified = counts('no_data')?.[1] ?? 0;
return {
head: ['n/N', '%'],
rows,
note: !reconciled
? 'Los conteos del informe no concilian con el total de pacientes: los grupos ausentes no se muestran como cero.'
: none && listed.includes('no_data')
? NO_ROUND
: unclassified &&
(empty.length || order.some((c) => !listed.includes(c) && c !== 'no_data'))
? EMPTY_ROUND
: undefined,
};
}
function ratios(rows: [string, number, number, string?][]): Bars | undefined {
if (!rows.length) return undefined; if (!rows.length) return undefined;
return { return {
head: ['n/N', '%'], head: ['n/N', '%'],
rows: rows.map(([label, n, total]) => ({ rows: rows.map(([label, n, total, color]) => ({
label, label,
color,
width: total ? (100 * n) / total : 0, width: total ? (100 * n) / total : 0,
marks: [], marks: [],
cells: [`${n}/${total}`, pct(n, total)], cells: [`${n}/${total}`, pct(n, total)],
@@ -211,17 +290,22 @@ function ratios(rows: [string, number, number][]): Bars | undefined {
} }
type Score = { score?: number; low?: number; high?: number }; type Score = { score?: number; low?: number; high?: number };
function medians(rows: { label: string; n: number; score?: Score }[]): Bars | undefined { function medians(
rows: { label: string; n: number; score?: Score }[],
tint?: Tint,
): Bars | undefined {
if (!rows.some((r) => r.score?.score !== undefined)) return undefined; if (!rows.some((r) => r.score?.score !== undefined)) return undefined;
const top = Math.max(...rows.flatMap((r) => [r.score?.score ?? 0, r.score?.high ?? 0])) || 1; const top = Math.max(...rows.flatMap((r) => [r.score?.score ?? 0, r.score?.high ?? 0])) || 1;
const at = (v: number) => (100 * v) / top; const at = (v: number) => (100 * v) / top;
return { return {
head: ['Mediana', 'n', 'Q1–Q3'], head: ['Mediana', 'n', 'Q1–Q3'],
markColor: tint?.mark,
rows: rows.map(({ label, n, score: s }) => { rows: rows.map(({ label, n, score: s }) => {
if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] }; if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] };
const spread = s.low !== undefined && s.high !== undefined ? [s.low, s.high] : []; const spread = s.low !== undefined && s.high !== undefined ? [s.low, s.high] : [];
return { return {
label, label,
color: tint?.bar,
width: at(s.score), width: at(s.score),
marks: spread.map(at), marks: spread.map(at),
cells: [`${days(s.score)} días`, `${n}`, spread.map(days).join('–') || '—'], cells: [`${days(s.score)} días`, `${n}`, spread.map(days).join('–') || '—'],
+81
View File
@@ -0,0 +1,81 @@
import { bars, Mode } from './bars';
import {
BIOPSY_COLORS,
CYTOLOGY_COLORS,
HPV_COLORS,
NEUTRAL,
PPV_CYTOLOGY_COLORS,
PPV_DONUT,
PPV_LEVEL_COLORS,
REQUEST_COLORS,
ROUND_COLORS,
STEEL,
VPH_DONUT,
} from './cacu-palette';
import type { Measure } from 'fhir/r4';
import { donut, Reading } from './measures';
describe('CaCu palette', () => {
it('a PPV group has the colour of its category elsewhere on the page', () => {
expect(PPV_CYTOLOGY_COLORS['ascus_plus']).toBe(CYTOLOGY_COLORS['ASC-US']);
expect(PPV_CYTOLOGY_COLORS['lsil_plus']).toBe(CYTOLOGY_COLORS['LSIL']);
expect(PPV_CYTOLOGY_COLORS['hsil_plus']).toBe(CYTOLOGY_COLORS['HSIL']);
expect(PPV_LEVEL_COLORS['cin1_plus']).toBe(BIOPSY_COLORS['LSIL']);
expect(PPV_LEVEL_COLORS['cin2_plus']).toBe(BIOPSY_COLORS['HSIL']);
expect(PPV_LEVEL_COLORS['carcinoma']).toBe(BIOPSY_COLORS['carcinoma']);
expect(HPV_COLORS['hpv_16']).toBe(HPV_COLORS['positive_16']);
expect(HPV_COLORS['hpv_18']).toBe(HPV_COLORS['positive_18']);
expect(HPV_COLORS['positive']).toBe(HPV_COLORS['positive_other']);
expect(REQUEST_COLORS['high_grade']).toBe(CYTOLOGY_COLORS['HSIL']);
});
it('"Sin dato" and what is not classified are neutral everywhere', () => {
for (const colors of [
CYTOLOGY_COLORS,
HPV_COLORS,
BIOPSY_COLORS,
ROUND_COLORS,
PPV_CYTOLOGY_COLORS,
])
expect(colors['no_data']).toBe(NEUTRAL);
expect(REQUEST_COLORS['pending']).toBe(NEUTRAL);
expect(PPV_DONUT['rest']).toBe(NEUTRAL);
expect(ROUND_COLORS['initial']).toBe(STEEL);
});
it('a donut colours by category, not by place in the report', () => {
const measure = { scoring: { coding: [{ code: 'cohort' }] } } as unknown as Measure;
const cells = (order: string[]): Reading => ({
populations: {},
strata: { category: Object.fromEntries(order.map((c) => [c, { 'initial-population': 1 }])) },
});
const colours = (order: string[]) =>
(donut(measure, cells(order), 'category', VPH_DONUT).data[0] as any).marker.colors;
expect(colours(['negative', 'positive'])).toEqual([
VPH_DONUT['negative'],
VPH_DONUT['positive'],
]);
expect(colours(['positive', 'negative'])).toEqual([
VPH_DONUT['positive'],
VPH_DONUT['negative'],
]);
});
it('bars take their colour from the mode by group, absent groups included', () => {
const r: Reading = {
populations: { 'initial-population': 5 },
strata: { round: { subsequent: { numerator: 1, denominator: 5 } } },
};
const mode: Mode = {
kind: 'shares',
label: 'x',
measure: 'M',
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
complete: true,
colors: ROUND_COLORS,
};
expect(bars(mode, () => r)!.rows.map((x) => x.color)).toEqual([
ROUND_COLORS['initial'],
ROUND_COLORS['subsequent'],
ROUND_COLORS['no_data'],
]);
});
});
+103
View File
@@ -0,0 +1,103 @@
/** The colours of CaCu's charts, by category. A colour names a category (never a position in a
* report, never a threshold), so the same category looks the same on every card; neutral greys
* are for what is absent or not classified. They are the ones CaCu's page had before the
* rebuild, kept here so that no other domain (CaMa, TEA) changes with them. */
/** Not classified, or no data. */
export const NEUTRAL = '#C9CDD2';
/** Not classified, a little darker: what a report names but a card does not. */
export const NEUTRAL_DARK = '#9AA3AB';
/** The steel tones of the groups that are not results: rounds, ages, follow-up status. */
export const STEEL = '#5F7F9A';
export const STEEL_MID = '#8FA7BB';
export const STEEL_LIGHT = '#B5C5D3';
/** Cytology by Bethesda category. */
export const CYTOLOGY_COLORS: Record<string, string> = {
NILM: '#408651',
'ASC-US': '#2778B8',
LSIL: '#B19525',
'ASC-H': '#7955B1',
HSIL: '#CE4778',
CIS: '#AA394D',
no_data: NEUTRAL,
};
/** HPV by genotype; `positive` (any high-risk type) is the colour of "positive other". */
export const HPV_COLORS: Record<string, string> = {
negative: '#42A77E',
positive_16: '#DF8640',
positive_18: '#C29C42',
positive_16_18: '#C24269',
positive_other: '#A8C243',
positive_incomplete: '#9C42C2',
inconsistent: '#687786',
positive: '#A8C243',
hpv_16: '#DF8640',
hpv_18: '#C29C42',
no_data: NEUTRAL,
};
/** Biopsy by the grade it states; the levels of a PPV (that grade or worse) take its colour. */
export const BIOPSY_COLORS: Record<string, string> = {
normal: '#408651',
LSIL: '#B19525',
HSIL: '#CE4778',
CIS: '#AA394D',
carcinoma: '#8D4C79',
cin1_plus: '#B19525',
cin2_plus: '#CE4778',
no_data: NEUTRAL,
};
/** What became of the biopsy requests: high grade is the colour of LIEAG, the rest steel. */
export const REQUEST_COLORS: Record<string, string> = {
high_grade: '#CE4778',
below_high_grade: STEEL_MID,
pending: NEUTRAL,
no_grade: NEUTRAL_DARK,
};
/** Detection round: steel tones; "Sin dato" is neutral. */
export const ROUND_COLORS: Record<string, string> = {
initial: STEEL,
subsequent: STEEL_MID,
no_data: NEUTRAL,
};
/** Follow-up status and age groups, as the HPV card drew them. */
export const STATUS_COLORS: Record<string, string> = {
pre_colposcopy: STEEL,
post_colposcopy: STEEL_MID,
post_treatment: STEEL_LIGHT,
case: NEUTRAL_DARK,
};
export const AGE_COLORS: Record<string, string> = Object.fromEntries(
['<25', '25-34', '35-44', '45-54', '55-64', '65+'].map((c) => [c, STEEL]),
);
/** Referral PPV groups: cytology and histology levels by the colour of their category, HPV by
* genotype. */
export const PPV_CYTOLOGY_COLORS: Record<string, string> = {
ascus_plus: CYTOLOGY_COLORS['ASC-US'],
lsil_plus: CYTOLOGY_COLORS['LSIL'],
hsil_plus: CYTOLOGY_COLORS['HSIL'],
no_data: NEUTRAL,
};
export const PPV_LEVEL_COLORS: Record<string, string> = {
cin1_plus: BIOPSY_COLORS['LSIL'],
cin2_plus: BIOPSY_COLORS['HSIL'],
carcinoma: BIOPSY_COLORS['carcinoma'],
};
/** The whole of a CaCu card as a donut: the colours of its two parts. */
export const VPH_DONUT: Record<string, string> = {
negative: HPV_COLORS['negative'],
positive: HPV_COLORS['positive_other'],
};
export const PPV_DONUT: Record<string, string> = { numerator: '#6A8000', rest: NEUTRAL };
/** Median bars of the screening route, and the marks of their quartiles. */
export const DURATION = '#42A77E';
export const QUARTILE = '#17324D';
-55
View File
@@ -1,55 +0,0 @@
import { durationMax, durationRows } from './durations';
import { Reading } from './measures';
const reading = (score?: number, n = 0, low?: number, high?: number): Reading => ({
populations: { 'measure-observation': n },
score,
low,
high,
strata: {},
});
describe('durationRows', () => {
const reads: Record<string, Reading> = {
A: reading(0, 3, 0, 1),
B: reading(6, 20, 4, 8),
C: reading(undefined, 0),
};
const rows = durationRows(
[
{ label: 'zero', measure: 'A' },
{ label: 'value', measure: 'B' },
{ label: 'nothing measured', measure: 'C' },
{ label: 'no report', measure: 'D' },
{ label: 'not in the catalog', measure: 'E' },
{ label: 'no measure' },
],
(m) => reads[m],
(m) => m !== 'E',
);
it('keeps a real zero as a value', () => {
expect(rows[0]).toEqual({
label: 'zero',
status: 'value',
median: 0,
observations: 3,
low: 0,
high: 1,
});
});
it('tells no measurements from an unpublished measure', () => {
expect(rows.map((r) => r.status)).toEqual([
'value',
'value',
'empty',
'empty',
'unpublished',
'unpublished',
]);
});
it('scales from zero to the largest median or third quartile', () => {
expect(durationMax(rows)).toBe(8);
expect(durationMax([])).toBe(0);
});
});
-46
View File
@@ -1,46 +0,0 @@
import { Reading } from './measures';
/** One step of a route: its name and the measure that times it. A step with no measure is
* not published yet. */
export interface RouteStep {
label: string;
measure?: string;
}
/** One row of a duration table: the median days, how many measurements and the quartiles.
* `empty` (published, nothing measured in the period) is not `unpublished` (no measure), and
* neither is a zero: a median of 0 days is a value. */
export interface DurationRow {
label: string;
status: 'value' | 'empty' | 'unpublished';
median?: number;
observations?: number;
low?: number;
high?: number;
}
/** The rows of a route in one reading; every step keeps its row. `published` says which
* measures the catalog has. */
export function durationRows(
steps: RouteStep[],
read: (measure: string) => Reading | undefined,
published: (measure: string) => boolean,
): DurationRow[] {
return steps.map(({ label, measure }) => {
if (!measure || !published(measure)) return { label, status: 'unpublished' };
const r = read(measure);
if (r?.score === undefined) return { label, status: 'empty' };
return {
label,
status: 'value',
median: r.score,
observations: r.populations['measure-observation'],
low: r.low,
high: r.high,
};
});
}
/** The scale of a table of durations, from zero: the largest median or third quartile shown. */
export const durationMax = (rows: DurationRow[]): number =>
Math.max(0, ...rows.map((r) => Math.max(r.median ?? 0, r.high ?? 0)));
+21 -5
View File
@@ -1,4 +1,5 @@
import { type Figure, PALETTE } from '../plot'; import { type Figure, PALETTE } from '../plot';
import { reconciles } from './bars';
import { name, type Reading } from './measures'; import { name, type Reading } from './measures';
import type { Catalog, Category, HistoryPanel } from './pages'; import type { Catalog, Category, HistoryPanel } from './pages';
@@ -96,14 +97,25 @@ export function scenarioBars(
catalog: Catalog, catalog: Catalog,
stratum: string, stratum: string,
label: (code: string) => string, label: (code: string) => string,
/** the groups in this order; an empty one is drawn when the counts reconcile (see `reconciles`) */
order?: string[],
): Figure { ): Figure {
const cells = r.strata[`${stratum}-category`] ?? {}; const cells = r.strata[`${stratum}-category`] ?? {};
const scenarios = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))].sort((a, b) => const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
label(a).localeCompare(label(b), 'es'), const listed = Object.values(cells).map((c) => c['initial-population']);
); const scenarios = order
? [
...order.filter(
(s) => found.includes(s) || reconciles(listed, r.populations['initial-population'] ?? 0),
),
...found.filter((s) => !order.includes(s)),
]
: found.sort((a, b) => label(a).localeCompare(label(b), 'es'));
const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0; 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 totals = scenarios.map((s) => catalog.categories.reduce((t, c) => t + n(s, c.code), 0));
const y = scenarios.map(label); const y = order
? scenarios.map((s, i) => `${label(s)}<br>n = ${totals[i]}`)
: scenarios.map(label);
return { return {
data: catalog.categories.map((c) => ({ data: catalog.categories.map((c) => ({
type: 'bar', type: 'bar',
@@ -118,7 +130,11 @@ export function scenarioBars(
layout: { layout: {
barmode: 'stack', barmode: 'stack',
xaxis: { xaxis: {
title: { text: '% de pacientes del escenario con resultado' }, title: {
text: order
? '% de pacientes con resultado'
: '% de pacientes del escenario con resultado',
},
ticksuffix: ' %', ticksuffix: ' %',
range: [0, 100.5], range: [0, 100.5],
dtick: 20, dtick: 20,
+16 -8
View File
@@ -133,8 +133,8 @@ export const LABELS: Record<string, string> = {
good: 'Bueno', good: 'Bueno',
bad: 'Malo', bad: 'Malo',
not_analyzed: 'Sin analizar', not_analyzed: 'Sin analizar',
initial: 'Inicial', initial: 'Detección inicial',
subsequent: 'Subsecuente', subsequent: 'Detección subsecuente',
positive: 'Positivo', positive: 'Positivo',
negative: 'Negativo', negative: 'Negativo',
hpv_16: 'VPH 16', hpv_16: 'VPH 16',
@@ -182,14 +182,14 @@ export function formatScore(measure: Measure, r: Reading | undefined): string {
} }
} }
export function detail(measure: Measure, r: Reading | undefined, unit = 'pacientes'): string { export function detail(measure: Measure, r: Reading | undefined): string {
if (!r) return ''; if (!r) return '';
const p = r.populations; const p = r.populations;
switch (scoring(measure)) { switch (scoring(measure)) {
case 'proportion': case 'proportion':
return r.score === undefined return r.score === undefined
? `Sin ${unit} en el periodo.` ? 'Sin pacientes en el periodo.'
: `${p['numerator']} de ${p['denominator']} ${unit}. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`; : `${p['numerator']} de ${p['denominator']} pacientes. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`;
case 'continuous-variable': case 'continuous-variable':
return r.score === undefined return r.score === undefined
? `${p['initial-population'] ?? 0} sin medición en el periodo.` ? `${p['initial-population'] ?? 0} sin medición en el periodo.`
@@ -202,15 +202,23 @@ export function detail(measure: Measure, r: Reading | undefined, unit = 'pacient
const pct = (v?: number) => (v === undefined ? '—' : `${(v * 100).toFixed(1)} %`); const pct = (v?: number) => (v === undefined ? '—' : `${(v * 100).toFixed(1)} %`);
/** A donut of one stratifier's counts (initial population), or of numerator vs the rest. */ /** A donut of one stratifier's counts (initial population), or of numerator vs the rest. */
export function donut(measure: Measure, r: Reading, stratifier = 'category'): Figure { export function donut(
let labels: string[], values: number[]; measure: Measure,
r: Reading,
stratifier = 'category',
/** a colour by category code (a proportion: `numerator` and `rest`); a part without one takes the palette's */
colors?: Record<string, string>,
): Figure {
let labels: string[], values: number[], codes: string[];
if (scoring(measure) === 'proportion') { if (scoring(measure) === 'proportion') {
const { numerator = 0, denominator = 0 } = r.populations; const { numerator = 0, denominator = 0 } = r.populations;
labels = ['Numerador', 'Resto']; labels = ['Numerador', 'Resto'];
codes = ['numerator', 'rest'];
values = [numerator, denominator - numerator]; values = [numerator, denominator - numerator];
} else { } else {
const cells = Object.entries(r.strata[stratifier] ?? {}); const cells = Object.entries(r.strata[stratifier] ?? {});
labels = cells.map(([v]) => name(v)); labels = cells.map(([v]) => name(v));
codes = cells.map(([v]) => v);
values = cells.map(([, c]) => c['initial-population'] ?? 0); values = cells.map(([, c]) => c['initial-population'] ?? 0);
} }
return { return {
@@ -222,7 +230,7 @@ export function donut(measure: Measure, r: Reading, stratifier = 'category'): Fi
values, values,
sort: false, sort: false,
textinfo: 'value+percent', textinfo: 'value+percent',
marker: { colors: PALETTE }, marker: { colors: codes.map((c, i) => colors?.[c] ?? PALETTE[i % PALETTE.length]) },
}, },
], ],
layout: { showlegend: true, margin: { t: 32, r: 8, b: 32, l: 8 } }, layout: { showlegend: true, margin: { t: 32, r: 8, b: 32, l: 8 } },
+93 -28
View File
@@ -1,4 +1,19 @@
import type { Mode } from './bars'; import type { Mode } from './bars';
import {
AGE_COLORS,
BIOPSY_COLORS,
CYTOLOGY_COLORS,
DURATION,
HPV_COLORS,
PPV_CYTOLOGY_COLORS,
PPV_DONUT,
PPV_LEVEL_COLORS,
QUARTILE,
REQUEST_COLORS,
ROUND_COLORS,
STATUS_COLORS,
VPH_DONUT,
} from './cacu-palette';
import type { Catalog, Page, ReadingsCard } from './pages'; import type { Catalog, Page, ReadingsCard } from './pages';
const OLIVE = '#A8C243'; const OLIVE = '#A8C243';
@@ -11,12 +26,12 @@ const CYTOLOGY: Catalog = {
{ id: 'abnormal', label: 'Anormal', color: ROSE }, { id: 'abnormal', label: 'Anormal', color: ROSE },
], ],
categories: [ categories: [
{ code: 'NILM', label: 'Normal', color: '#A8C243', group: 'normal' }, { code: 'NILM', label: 'Normal', color: CYTOLOGY_COLORS['NILM'], group: 'normal' },
{ code: 'ASC-US', label: 'ASC-US', color: '#92324F', group: 'abnormal' }, { code: 'ASC-US', label: 'ASC-US', color: CYTOLOGY_COLORS['ASC-US'], group: 'abnormal' },
{ code: 'LSIL', label: 'LIEBG', color: '#AA3A5C', group: 'abnormal' }, { code: 'LSIL', label: 'LIEBG', color: CYTOLOGY_COLORS['LSIL'], group: 'abnormal' },
{ code: 'ASC-H', label: 'ASC-H', color: '#C24269', group: 'abnormal' }, { code: 'ASC-H', label: 'ASC-H', color: CYTOLOGY_COLORS['ASC-H'], group: 'abnormal' },
{ code: 'HSIL', label: 'LIEAG', color: '#C54C71', group: 'abnormal' }, { code: 'HSIL', label: 'LIEAG', color: CYTOLOGY_COLORS['HSIL'], group: 'abnormal' },
{ code: 'CIS', label: 'Carcinoma in situ', color: '#C9577A', group: 'abnormal' }, { code: 'CIS', label: 'Carcinoma in situ', color: CYTOLOGY_COLORS['CIS'], group: 'abnormal' },
], ],
}; };
@@ -27,31 +42,50 @@ const BIOPSY: Catalog = {
{ id: 'high', label: 'LIEAG o más', color: ROSE }, { id: 'high', label: 'LIEAG o más', color: ROSE },
], ],
categories: [ categories: [
{ code: 'normal', label: 'Normal', color: '#7E9232', group: 'low' }, { code: 'normal', label: 'Normal', color: BIOPSY_COLORS['normal'], group: 'low' },
{ code: 'LSIL', label: 'LIEBG (CIN 1)', color: '#B2C958', group: 'low' }, { code: 'LSIL', label: 'LIEBG (CIN 1)', color: BIOPSY_COLORS['LSIL'], group: 'low' },
{ code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: '#92324F', group: 'high' }, { code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: BIOPSY_COLORS['HSIL'], group: 'high' },
{ code: 'CIS', label: 'Carcinoma in situ', color: '#C24269', group: 'high' }, { code: 'CIS', label: 'Carcinoma in situ', color: BIOPSY_COLORS['CIS'], group: 'high' },
{ code: 'carcinoma', label: 'Carcinoma invasor', color: '#C9577A', group: 'high' }, {
code: 'carcinoma',
label: 'Carcinoma invasor',
color: BIOPSY_COLORS['carcinoma'],
group: 'high',
},
], ],
faded: ['normal', 'LSIL'], faded: ['normal', 'LSIL'],
}; };
/** HPV reports by genotype, and biopsy requests by what became of them. */ /** HPV reports by genotype, and biopsy requests by what became of them. */
const HPV = [ const HPV = [
{ code: 'negative', label: 'Negativo', color: '#A8C243' }, { code: 'negative', label: 'Negativo', color: HPV_COLORS['negative'] },
{ code: 'positive_16', label: 'VPH 16', color: '#C24269' }, { code: 'positive_16', label: 'VPH 16', color: HPV_COLORS['positive_16'] },
{ code: 'positive_18', label: 'VPH 18', color: '#9C42C2' }, { code: 'positive_18', label: 'VPH 18', color: HPV_COLORS['positive_18'] },
{ code: 'positive_16_18', label: 'VPH 16 y 18', color: '#92324F' }, { code: 'positive_16_18', label: 'VPH 16 y 18', color: HPV_COLORS['positive_16_18'] },
{ code: 'positive_other', label: 'Otro de alto riesgo', color: '#C54C71' }, { code: 'positive_other', label: 'Otro de alto riesgo', color: HPV_COLORS['positive_other'] },
{ code: 'positive_incomplete', label: 'Positivo, genotipo incompleto', color: '#C9577A' }, {
code: 'positive_incomplete',
label: 'Positivo, genotipo incompleto',
color: HPV_COLORS['positive_incomplete'],
},
]; ];
const REQUESTS = [ const REQUESTS = [
{ code: 'high_grade', label: 'LIEAG o más', color: '#C24269' }, { code: 'high_grade', label: 'LIEAG o más', color: REQUEST_COLORS['high_grade'] },
{ code: 'below_high_grade', label: 'Menor que LIEAG', color: '#A8C243' }, { code: 'below_high_grade', label: 'Menor que LIEAG', color: REQUEST_COLORS['below_high_grade'] },
{ code: 'pending', label: 'Pendiente', color: '#C9CDD2' }, { code: 'pending', label: 'Pendiente', color: REQUEST_COLORS['pending'] },
{ code: 'no_grade', label: 'Sin grado', color: '#9AA3AB' }, { code: 'no_grade', label: 'Sin grado', color: REQUEST_COLORS['no_grade'] },
]; ];
/** The screening route's bars: a median, and the marks of its quartiles. */
const TINT = { bar: DURATION, mark: QUARTILE };
/** The screening rounds, in the order the cards draw them. */
const ROUNDS = ['initial', 'subsequent', 'no_data'];
const ROUND_CAPTION =
'Cada paciente está en un solo grupo, según su muestra (fecha de toma): detección inicial (primera vez en la vida), ' +
'subsecuente (detección previa registrada, o ya con colposcopía o tratamiento) o «Sin dato». ' +
'Un grupo sin pacientes se muestra en cero; sin porcentaje.';
/** A PPV's card: the whole, and by each of its stratifiers. */ /** A PPV's card: the whole, and by each of its stratifiers. */
const ppv = (measure: string, title: string, note: string, ...more: Mode[]): ReadingsCard => ({ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): ReadingsCard => ({
kind: 'readings', kind: 'readings',
@@ -59,13 +93,14 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
headline: measure, headline: measure,
note: `${note} Confirma la histología LIEBG o mayor.`, note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [ modes: [
{ kind: 'figure', label: 'Total', measure, figure: 'donut' }, { kind: 'figure', label: 'Total', measure, figure: 'donut', colors: PPV_DONUT },
{ {
kind: 'shares', kind: 'shares',
label: 'Citología previa', label: 'Citología previa',
caption: 'La última válida de los 365 días anteriores; cada grupo incluye los más severos.', caption: 'La última válida de los 365 días anteriores; cada grupo incluye los más severos.',
measure, measure,
stratum: 'cytology', stratum: 'cytology',
colors: PPV_CYTOLOGY_COLORS,
order: ['ascus_plus', 'lsil_plus', 'hsil_plus', 'no_data'], order: ['ascus_plus', 'lsil_plus', 'hsil_plus', 'no_data'],
}, },
{ {
@@ -74,6 +109,7 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
caption: 'Los grupos se traslapan.', caption: 'Los grupos se traslapan.',
measure, measure,
stratum: 'hpv', stratum: 'hpv',
colors: HPV_COLORS,
order: ['negative', 'positive', 'hpv_16', 'hpv_18', 'no_data'], order: ['negative', 'positive', 'hpv_16', 'hpv_18', 'no_data'],
}, },
{ {
@@ -81,14 +117,18 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
label: 'Nivel de histología', label: 'Nivel de histología',
measure, measure,
stratum: 'level', stratum: 'level',
colors: PPV_LEVEL_COLORS,
order: ['cin1_plus', 'cin2_plus', 'carcinoma'], order: ['cin1_plus', 'cin2_plus', 'carcinoma'],
}, },
{ {
kind: 'shares', kind: 'shares',
label: 'Tamizaje', label: 'Por detección inicial y subsecuente',
caption: ROUND_CAPTION,
measure, measure,
stratum: 'round', stratum: 'round',
order: ['initial', 'subsequent', 'no_data'], colors: ROUND_COLORS,
order: ROUNDS,
complete: true,
}, },
...more, ...more,
], ],
@@ -136,6 +176,7 @@ export const CACU: Page = {
modes: [ modes: [
{ {
kind: 'days', kind: 'days',
tint: TINT,
label: 'Acumulado desde la toma', label: 'Acumulado desde la toma',
steps: [ steps: [
{ label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' }, { label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
@@ -146,6 +187,7 @@ export const CACU: Page = {
}, },
{ {
kind: 'days', kind: 'days',
tint: TINT,
label: 'Por pasos', label: 'Por pasos',
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.', caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
steps: [ steps: [
@@ -157,6 +199,7 @@ export const CACU: Page = {
}, },
{ {
kind: 'days-by', kind: 'days-by',
tint: TINT,
label: 'Por CIE-10', label: 'Por CIE-10',
caption: 'Días de la toma al diagnóstico, por el código de la nota que lo fecha.', caption: 'Días de la toma al diagnóstico, por el código de la nota que lo fecha.',
measure: 'CACU_TIEMPO_DIAGNOSTICO_CIE10', measure: 'CACU_TIEMPO_DIAGNOSTICO_CIE10',
@@ -183,10 +226,20 @@ export const CACU: Page = {
}, },
{ {
kind: 'figure', kind: 'figure',
label: 'Por escenario clínico', label: 'Por detección inicial y subsecuente',
caption:
'Cada paciente cuenta una vez, con su última muestra válida del periodo; la detección es la de esa muestra (fecha de toma). ' +
'«Detección inicial»: primera vez en la vida y sin colposcopía ni tratamiento a la toma. ' +
'«Detección subsecuente»: con detección previa registrada, o ya con colposcopía o tratamiento a la toma. ' +
'«Sin dato»: sin detección previa registrada y sin colposcopía ni tratamiento. ' +
'Cada barra suma 100 % de las pacientes del grupo con resultado citológico (n indica cuántas son). ' +
'Si hay pacientes en «Sin dato», una barra vacía significa que no hay pacientes clasificadas en esa detección según la información disponible.',
measure: 'CACU_EU7', measure: 'CACU_EU7',
figure: 'scenarios', figure: 'scenarios',
catalog: CYTOLOGY.categories, catalog: CYTOLOGY.categories,
stratum: 'round',
order: ROUNDS,
complete: true,
}, },
], ],
}, },
@@ -217,12 +270,19 @@ export const CACU: Page = {
headline: 'CACU_VPH', headline: 'CACU_VPH',
note: 'Una vez cada paciente, por su última muestra con resultado.', note: 'Una vez cada paciente, por su última muestra con resultado.',
modes: [ modes: [
{ kind: 'figure', label: 'Total', measure: 'CACU_VPH', figure: 'donut' }, {
kind: 'figure',
label: 'Total',
measure: 'CACU_VPH',
figure: 'donut',
colors: VPH_DONUT,
},
{ {
kind: 'positives', kind: 'positives',
label: 'Por grupo de edad', label: 'Por grupo de edad',
measure: 'CACU_VPH', measure: 'CACU_VPH',
stratum: 'age_group', stratum: 'age_group',
colors: AGE_COLORS,
order: ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data'], order: ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data'],
}, },
{ {
@@ -230,6 +290,7 @@ export const CACU: Page = {
label: 'Por estatus de seguimiento', label: 'Por estatus de seguimiento',
measure: 'CACU_VPH', measure: 'CACU_VPH',
stratum: 'follow_up_status', stratum: 'follow_up_status',
colors: STATUS_COLORS,
order: ['pre_colposcopy', 'post_colposcopy', 'post_treatment', 'case'], order: ['pre_colposcopy', 'post_colposcopy', 'post_treatment', 'case'],
}, },
{ {
@@ -237,13 +298,17 @@ export const CACU: Page = {
label: 'Por genotipo', label: 'Por genotipo',
measure: 'CACU_VPH', measure: 'CACU_VPH',
strata: ['hpv_16', 'hpv_18'], strata: ['hpv_16', 'hpv_18'],
colors: HPV_COLORS,
}, },
{ {
kind: 'positives', kind: 'positives',
label: 'Por tamizaje', label: 'Por detección inicial y subsecuente',
caption: `${ROUND_CAPTION} Positivas sobre las pacientes con resultado de VPH del grupo.`,
measure: 'CACU_VPH', measure: 'CACU_VPH',
stratum: 'round', stratum: 'round',
order: ['initial', 'subsequent', 'no_data'], colors: ROUND_COLORS,
order: ROUNDS,
complete: true,
}, },
], ],
}, },
+39 -108
View File
@@ -1,6 +1,5 @@
import type { Mode } from './bars'; import type { Mode } from './bars';
import { CACU } from './pages-cacu'; import { CACU } from './pages-cacu';
import type { RouteStep } from './durations';
/** 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.
@@ -26,28 +25,15 @@ export interface ReadingsCard {
kind: 'readings'; kind: 'readings';
title: string; title: string;
headline?: string; headline?: string;
/** what the headline proportion counts, in the plural (default: pacientes) */
unit?: string;
note?: string; note?: string;
modes: Mode[]; modes: Mode[];
} }
export type Section = export type Section =
| ReadingsCard | ReadingsCard
/** A screening route as one compact card: a bar per step with its median, observations and
* quartiles. `sample` reads each step from the sample (its own measure, never a sum of
* medians); `step` reads each from the previous step. A reading with no steps is not offered. */
| { kind: 'route'; title: string; sample: RouteStep[]; step: RouteStep[] }
/** Cards side by side; the last one alone when odd. */ /** Cards side by side; the last one alone when odd. */
| { kind: 'columns'; title: string; sections: ReadingsCard[] } | { kind: 'columns'; title: string; sections: ReadingsCard[] }
/** One section at a time. */ /** One section at a time. */
/** `card`: the title, the tabs and the chosen reading in one card (the reading's own title is | { kind: 'choice'; title: string; choices: { label: string; section: ReadingsCard }[] }
* left out: its tab names it) */
| {
kind: 'choice';
title: string;
choices: { label: string; section: ReadingsCard }[];
card?: boolean;
}
| { kind: 'figures'; title?: string; figures: FigureSpec[] } | { kind: 'figures'; title?: string; figures: FigureSpec[] }
| { | {
kind: 'boxes'; kind: 'boxes';
@@ -127,22 +113,17 @@ const BIRADS: Catalog = {
{ code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' }, { code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' },
], ],
}; };
const BREAST_BIOPSY: Catalog = {
/** A breast biopsy's grades, and what stands in their place when there is none. */ groups: [
const BIOPSY_GRADES = [ { id: 'benign', label: 'No maligno', color: '#42C29C' },
{ code: 'benign', label: 'Benigno', color: '#A8C243' }, { id: 'malignant', label: 'Maligno', color: ROSE },
{ code: 'in_situ', label: 'Carcinoma in situ', color: '#9C42C2' }, ],
{ code: 'invasive', label: 'Carcinoma invasor', color: '#5C42C2' }, categories: [
]; { code: 'benign', label: 'Benigno', color: OLIVE, group: 'benign' },
/** What «Sin biopsia» says, whatever the contract's category is called. */ { code: 'in_situ', label: 'Carcinoma in situ', color: '#9C42C2', group: 'malignant' },
const NO_BIOPSY_MEANS = { code: 'invasive', label: 'Carcinoma invasor', color: '#5C42C2', group: 'malignant' },
'«Sin biopsia»: no existe una biopsia vinculada según los datos disponibles.'; ],
const INSTITUTIONAL = '#A8C243'; };
const NEUTRAL = '#C9CDD2';
const NO_RESULT = [
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#C9CDD2' },
{ code: 'no_data', label: 'Sin dato', color: '#8C949C' },
];
export const PAGES: Record<string, Page> = { export const PAGES: Record<string, Page> = {
tea: { tea: {
@@ -248,9 +229,9 @@ export const PAGES: Record<string, Page> = {
}, },
{ {
measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA', measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
title: 'Tasa de detección histopatológica', title: 'Tasa de confirmación histopatológica',
value: '{pct} %', value: '{pct} %',
note: '{num} de {den} biopsias con grado conocido presentan carcinoma (in situ o invasor).', note: '{num} de {den} biopsias con riesgo a carcinoma.',
}, },
{ {
measure: 'CAMA_EU38A', measure: 'CAMA_EU38A',
@@ -270,27 +251,21 @@ export const PAGES: Record<string, Page> = {
], ],
opportunity: [ opportunity: [
{ {
kind: 'route', kind: 'boxes',
title: 'Tiempo de tamizaje a diagnóstico', title: 'Tiempo de tamizaje a diagnóstico',
// from the mammography: only the two measures that start at it subtitles: true,
sample: [ cards: [
{ label: 'Interpretación radiológica', measure: 'CAMA_EU38A' },
{ {
label: 'Diagnóstico (tiempo total de tamizaje a diagnóstico)', measure: 'CAMA_EU38A',
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', title: 'Tiempo de toma de mastografía a interpretación radiológica',
}, },
],
step: [
{ label: 'Toma de mastografía a interpretación radiológica', measure: 'CAMA_EU38A' },
{ {
label: 'Interpretación radiológica a diagnóstico',
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO', 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' },
label: 'Interpretación radiológica a resultado de biopsia', { title: 'Tiempo de diagnóstico a tratamiento' },
measure: 'CAMA_DIAS_RESULTADO_BIOPSIA', { measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', title: 'Tiempo de tamizaje a diagnóstico' },
},
{ label: 'Diagnóstico a tratamiento' },
], ],
}, },
], ],
@@ -315,78 +290,34 @@ export const PAGES: Record<string, Page> = {
], ],
}, },
{ {
kind: 'readings', kind: 'figures',
title: 'Resultado histopatológico por categoría BI-RADS', title: 'Resultado histopatológico por categoría BI-RADS',
note: 'Pacientes: su mastografía BI-RADS 4, 5 o 6 más grave y su biopsia más grave reportada, por fecha del examen. El porcentaje maligno se calcula solo sobre las pacientes con biopsia con grado.', figures: [
modes: [
{ {
kind: 'outcomes', kind: 'rates',
label: 'Por categoría BI-RADS', title: 'Por categoría BI-RADS, {p}',
heading: 'Resultados por paciente',
caption: NO_BIOPSY_MEANS,
measure: 'CAMA_HISTOPATOLOGIA_BIRADS', measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
stratum: 'birads', stratum: 'birads',
rows: BIRADS.categories, rows: BIRADS.categories,
results: [...BIOPSY_GRADES, ...NO_RESULT], colored: true,
malignant: ['in_situ', 'invasive'], positive: ['in_situ', 'invasive'],
axis: 'Porcentaje con resultado maligno',
}, },
{ {
kind: 'counts', kind: 'donut',
label: 'Todas las categorías', title: 'Resultado de la biopsia, {p}',
heading: 'Resultados por paciente',
caption: `Todas las categorías BI-RADS juntas. ${NO_BIOPSY_MEANS}`,
measure: 'CAMA_HISTOPATOLOGIA_BIRADS', measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
catalog: [...BIOPSY_GRADES, ...NO_RESULT], catalog: BREAST_BIOPSY,
percent: true, center: 'con resultado',
}, },
], ],
}, },
{ {
kind: 'choice', kind: 'card',
title: 'Confirmación histopatológica', measure: 'CAMA_CONFIRMACION_BIRADS45',
card: true, title: 'Tasa de confirmación histopatológica',
choices: [ value: '{pct} %',
{ note: '{num} de {den} mastografías BI-RADS 4 y 5 con reporte de biopsia.',
label: 'Resultado de biopsias',
section: {
kind: 'readings',
title: 'Resultado de biopsias',
headline: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
unit: 'biopsias',
note: 'Biopsias con resultado reportado, por fecha del reporte (no son pacientes ni mastografías). La tasa divide los carcinomas (in situ o invasor) entre biopsias con grado conocido. Los porcentajes de la distribución incluyen todas las biopsias reportadas, también «Sin dato» (sin grado), por lo que sus denominadores pueden ser distintos.',
modes: [
{
kind: 'counts',
label: 'Biopsias reportadas',
heading: 'Biopsias reportadas',
measure: 'CAMA_BIOPSIAS',
catalog: [...BIOPSY_GRADES, NO_RESULT[1]],
percent: true,
},
],
},
},
{
label: 'Mastografías con biopsia',
section: {
kind: 'readings',
title: 'Mastografías con biopsia',
headline: 'CAMA_CONFIRMACION_BIRADS45',
unit: 'mastografías',
note: 'Mastografías BI-RADS 4, 4A, 4B, 4C o 5 con reporte, por fecha del examen: cuántas tienen un reporte de biopsia. Mide el seguimiento, no el resultado de la biopsia; no es equivalente a la tasa de detección.',
modes: [
{
kind: 'split',
label: 'Con y sin biopsia',
measure: 'CAMA_CONFIRMACION_BIRADS45',
yes: 'Con reporte de biopsia',
no: 'Sin reporte de biopsia',
colors: [INSTITUTIONAL, NEUTRAL],
},
],
},
},
],
}, },
], ],
}, },
+31 -90
View File
@@ -2,18 +2,15 @@ import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { Figure, Plot } from '../plot'; import { Figure, Plot } from '../plot';
import { bars, Mode } from './bars'; import { bars, Mode, unavailable } from './bars';
import { Reading } from './measures'; import { Reading } from './measures';
/** A card read one mode at a time: its title, its headline, the toggle and the bars. */ /** A card read one mode at a time: its title, its headline, the toggle and the bars. */
@Component({ @Component({
selector: 'app-readings', selector: 'app-readings',
host: { '[class.cama]': 'camaStyle()' },
imports: [Loading, MatButtonToggleModule, Plot], imports: [Loading, MatButtonToggleModule, Plot],
template: ` template: `
@if (!hideTitle()) { <h3 class="title">{{ title() }}</h3>
<h3 class="title">{{ title() }}</h3>
}
@if (headline()) { @if (headline()) {
<p class="headline">{{ headline() }}</p> <p class="headline">{{ headline() }}</p>
} }
@@ -31,16 +28,15 @@ import { Reading } from './measures';
} }
</mat-button-toggle-group> </mat-button-toggle-group>
} }
@if (mode().heading) {
<h4 class="heading">{{ mode().heading }}</h4>
}
@if (mode().caption) { @if (mode().caption) {
<p class="state">{{ mode().caption }}</p> <p class="state">{{ mode().caption }}</p>
} }
@if (loading()) { @if (loading()) {
<app-loading what="la figura" [figure]="true" /> <app-loading what="la figura" [figure]="true" />
} @else if (missing(); as why) {
<p class="state" role="status">{{ why }}</p>
} @else if (figure(); as f) { } @else if (figure(); as f) {
<app-plot [figure]="f" [height]="300" /> <app-plot [figure]="f" [height]="height()" />
} @else if (table(); as t) { } @else if (table(); as t) {
<table [attr.aria-label]="mode().label"> <table [attr.aria-label]="mode().label">
<thead> <thead>
@@ -56,31 +52,19 @@ import { Reading } from './measures';
<tr> <tr>
<th scope="row"> <th scope="row">
{{ row.label }} {{ row.label }}
@if (row.none) { @if (row.hint) {
<span class="none">{{ row.none }}</span> <span class="hint">{{ row.hint }}</span>
} @else {
<span class="track" [class.parts]="!!row.segments" aria-hidden="true">
@if (row.segments; as parts) {
@for (p of parts; track $index) {
<span
class="bar"
[style.width.%]="p.width"
[style.background]="p.color"
[attr.title]="p.title"
></span>
}
} @else {
<span
class="bar"
[style.width.%]="row.width"
[style.background]="row.color"
></span>
}
@for (m of row.marks; track $index) {
<span class="mark" [style.left.%]="m"></span>
}
</span>
} }
<span class="track" aria-hidden="true">
<span
class="bar"
[style.width.%]="row.width"
[style.background]="row.color"
></span>
@for (m of row.marks; track $index) {
<span class="mark" [style.left.%]="m" [style.background]="t.markColor"></span>
}
</span>
</th> </th>
@for (c of row.cells; track $index) { @for (c of row.cells; track $index) {
<td>{{ c }}</td> <td>{{ c }}</td>
@@ -89,12 +73,8 @@ import { Reading } from './measures';
} }
</tbody> </tbody>
</table> </table>
@if (t.legend; as legend) { @if (t.note) {
<p class="legend"> <p class="state">{{ t.note }}</p>
@for (l of legend; track l.label) {
<span><i [style.background]="l.color"></i>{{ l.label }}</span>
}
</p>
} }
} @else { } @else {
<p class="state">Sin datos en el periodo.</p> <p class="state">Sin datos en el periodo.</p>
@@ -105,32 +85,12 @@ import { Reading } from './measures';
display: block; display: block;
min-width: 0; min-width: 0;
} }
:host(.cama) {
overflow-x: auto;
}
.title { .title {
margin: 0 0 8px; margin: 0 0 8px;
} }
:host(.cama) .title {
font-size: 18px;
font-weight: 500;
}
.heading {
font-size: 14px;
font-weight: 500;
margin: 12px 0 4px;
}
.headline { .headline {
font-weight: 500; font-weight: 500;
} }
:host(.cama) .headline {
margin: 8px 0;
}
:host(.cama) .state {
color: var(--color-text-secondary);
font-size: 13px;
margin: 8px 0;
}
mat-button-toggle-group { mat-button-toggle-group {
flex-wrap: wrap; flex-wrap: wrap;
margin: 4px 0; margin: 4px 0;
@@ -139,12 +99,6 @@ import { Reading } from './measures';
border-collapse: collapse; border-collapse: collapse;
width: 100%; width: 100%;
} }
:host(.cama) table {
font-size: 13px;
}
:host(.cama) thead th {
font-weight: 500;
}
th, th,
td { td {
font-weight: 400; font-weight: 400;
@@ -157,6 +111,11 @@ import { Reading } from './measures';
white-space: normal; white-space: normal;
width: 60%; width: 60%;
} }
.hint {
color: var(--mat-sys-on-surface-variant, #5f6368);
display: block;
font-size: 0.8em;
}
.track { .track {
background: rgba(0, 0, 0, 0.06); background: rgba(0, 0, 0, 0.06);
display: block; display: block;
@@ -168,28 +127,6 @@ import { Reading } from './measures';
display: block; display: block;
height: 100%; height: 100%;
} }
.parts {
display: flex;
}
.none {
color: rgba(0, 0, 0, 0.6);
display: block;
font-size: 12px;
font-weight: 400;
}
.legend {
display: flex;
flex-wrap: wrap;
font-size: 12px;
gap: 4px 16px;
margin: 8px 0 0;
}
.legend i {
display: inline-block;
height: 10px;
margin-right: 6px;
width: 10px;
}
.mark { .mark {
background: #333; background: #333;
height: 12px; height: 12px;
@@ -203,9 +140,6 @@ export class Readings {
readonly title = input.required<string>(); readonly title = input.required<string>();
readonly headline = input(''); readonly headline = input('');
readonly note = input(''); readonly note = input('');
/** the card around it names it already (tabs inside one card) */
readonly hideTitle = input(false);
readonly camaStyle = input(false);
readonly modes = input.required<Mode[]>(); readonly modes = input.required<Mode[]>();
readonly loading = input(false); readonly loading = input(false);
/** A measure's reading in the applied period, and the figure of a mode that has one. */ /** A measure's reading in the applied period, and the figure of a mode that has one. */
@@ -217,6 +151,13 @@ export class Readings {
() => this.modes().find((m) => m.label === this.chosen()) ?? this.modes()[0], () => this.modes().find((m) => m.label === this.chosen()) ?? this.modes()[0],
); );
protected readonly table = computed(() => bars(this.mode(), this.read())); protected readonly table = computed(() => bars(this.mode(), this.read()));
/** The bars of a scenarios figure need more room than a donut. */
protected readonly height = computed(() => {
const m = this.mode();
return m.kind === 'figure' && m.figure === 'scenarios' ? 360 : 300;
});
/** Patients in the period but no classification published: say it, do not draw nothing. */
protected readonly missing = computed(() => unavailable(this.mode(), this.read()));
protected readonly figure = computed(() => protected readonly figure = computed(() =>
this.mode().kind === 'figure' ? this.draw()(this.mode()) : undefined, this.mode().kind === 'figure' ? this.draw()(this.mode()) : undefined,
); );
-183
View File
@@ -1,183 +0,0 @@
import { Component, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { Loading } from '../loading';
import { DurationRow, durationMax } from './durations';
/** A screening route as one compact card: a bar per step with its median, its observations
* and its quartiles, read step by step or cumulatively from the sample. A step that is not
* published, or has no measurements in the period, keeps its row and says so. */
@Component({
selector: 'app-route-card',
imports: [Loading, MatButtonToggleModule, MatCardModule],
template: `
<mat-card appearance="outlined">
<mat-card-content>
<div class="head">
<h3>{{ title() }}</h3>
@if (sample().length && step().length) {
<mat-button-toggle-group
aria-label="Lectura de los tiempos"
[value]="mode()"
(change)="mode.set($event.value)"
>
<mat-button-toggle value="step">Por pasos</mat-button-toggle>
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
</mat-button-toggle-group>
}
</div>
@if (loading()) {
<app-loading what="los tiempos" [figure]="true" />
} @else {
@let rows = mode() === 'sample' ? sample() : step();
@let max = scale(rows);
<p class="state">
@if (mode() === 'sample') {
Mediana de días desde la toma de la mastografía hasta cada etapa; cada medida se
calcula por separado.
} @else {
Cada barra es la mediana de su paso, desde cero y por separado; los pasos pueden
corresponder a poblaciones diferentes, por lo que las medianas no se suman.
}
Las marcas indican el primer y tercer cuartil.
@if (max) {
Escala: 0 a {{ max }} días.
}
</p>
<table [attr.aria-label]="title()">
<thead>
<tr>
<th>{{ mode() === 'sample' ? 'Etapa' : 'Paso' }}</th>
<th>Mediana</th>
<th>Observaciones</th>
<th>Q1–Q3</th>
</tr>
</thead>
<tbody>
@for (row of rows; track row.label) {
<tr [attr.data-status]="row.status">
<th scope="row">
{{ row.label }}
@if (row.status === 'value') {
<span class="track" aria-hidden="true">
<span
class="bar"
[style.width.%]="max ? (100 * row.median!) / max : 0"
></span>
@if (row.low !== undefined && row.high !== undefined) {
<span
class="mark"
[style.left.%]="max ? (100 * row.low) / max : 0"
></span>
<span
class="mark"
[style.left.%]="max ? (100 * row.high) / max : 0"
></span>
}
</span>
} @else {
<span class="none">
{{
row.status === 'empty'
? 'Sin mediciones en el periodo'
: 'Indicador no publicado'
}}
</span>
}
</th>
<td>{{ row.status === 'value' ? row.median + ' días' : '—' }}</td>
<td>{{ row.observations ?? '—' }}</td>
<td>
{{
row.low === undefined || row.high === undefined
? '—'
: row.low + '–' + row.high
}}
</td>
</tr>
}
</tbody>
</table>
}
</mat-card-content>
</mat-card>
`,
styles: `
:host {
display: block;
margin-top: 24px;
}
.head {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
justify-content: space-between;
}
h3 {
font-size: 18px;
font-weight: 500;
margin: 0;
}
.state {
color: var(--color-text-secondary);
font-size: 13px;
margin: 8px 0;
}
table {
border-collapse: collapse;
font-size: 13px;
width: 100%;
}
th {
font-weight: 500;
text-align: left;
}
th[scope='row'] {
padding: 5px 0;
}
td,
thead th:not(:first-child) {
font-variant-numeric: tabular-nums;
padding-left: 12px;
text-align: right;
white-space: nowrap;
}
.track {
background: #eef1f3;
display: block;
height: 8px;
margin-top: 3px;
position: relative;
}
.bar {
background: #42a77e;
display: block;
height: 100%;
}
.mark {
background: #17324d;
height: 14px;
position: absolute;
top: -3px;
width: 2px;
}
.none {
color: var(--color-text-secondary);
display: block;
font-size: 12px;
font-weight: 400;
margin-top: 3px;
}
`,
})
export class RouteCard {
readonly title = input.required<string>();
/** The rows from the sample, and the rows step by step. */
readonly sample = input.required<DurationRow[]>();
readonly step = input.required<DurationRow[]>();
readonly loading = input(false);
protected readonly mode = signal<'sample' | 'step'>('step');
protected readonly scale = durationMax;
}
+16 -54
View File
@@ -5,7 +5,7 @@ import type { Measure } from 'fhir/r4';
import { Mode } from './bars'; import { Mode } from './bars';
import { scenarioBars } from './figures'; import { scenarioBars } from './figures';
import { detail, donut, formatScore, name, Reading, scoring } from './measures'; import { detail, donut, formatScore, name, Reading, scoring } from './measures';
import type { ReadingsCard, Section } from './pages'; import type { Section } from './pages';
import { Readings } from './readings'; import { Readings } from './readings';
/** The applied period's readings and the measures they are of. */ /** The applied period's readings and the measures they are of. */
@@ -27,8 +27,7 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
<mat-card-content> <mat-card-content>
<app-readings <app-readings
[title]="s.title" [title]="s.title"
[camaStyle]="hasCamaHeading(s)" [headline]="headline()"
[headline]="headlineOf(s)"
[note]="s.note ?? ''" [note]="s.note ?? ''"
[modes]="s.modes" [modes]="s.modes"
[loading]="of().loading" [loading]="of().loading"
@@ -37,37 +36,6 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
/> />
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
} @else if (s.kind === 'choice' && s.card) {
@let open = chosen() || s.choices[0].label;
<mat-card appearance="outlined" class="choice-card">
<mat-card-content>
<h3 class="title">{{ s.title }}</h3>
<mat-button-toggle-group
[attr.aria-label]="s.title"
[value]="open"
(change)="chosen.set($event.value)"
>
@for (c of s.choices; track c.label) {
<mat-button-toggle [value]="c.label">{{ c.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
@for (c of s.choices; track c.label) {
@if (c.label === open) {
<app-readings
[title]="c.section.title"
[hideTitle]="true"
[camaStyle]="true"
[headline]="headlineOf(c.section)"
[note]="c.section.note ?? ''"
[modes]="c.section.modes"
[loading]="of().loading"
[read]="of().reading"
[draw]="draw()"
/>
}
}
</mat-card-content>
</mat-card>
} @else { } @else {
<h2>{{ s.title }}</h2> <h2>{{ s.title }}</h2>
@if (s.kind === 'columns') { @if (s.kind === 'columns') {
@@ -98,17 +66,9 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
styles: ` styles: `
:host { :host {
display: block; display: block;
margin-top: 24px; margin-top: 16px;
min-width: 0; min-width: 0;
} }
.title {
font-size: 18px;
font-weight: 500;
margin: 0 0 8px;
}
.choice-card app-readings {
margin-top: 8px;
}
.columns { .columns {
display: grid; display: grid;
column-gap: 16px; column-gap: 16px;
@@ -124,26 +84,28 @@ export class ReadingsSection {
readonly of = input.required<Source>(); readonly of = input.required<Source>();
protected readonly chosen = signal(''); protected readonly chosen = signal('');
protected hasCamaHeading(s: ReadingsCard): boolean { protected readonly headline = computed(() => {
return s.modes.some((mode) => !!mode.heading); const s = this.section();
} const code = s.kind === 'readings' ? s.headline : undefined;
/** A reading card's headline: its measure's score and its counts, in its own units. */
protected headlineOf(s: ReadingsCard): string {
const code = s.headline;
const measure = code && this.of().measure(code); const measure = code && this.of().measure(code);
const r = code && this.of().reading(code); const r = code && this.of().reading(code);
if (!measure || !r) return ''; if (!measure || !r) return '';
const words = detail(measure, r, s.unit); const words = detail(measure, r);
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`; return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
} });
protected readonly draw = computed(() => (mode: Mode) => { protected readonly draw = computed(() => (mode: Mode) => {
if (mode.kind !== 'figure') return undefined; if (mode.kind !== 'figure') return undefined;
const r = this.of().reading(mode.measure); const r = this.of().reading(mode.measure);
const measure = this.of().measure(mode.measure); const measure = this.of().measure(mode.measure);
if (!measure || !r?.populations['initial-population']) return undefined; if (!measure || !r?.populations['initial-population']) return undefined;
if (mode.figure === 'donut') return donut(measure, r); if (mode.figure === 'donut') return donut(measure, r, 'category', mode.colors);
const categories = (mode.catalog ?? []).map((c) => ({ ...c, group: '' })); const categories = (mode.catalog ?? []).map((c) => ({ ...c, group: '' }));
return scenarioBars(r, { groups: [], categories }, 'follow_up_status', name); return scenarioBars(
r,
{ groups: [], categories },
mode.stratum ?? 'follow_up_status',
name,
mode.complete ? mode.order : undefined,
);
}); });
} }
-8
View File
@@ -90,14 +90,6 @@
@case ('choice') { @case ('choice') {
<app-section [section]="section" [of]="of()" /> <app-section [section]="section" [of]="of()" />
} }
@case ('route') {
<app-route-card
[title]="section.title"
[sample]="stepRows(section, 'sample')"
[step]="stepRows(section, 'step')"
[loading]="reports.isLoading()"
/>
}
@case ('tea-summary') { @case ('tea-summary') {
@if (teaSummary(); as t) { @if (teaSummary(); as t) {
<mat-card appearance="outlined" class="summary"> <mat-card appearance="outlined" class="summary">
-12
View File
@@ -8,7 +8,6 @@ import { MatSelectModule } from '@angular/material/select';
import type { Measure, MeasureReport } from 'fhir/r4'; import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir'; import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot'; import { Figure, Plot } from '../plot';
import { DurationRow, durationRows } from './durations';
import { LAYOUTS } from './layout'; import { LAYOUTS } from './layout';
import { import {
ageShare, ageShare,
@@ -38,7 +37,6 @@ import {
strataBars, strataBars,
} from './measures'; } from './measures';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { RouteCard } from './route-card';
import { ReadingsSection, Source } from './section'; import { ReadingsSection, Source } from './section';
/** The period's indicators: the timeliness KPIs, the screening route, and a card per /** The period's indicators: the timeliness KPIs, the screening route, and a card per
@@ -55,7 +53,6 @@ import { ReadingsSection, Source } from './section';
MatSelectModule, MatSelectModule,
Plot, Plot,
ReadingsSection, ReadingsSection,
RouteCard,
], ],
templateUrl: './tab-indicadores.html', templateUrl: './tab-indicadores.html',
styleUrl: './tab-indicadores.scss', styleUrl: './tab-indicadores.scss',
@@ -197,15 +194,6 @@ export class TabIndicadores {
} }
protected readonly name = name; protected readonly name = name;
protected stepRows(section: Section, mode: 'sample' | 'step'): DurationRow[] {
if (section.kind !== 'route') return [];
return durationRows(
section[mode],
(code) => this.rd(code),
(code) => this.byName().has(code),
);
}
/** A measure's reading in the applied period, by code. */ /** A measure's reading in the applied period, by code. */
protected rd(code: string): Reading | undefined { protected rd(code: string): Reading | undefined {
return this.loaded()?.get(code); return this.loaded()?.get(code);