diff --git a/e2e/cacu.spec.ts b/e2e/cacu.spec.ts
index d7ef7c1..7fad114 100644
--- a/e2e/cacu.spec.ts
+++ b/e2e/cacu.spec.ts
@@ -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 }) => {
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.')),
).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
+ .locator('app-readings', {
+ has: page.getByRole('heading', { name: 'Valor predictivo positivo de la biopsia' }),
+ })
+ .getByRole('radio', round)
+ .click();
await expect(
tab.getByRole('heading', { name: 'Valor predictivo positivo de la biopsia' }),
).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();
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('
')[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([]);
+ });
+}
diff --git a/e2e/simulated-rounds.ts b/e2e/simulated-rounds.ts
new file mode 100644
index 0000000..382cfb0
--- /dev/null
+++ b/e2e/simulated-rounds.ts
@@ -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',
+ });
+ });
+}
diff --git a/src/app/indicadores/bars.spec.ts b/src/app/indicadores/bars.spec.ts
index 79b264d..ece80ac 100644
--- a/src/app/indicadores/bars.spec.ts
+++ b/src/app/indicadores/bars.spec.ts
@@ -1,4 +1,5 @@
-import { bars } from './bars';
+import { bars, unavailable } from './bars';
+import { scenarioBars } from './figures';
import { Reading } from './measures';
describe('bars', () => {
@@ -24,4 +25,146 @@ describe('bars', () => {
const mode = { kind: 'shares', label: 'x', measure: 'M', stratum: 's', order: ['initial'] };
expect(bars(mode as any, () => r)!.rows[0].cells).toEqual(['0/0', '—']);
});
+
+ describe('screening rounds (complete)', () => {
+ const ORDER = ['initial', 'subsequent', 'no_data'];
+ const cell = (numerator: number, denominator: number) => ({ numerator, denominator });
+ const ppv = (strata: Record, total: number): Reading => ({
+ 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 %'],
+ ]);
+ });
+ });
+
+ describe('cytology by round', () => {
+ const cats = [
+ { code: 'NILM', label: 'Normal', color: '#0a0', group: '' },
+ { code: 'HSIL', label: 'LIEAG', color: '#a00', group: '' },
+ ];
+ const reading = (cells: Record, total: number): Reading => ({
+ populations: { 'initial-population': total },
+ strata: {
+ 'round-category': Object.fromEntries(
+ Object.entries(cells).map(([k, n]) => [k, { 'initial-population': n }]),
+ ),
+ },
+ });
+ const draw = (r: Reading) =>
+ scenarioBars(
+ r,
+ { groups: [], categories: cats },
+ 'round',
+ (c) =>
+ c === 'initial'
+ ? 'Detección inicial'
+ : c === 'subsequent'
+ ? 'Detección subsecuente'
+ : 'Sin dato',
+ ['initial', 'subsequent', 'no_data'],
+ );
+
+ it('keeps the order and shows each bar with its n, an empty one included', () => {
+ const f = draw(
+ reading({ 'subsequent|NILM': 6, 'subsequent|HSIL': 2, 'no_data|NILM': 2 }, 10),
+ );
+ const y = (f.data[0] as any).y;
+ expect(y).toEqual([
+ 'Detección inicial
n = 0',
+ 'Detección subsecuente
n = 8',
+ 'Sin dato
n = 2',
+ ]);
+ expect((f.data[0] as any).x).toEqual([0, 75, 100]);
+ });
+ it('leaves out a group that does not reconcile', () => {
+ const f = draw(reading({ 'subsequent|NILM': 6 }, 10));
+ expect((f.data[0] as any).y).toEqual(['Detección subsecuente
n = 6']);
+ });
+ });
});
diff --git a/src/app/indicadores/bars.ts b/src/app/indicadores/bars.ts
index 5bfba09..87e5a8e 100644
--- a/src/app/indicadores/bars.ts
+++ b/src/app/indicadores/bars.ts
@@ -1,4 +1,5 @@
import { CIE10 } from './cie10';
+import { NEUTRAL_DARK } from './cacu-palette';
import { name, Reading } from './measures';
/** A category as drawn: its code in the report, its name and its colour. */
@@ -7,17 +8,49 @@ export type Category = { code: string; label: string; color: string };
/** One way of reading a card, as bars from the reports, or a figure. */
export type Mode = { label: string; caption?: string } & (
| { kind: 'counts'; measure: string; catalog: Category[] }
- | { kind: 'shares'; measure: string; stratum: string; order: string[] }
- | { kind: 'positives'; measure: string; stratum: string; order: string[] }
- | { kind: 'signs'; measure: string; strata: string[] }
- | { kind: 'days'; steps: { label: string; measure: string }[] }
- | { kind: 'days-by'; measure: string; stratum: string }
- | { kind: 'figure'; measure: string; figure: 'donut' | 'scenarios'; catalog?: Category[] }
+ | {
+ kind: 'shares';
+ measure: string;
+ stratum: string;
+ order: string[];
+ complete?: boolean;
+ colors?: Colors;
+ }
+ | {
+ kind: 'positives';
+ measure: string;
+ stratum: string;
+ order: string[];
+ complete?: boolean;
+ colors?: Colors;
+ }
+ | { kind: 'signs'; measure: string; strata: string[]; colors?: Colors }
+ | { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint }
+ | { kind: 'days-by'; measure: string; stratum: string; tint?: Tint }
+ | {
+ kind: 'figure';
+ measure: string;
+ figure: 'donut' | 'scenarios';
+ /** a donut's colour by part (a category, or numerator and rest); none: the page's palette */
+ 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;
+/** 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. */
export interface Bar {
label: string;
+ /** why the row has no figures: no patients in the group, or not available */
+ hint?: string;
color?: string;
width: number;
marks: number[];
@@ -26,6 +59,45 @@ export interface Bar {
export interface Bars {
head: string[];
rows: Bar[];
+ /** the colour of the quartile marks, when the card has its own */
+ 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)} %` : '—');
@@ -44,7 +116,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
const rest = Object.keys(cells).filter((c) => !named.includes(c));
const all = [
...mode.catalog,
- ...rest.map((code) => ({ code, label: name(code), color: '#9AA3AB' })),
+ ...rest.map((code) => ({ code, label: name(code), color: NEUTRAL_DARK })),
];
const most = Math.max(...Object.values(cells).map(size));
return {
@@ -57,23 +129,63 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
};
}
case 'shares': {
- const cells = of(mode.measure)?.strata[mode.stratum] ?? {};
- return ratios(
- mode.order
- .filter((c) => cells[c])
- .map((c) => [name(c), cells[c]['numerator'] ?? 0, cells[c]['denominator'] ?? 0]),
+ const r = of(mode.measure);
+ const cells = r?.strata[mode.stratum] ?? {};
+ if (!mode.complete)
+ return ratios(
+ 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': {
- 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]));
- return ratios(
- mode.order
- .filter((c) => found.has(c))
- .map((c) => {
- const positive = size(cells[`${c}|positive`]);
- return [name(c), positive, positive + size(cells[`${c}|negative`])];
- }),
+ if (!mode.complete)
+ return ratios(
+ mode.order
+ .filter((c) => found.has(c))
+ .map((c) => {
+ 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': {
@@ -83,7 +195,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
.filter((s) => Object.keys(strata[s] ?? {}).length)
.map((s) => {
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]];
}),
);
}
@@ -93,6 +205,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
const r = of(measure);
return { label, n: r?.populations['measure-observation'] ?? 0, score: r };
}),
+ mode.tint,
);
case 'days-by': {
const r = of(mode.measure);
@@ -105,6 +218,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
score: r?.scores?.[mode.stratum]?.[c],
}))
.sort((a, b) => b.n - a.n),
+ mode.tint,
);
}
default:
@@ -112,12 +226,62 @@ export function bars(mode: Mode, of: (measure: string) => Reading | 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;
return {
head: ['n/N', '%'],
- rows: rows.map(([label, n, total]) => ({
+ rows: rows.map(([label, n, total, color]) => ({
label,
+ color,
width: total ? (100 * n) / total : 0,
marks: [],
cells: [`${n}/${total}`, pct(n, total)],
@@ -126,17 +290,22 @@ function ratios(rows: [string, number, number][]): Bars | undefined {
}
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;
const top = Math.max(...rows.flatMap((r) => [r.score?.score ?? 0, r.score?.high ?? 0])) || 1;
const at = (v: number) => (100 * v) / top;
return {
head: ['Mediana', 'n', 'Q1–Q3'],
+ markColor: tint?.mark,
rows: rows.map(({ label, n, score: s }) => {
if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] };
const spread = s.low !== undefined && s.high !== undefined ? [s.low, s.high] : [];
return {
label,
+ color: tint?.bar,
width: at(s.score),
marks: spread.map(at),
cells: [`${days(s.score)} días`, `${n}`, spread.map(days).join('–') || '—'],
diff --git a/src/app/indicadores/cacu-palette.spec.ts b/src/app/indicadores/cacu-palette.spec.ts
new file mode 100644
index 0000000..70d5411
--- /dev/null
+++ b/src/app/indicadores/cacu-palette.spec.ts
@@ -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'],
+ ]);
+ });
+});
diff --git a/src/app/indicadores/cacu-palette.ts b/src/app/indicadores/cacu-palette.ts
new file mode 100644
index 0000000..32b3170
--- /dev/null
+++ b/src/app/indicadores/cacu-palette.ts
@@ -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 = {
+ 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 = {
+ 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 = {
+ 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 = {
+ 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 = {
+ 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 = {
+ pre_colposcopy: STEEL,
+ post_colposcopy: STEEL_MID,
+ post_treatment: STEEL_LIGHT,
+ case: NEUTRAL_DARK,
+};
+export const AGE_COLORS: Record = 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 = {
+ 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 = {
+ 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 = {
+ negative: HPV_COLORS['negative'],
+ positive: HPV_COLORS['positive_other'],
+};
+export const PPV_DONUT: Record = { numerator: '#6A8000', rest: NEUTRAL };
+
+/** Median bars of the screening route, and the marks of their quartiles. */
+export const DURATION = '#42A77E';
+export const QUARTILE = '#17324D';
diff --git a/src/app/indicadores/figures.ts b/src/app/indicadores/figures.ts
index 88596dc..a482b51 100644
--- a/src/app/indicadores/figures.ts
+++ b/src/app/indicadores/figures.ts
@@ -1,4 +1,5 @@
import { type Figure, PALETTE } from '../plot';
+import { reconciles } from './bars';
import { name, type Reading } from './measures';
import type { Catalog, Category, HistoryPanel } from './pages';
@@ -96,14 +97,25 @@ export function scenarioBars(
catalog: Catalog,
stratum: string,
label: (code: string) => string,
+ /** the groups in this order; an empty one is drawn when the counts reconcile (see `reconciles`) */
+ order?: 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 found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
+ 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 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)}
n = ${totals[i]}`)
+ : scenarios.map(label);
return {
data: catalog.categories.map((c) => ({
type: 'bar',
@@ -118,7 +130,11 @@ export function scenarioBars(
layout: {
barmode: 'stack',
xaxis: {
- title: { text: '% de pacientes del escenario con resultado' },
+ title: {
+ text: order
+ ? '% de pacientes con resultado'
+ : '% de pacientes del escenario con resultado',
+ },
ticksuffix: ' %',
range: [0, 100.5],
dtick: 20,
diff --git a/src/app/indicadores/measures.ts b/src/app/indicadores/measures.ts
index 7d9e304..5c76658 100644
--- a/src/app/indicadores/measures.ts
+++ b/src/app/indicadores/measures.ts
@@ -133,8 +133,8 @@ export const LABELS: Record = {
good: 'Bueno',
bad: 'Malo',
not_analyzed: 'Sin analizar',
- initial: 'Inicial',
- subsequent: 'Subsecuente',
+ initial: 'Detección inicial',
+ subsequent: 'Detección subsecuente',
positive: 'Positivo',
negative: 'Negativo',
hpv_16: 'VPH 16',
@@ -202,15 +202,23 @@ export function detail(measure: Measure, r: Reading | undefined): string {
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. */
-export function donut(measure: Measure, r: Reading, stratifier = 'category'): Figure {
- let labels: string[], values: number[];
+export function donut(
+ 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,
+): Figure {
+ let labels: string[], values: number[], codes: string[];
if (scoring(measure) === 'proportion') {
const { numerator = 0, denominator = 0 } = r.populations;
labels = ['Numerador', 'Resto'];
+ codes = ['numerator', 'rest'];
values = [numerator, denominator - numerator];
} else {
const cells = Object.entries(r.strata[stratifier] ?? {});
labels = cells.map(([v]) => name(v));
+ codes = cells.map(([v]) => v);
values = cells.map(([, c]) => c['initial-population'] ?? 0);
}
return {
@@ -222,7 +230,7 @@ export function donut(measure: Measure, r: Reading, stratifier = 'category'): Fi
values,
sort: false,
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 } },
diff --git a/src/app/indicadores/pages-cacu.ts b/src/app/indicadores/pages-cacu.ts
index 786533b..7a360e2 100644
--- a/src/app/indicadores/pages-cacu.ts
+++ b/src/app/indicadores/pages-cacu.ts
@@ -1,4 +1,19 @@
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';
const OLIVE = '#A8C243';
@@ -11,12 +26,12 @@ const CYTOLOGY: Catalog = {
{ 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' },
+ { code: 'NILM', label: 'Normal', color: CYTOLOGY_COLORS['NILM'], group: 'normal' },
+ { code: 'ASC-US', label: 'ASC-US', color: CYTOLOGY_COLORS['ASC-US'], group: 'abnormal' },
+ { code: 'LSIL', label: 'LIEBG', color: CYTOLOGY_COLORS['LSIL'], group: 'abnormal' },
+ { code: 'ASC-H', label: 'ASC-H', color: CYTOLOGY_COLORS['ASC-H'], group: 'abnormal' },
+ { code: 'HSIL', label: 'LIEAG', color: CYTOLOGY_COLORS['HSIL'], 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 },
],
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' },
+ { code: 'normal', label: 'Normal', color: BIOPSY_COLORS['normal'], group: 'low' },
+ { code: 'LSIL', label: 'LIEBG (CIN 1)', color: BIOPSY_COLORS['LSIL'], group: 'low' },
+ { code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: BIOPSY_COLORS['HSIL'], group: 'high' },
+ { code: 'CIS', label: 'Carcinoma in situ', color: BIOPSY_COLORS['CIS'], group: 'high' },
+ {
+ code: 'carcinoma',
+ label: 'Carcinoma invasor',
+ color: BIOPSY_COLORS['carcinoma'],
+ group: 'high',
+ },
],
faded: ['normal', 'LSIL'],
};
/** HPV reports by genotype, and biopsy requests by what became of them. */
const HPV = [
- { code: 'negative', label: 'Negativo', color: '#A8C243' },
- { code: 'positive_16', label: 'VPH 16', color: '#C24269' },
- { code: 'positive_18', label: 'VPH 18', color: '#9C42C2' },
- { code: 'positive_16_18', label: 'VPH 16 y 18', color: '#92324F' },
- { code: 'positive_other', label: 'Otro de alto riesgo', color: '#C54C71' },
- { code: 'positive_incomplete', label: 'Positivo, genotipo incompleto', color: '#C9577A' },
+ { code: 'negative', label: 'Negativo', color: HPV_COLORS['negative'] },
+ { code: 'positive_16', label: 'VPH 16', color: HPV_COLORS['positive_16'] },
+ { code: 'positive_18', label: 'VPH 18', color: HPV_COLORS['positive_18'] },
+ { code: 'positive_16_18', label: 'VPH 16 y 18', color: HPV_COLORS['positive_16_18'] },
+ { code: 'positive_other', label: 'Otro de alto riesgo', color: HPV_COLORS['positive_other'] },
+ {
+ code: 'positive_incomplete',
+ label: 'Positivo, genotipo incompleto',
+ color: HPV_COLORS['positive_incomplete'],
+ },
];
const REQUESTS = [
- { code: 'high_grade', label: 'LIEAG o más', color: '#C24269' },
- { code: 'below_high_grade', label: 'Menor que LIEAG', color: '#A8C243' },
- { code: 'pending', label: 'Pendiente', color: '#C9CDD2' },
- { code: 'no_grade', label: 'Sin grado', color: '#9AA3AB' },
+ { code: 'high_grade', label: 'LIEAG o más', color: REQUEST_COLORS['high_grade'] },
+ { code: 'below_high_grade', label: 'Menor que LIEAG', color: REQUEST_COLORS['below_high_grade'] },
+ { code: 'pending', label: 'Pendiente', color: REQUEST_COLORS['pending'] },
+ { 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. */
const ppv = (measure: string, title: string, note: string, ...more: Mode[]): ReadingsCard => ({
kind: 'readings',
@@ -59,13 +93,14 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
headline: measure,
note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [
- { kind: 'figure', label: 'Total', measure, figure: 'donut' },
+ { kind: 'figure', label: 'Total', measure, figure: 'donut', colors: PPV_DONUT },
{
kind: 'shares',
label: 'Citología previa',
caption: 'La última válida de los 365 días anteriores; cada grupo incluye los más severos.',
measure,
stratum: 'cytology',
+ colors: PPV_CYTOLOGY_COLORS,
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.',
measure,
stratum: 'hpv',
+ colors: HPV_COLORS,
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',
measure,
stratum: 'level',
+ colors: PPV_LEVEL_COLORS,
order: ['cin1_plus', 'cin2_plus', 'carcinoma'],
},
{
kind: 'shares',
- label: 'Tamizaje',
+ label: 'Por detección inicial y subsecuente',
+ caption: ROUND_CAPTION,
measure,
stratum: 'round',
- order: ['initial', 'subsequent', 'no_data'],
+ colors: ROUND_COLORS,
+ order: ROUNDS,
+ complete: true,
},
...more,
],
@@ -136,6 +176,7 @@ export const CACU: Page = {
modes: [
{
kind: 'days',
+ tint: TINT,
label: 'Acumulado desde la toma',
steps: [
{ label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
@@ -146,6 +187,7 @@ export const CACU: Page = {
},
{
kind: 'days',
+ tint: TINT,
label: 'Por pasos',
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
steps: [
@@ -157,6 +199,7 @@ export const CACU: Page = {
},
{
kind: 'days-by',
+ tint: TINT,
label: 'Por CIE-10',
caption: 'Días de la toma al diagnóstico, por el código de la nota que lo fecha.',
measure: 'CACU_TIEMPO_DIAGNOSTICO_CIE10',
@@ -183,10 +226,20 @@ export const CACU: Page = {
},
{
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',
figure: 'scenarios',
catalog: CYTOLOGY.categories,
+ stratum: 'round',
+ order: ROUNDS,
+ complete: true,
},
],
},
@@ -217,12 +270,19 @@ export const CACU: Page = {
headline: 'CACU_VPH',
note: 'Una vez cada paciente, por su última muestra con resultado.',
modes: [
- { kind: 'figure', label: 'Total', measure: 'CACU_VPH', figure: 'donut' },
+ {
+ kind: 'figure',
+ label: 'Total',
+ measure: 'CACU_VPH',
+ figure: 'donut',
+ colors: VPH_DONUT,
+ },
{
kind: 'positives',
label: 'Por grupo de edad',
measure: 'CACU_VPH',
stratum: 'age_group',
+ colors: AGE_COLORS,
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',
measure: 'CACU_VPH',
stratum: 'follow_up_status',
+ colors: STATUS_COLORS,
order: ['pre_colposcopy', 'post_colposcopy', 'post_treatment', 'case'],
},
{
@@ -237,13 +298,17 @@ export const CACU: Page = {
label: 'Por genotipo',
measure: 'CACU_VPH',
strata: ['hpv_16', 'hpv_18'],
+ colors: HPV_COLORS,
},
{
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',
stratum: 'round',
- order: ['initial', 'subsequent', 'no_data'],
+ colors: ROUND_COLORS,
+ order: ROUNDS,
+ complete: true,
},
],
},
diff --git a/src/app/indicadores/readings.ts b/src/app/indicadores/readings.ts
index 8a5985e..54c3c09 100644
--- a/src/app/indicadores/readings.ts
+++ b/src/app/indicadores/readings.ts
@@ -2,7 +2,7 @@ import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { Loading } from '../loading';
import { Figure, Plot } from '../plot';
-import { bars, Mode } from './bars';
+import { bars, Mode, unavailable } from './bars';
import { Reading } from './measures';
/** A card read one mode at a time: its title, its headline, the toggle and the bars. */
@@ -33,8 +33,10 @@ import { Reading } from './measures';
}
@if (loading()) {
+ } @else if (missing(); as why) {
+ {{ why }}
} @else if (figure(); as f) {
-
+
} @else if (table(); as t) {
@@ -50,6 +52,9 @@ import { Reading } from './measures';
|
{{ row.label }}
+ @if (row.hint) {
+ {{ row.hint }}
+ }
@for (m of row.marks; track $index) {
-
+
}
|
@@ -68,6 +73,9 @@ import { Reading } from './measures';
}
+ @if (t.note) {
+ {{ t.note }}
+ }
} @else {
Sin datos en el periodo.
}
@@ -103,6 +111,11 @@ import { Reading } from './measures';
white-space: normal;
width: 60%;
}
+ .hint {
+ color: var(--mat-sys-on-surface-variant, #5f6368);
+ display: block;
+ font-size: 0.8em;
+ }
.track {
background: rgba(0, 0, 0, 0.06);
display: block;
@@ -138,6 +151,13 @@ export class Readings {
() => this.modes().find((m) => m.label === this.chosen()) ?? this.modes()[0],
);
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(() =>
this.mode().kind === 'figure' ? this.draw()(this.mode()) : undefined,
);
diff --git a/src/app/indicadores/section.ts b/src/app/indicadores/section.ts
index 305a507..eafc883 100644
--- a/src/app/indicadores/section.ts
+++ b/src/app/indicadores/section.ts
@@ -98,8 +98,14 @@ export class ReadingsSection {
const r = this.of().reading(mode.measure);
const measure = this.of().measure(mode.measure);
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: '' }));
- 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,
+ );
});
}