Ajustar indicadores, fecha de corte y ficha de CaMa y CaCu

This commit is contained in:
2026-12-03 19:33:13 -06:00
parent 0fe772ed6f
commit cbcb524902
18 changed files with 333 additions and 120 deletions
+7 -7
View File
@@ -9,7 +9,7 @@ test.beforeEach(async ({ page }) => {
const ROUND = { name: 'Por detección inicial y subsecuente' }; const ROUND = { name: 'Por detección inicial y subsecuente' };
const VIEWS_LABEL = 'Lectura de la distribución citológica y del VPH por genotipo'; const VIEWS_LABEL = 'Lectura de la distribución citológica y del VPH por genotipo';
const VIEWS = ['General', 'Por grupo de edad', 'Por estatus de seguimiento', ROUND.name]; const VIEWS = ['General', 'Por grupo de edad', ROUND.name];
const TITLES = { const TITLES = {
cytology: 'Distribución de resultados citológicos', cytology: 'Distribución de resultados citológicos',
genotype: 'Resultados de VPH por genotipo', genotype: 'Resultados de VPH por genotipo',
@@ -28,9 +28,7 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
const headings = await tab const headings = await tab
.locator('h2, app-readings h3') .locator('h2, app-readings h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim())); .evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([ expect(headings.slice(headings.indexOf('Indicadores clínicos'))).toEqual([
'Indicadores de oportunidad',
'Tiempos de tamizaje',
'Indicadores clínicos', 'Indicadores clínicos',
'Resultados de citología, VPH y biopsia', 'Resultados de citología, VPH y biopsia',
'Distribución de resultados citológicos', 'Distribución de resultados citológicos',
@@ -38,9 +36,11 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
'Resultados de biopsia cervical', 'Resultados de biopsia cervical',
'Tasa de confirmación histopatológica', 'Tasa de confirmación histopatológica',
'Tasa de confirmación histopatológica de referencia a colposcopía', 'Tasa de confirmación histopatológica de referencia a colposcopía',
'Indicadores de oportunidad',
'Tiempos de tamizaje',
]); ]);
const route = tab.locator('app-readings').first(); const route = tab.locator('app-readings').filter({ has: page.getByRole('heading', { name: 'Tiempos de tamizaje' }) });
for (const mode of ['Por ventana de tiempo', 'Primer diagnóstico', 'Diagnóstico tras biopsia', 'Acumulado desde la toma']) { for (const mode of ['Por ventana de tiempo', 'Diagnóstico precolposcópico', 'Diagnóstico tras biopsia', 'Acumulado desde la toma']) {
await route.getByRole('radio', { name: mode }).click(); await route.getByRole('radio', { name: mode }).click();
await expect( await expect(
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.')),
@@ -107,7 +107,7 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
await expect( await expect(
tab.getByRole('heading', { name: 'Tasa de confirmación histopatológica de referencia a biopsia' }), tab.getByRole('heading', { name: 'Tasa de confirmación histopatológica de referencia a biopsia' }),
).toBeVisible(); ).toBeVisible();
await tab.getByRole('radio', { name: 'Solicitudes' }).click(); await expect(tab.getByRole('radio', { name: 'Solicitudes' })).toHaveCount(0);
}); });
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => { test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
+20 -1
View File
@@ -251,9 +251,28 @@ for (const domain of ['cama', 'tea']) {
.locator('h2, h3') .locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim())); .evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
const from = headings.indexOf('Indicadores de oportunidad'); const from = headings.indexOf('Indicadores de oportunidad');
if (domain === 'cama') {
const ordered = [
'Días de toma de mastografía a interpretación radiológica',
'Días de interpretación radiológica a diagnóstico',
'Días de tamizaje a diagnóstico',
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
'Pacientes evaluadas con BI-RADS 4, 5 o 6',
'Resultado histopatológico por categoría BI-RADS',
'Confirmación histopatológica',
'Tasa de detección histopatológica',
];
let last = -1;
for (const title of ordered) {
const next = headings.findIndex((h, index) => index > last && h.startsWith(title));
expect(next, title).toBeGreaterThan(last);
last = next;
}
} else {
expect(headings.slice(from).map(period)).toEqual( expect(headings.slice(from).map(period)).toEqual(
old.filter((i) => i.kind !== 'plot').map((i) => period(domain === 'cama' ? i.text.replace(/^Tiempo de /, 'Días de ') : i.text)), old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
); );
}
// Each figure drawn is one of the old kinds (a figure with no data in the period is named). // Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab const drawn = await tab
.locator('.js-plotly-plot') .locator('.js-plotly-plot')
+54 -1
View File
@@ -1,4 +1,4 @@
import { bars, grouped, hiddenNote, Mode, unavailable } from './bars'; import { bars, grouped, hiddenNote, Mode, subsequentHistory, unavailable } from './bars';
import { scenarioBars } from './figures'; import { scenarioBars } from './figures';
import { Reading } from './measures'; import { Reading } from './measures';
@@ -17,6 +17,59 @@ describe('bars', () => {
['1', '25.0 %'], ['1', '25.0 %'],
]); ]);
}); });
it('aggregates only named abnormal cytology results without changing the denominator', () => {
const cell = (n: number) => ({ 'initial-population': n });
const r: Reading = {
populations: { 'initial-population': 10 },
strata: {
category: { NILM: cell(4), LSIL: cell(2), HSIL: cell(1), no_data: cell(3) },
'age_group-category': {
'25-34|NILM': cell(4),
'25-34|LSIL': cell(2),
'25-34|HSIL': cell(1),
'25-34|no_data': cell(3),
},
},
};
const catalog = ['NILM', 'LSIL', 'HSIL'].map((code) => ({ code, label: code, color: '#000' }));
const aggregate = { label: 'Anormal', color: '#f00', codes: ['LSIL', 'HSIL'] };
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog, aggregate }, () => r)!;
expect(t.rows[1].cells).toEqual(['3', '30.0 %']);
const g = grouped(
{
kind: 'grouped',
label: 'x',
measure: 'M',
catalog,
aggregate,
stratum: 'age_group',
order: ['25-34'],
unit: 'pacientes',
ofAll: true,
},
() => r,
)!;
expect(g.groups[0].rows[1].text).toBe('3/10 · 30.0 %');
});
it('shows the form history within subsequent screening without treating missing answers as a category', () => {
const r: Reading = {
populations: {},
strata: {
round: { subsequent: { 'initial-population': 5 } },
subsequent_history: {
within_1_year: { 'initial-population': 1 },
'3_or_more_years': { 'initial-population': 2 },
no_data: { 'initial-population': 2 },
},
},
};
expect(subsequentHistory(r)).toEqual([
{ label: 'Un año o menos', text: '1/5 · 20.0 %' },
{ label: 'Dos años', text: '0/5 · 0.0 %' },
{ label: 'Tres o más años', text: '2/5 · 40.0 %' },
]);
expect(subsequentHistory({ populations: {}, strata: {} })).toBeUndefined();
});
it('a group with no patients has no rate', () => { it('a group with no patients has no rate', () => {
const r: Reading = { const r: Reading = {
populations: {}, populations: {},
+58 -5
View File
@@ -16,6 +16,7 @@ export type Mode = {
kind: 'counts'; kind: 'counts';
measure: string; measure: string;
catalog: Category[]; catalog: Category[];
aggregate?: { label: string; color: string; codes: string[] };
/** The records counted in the category distribution. */ /** The records counted in the category distribution. */
unit?: string; unit?: string;
/** What the share in the second column is a share of. */ /** What the share in the second column is a share of. */
@@ -54,6 +55,7 @@ export type Mode = {
measure: string; measure: string;
/** the categories drawn in each group, in this order (each in its own colour) */ /** the categories drawn in each group, in this order (each in its own colour) */
catalog: Category[]; catalog: Category[];
aggregate?: { label: string; color: string; codes: string[] };
/** the groups' stratifier (its crossed cells `<stratum>-category`) and their order */ /** the groups' stratifier (its crossed cells `<stratum>-category`) and their order */
stratum: string; stratum: string;
order: string[]; order: string[];
@@ -262,10 +264,23 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
const most = mode.percent ? total : Math.max(...Object.values(cells).map(size)); const most = mode.percent ? total : Math.max(...Object.values(cells).map(size));
return { return {
head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'], head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'],
rows: all.map(({ code, label, color }) => { rows: all.flatMap(({ code, label, color }, index) => {
const n = size(cells[code]); const n = size(cells[code]);
const cols = [`${n}`, pct(n, total)]; const cols = [`${n}`, pct(n, total)];
return { label, color, width: (100 * n) / most, marks: [], cells: cols }; const row = { label, color, width: (100 * n) / most, marks: [], cells: cols };
if (index !== 0 || !mode.aggregate) return [row];
const a = mode.aggregate;
const sum = a.codes.reduce((total, key) => total + size(cells[key]), 0);
return [
row,
{
label: a.label,
color: a.color,
width: (100 * sum) / most,
marks: [],
cells: [`${sum}`, pct(sum, total)],
},
];
}), }),
note: hiddenNote(mode, of), note: hiddenNote(mode, of),
}; };
@@ -433,6 +448,24 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
} }
} }
/** Reported form answers within the subsequent round, over that round's own total. */
export function subsequentHistory(reading?: Reading) {
const values = reading?.strata['subsequent_history'];
const den = reading?.strata['round']?.['subsequent']?.['initial-population'] ?? 0;
if (!values) return undefined;
return [
['within_1_year', 'Un año o menos'],
['2_years', 'Dos años'],
['3_or_more_years', 'Tres o más años'],
].map(([code, label]) => {
const count = values[code]?.['initial-population'] ?? 0;
return {
label,
text: `${count}/${den} · ${den ? ((100 * count) / den).toFixed(1) + ' %' : '—'}`,
};
});
}
/** The groups of a grouped mode: each group (an age group, a follow-up status, a screening round) with /** The groups of a grouped mode: each group (an age group, a follow-up status, a screening round) with
* one independent bar per category over the group's own records. A group the report leaves out is * one independent bar per category over the group's own records. A group the report leaves out is
* drawn empty only when the listed ones add up to every record of the period (`complete`). */ * drawn empty only when the listed ones add up to every record of the period (`complete`). */
@@ -464,13 +497,18 @@ export function grouped(
const den = total(code); const den = total(code);
return { return {
code, code,
label: name(code), label:
mode.stratum === 'age_group' &&
code === '<25' &&
['CACU_EU7', 'CACU_VPH_GENOTIPO'].includes(mode.measure)
? '14 años y 10 meses a menos de 25 años'
: name(code),
total: den, total: den,
hint: den ? undefined : `Sin ${mode.unit} en el grupo`, hint: den ? undefined : `Sin ${mode.unit} en el grupo`,
rows: mode.catalog.map((c) => { rows: mode.catalog.flatMap((c, index) => {
const count = n(code, c.code); const count = n(code, c.code);
const percent = den ? (100 * count) / den : undefined; const percent = den ? (100 * count) / den : undefined;
return { const row = {
label: c.label, label: c.label,
color: c.color, color: c.color,
count, count,
@@ -478,6 +516,21 @@ export function grouped(
percent, percent,
text: `${count}/${den} · ${percent === undefined ? '—' : percent.toFixed(1) + ' %'}`, text: `${count}/${den} · ${percent === undefined ? '—' : percent.toFixed(1) + ' %'}`,
}; };
if (index !== 0 || !mode.aggregate) return [row];
const a = mode.aggregate;
const sum = a.codes.reduce((total, key) => total + n(code, key), 0);
const share = den ? (100 * sum) / den : undefined;
return [
row,
{
label: a.label,
color: a.color,
count: sum,
of: den,
percent: share,
text: `${sum}/${den} · ${share === undefined ? '—' : share.toFixed(1) + ' %'}`,
},
];
}), }),
}; };
}); });
+13 -25
View File
@@ -8,13 +8,13 @@ import {
PPV_DONUT, PPV_DONUT,
PPV_LEVEL_COLORS, PPV_LEVEL_COLORS,
QUARTILE, QUARTILE,
REQUEST_COLORS,
ROUND_COLORS, ROUND_COLORS,
} from './cacu-palette'; } from './cacu-palette';
import type { Catalog, Page, ReadingsCard } from './pages'; import type { Catalog, Page, ReadingsCard } from './pages';
const OLIVE = '#A8C243'; const OLIVE = '#A8C243';
const ROSE = '#C24269'; const ROSE = '#C24269';
const ABNORMAL = { label: 'Anormal', color: ROSE, codes: ['ASC-US', 'LSIL', 'ASC-H', 'HSIL', 'CIS', 'carcinoma'] };
/** Bethesda results as the old app grouped and coloured them. */ /** Bethesda results as the old app grouped and coloured them. */
const CYTOLOGY: Catalog = { const CYTOLOGY: Catalog = {
@@ -29,6 +29,12 @@ const CYTOLOGY: Catalog = {
{ code: 'ASC-H', label: 'ASC-H', color: CYTOLOGY_COLORS['ASC-H'], 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: 'HSIL', label: 'LIEAG', color: CYTOLOGY_COLORS['HSIL'], group: 'abnormal' },
{ code: 'CIS', label: 'Carcinoma in situ', color: CYTOLOGY_COLORS['CIS'], group: 'abnormal' }, { code: 'CIS', label: 'Carcinoma in situ', color: CYTOLOGY_COLORS['CIS'], group: 'abnormal' },
{
code: 'carcinoma',
label: 'Carcinoma epidermoide invasor',
color: BIOPSY_COLORS['carcinoma'],
group: 'abnormal',
},
], ],
}; };
@@ -61,13 +67,6 @@ const HPV = [
{ code: 'positive_16_18', label: 'VPH 16 y 18', color: HPV_COLORS['positive_16_18'] }, { code: 'positive_16_18', label: 'VPH 16 y 18', color: HPV_COLORS['positive_16_18'] },
{ code: 'positive_other', label: 'Positivo sin genotipo', color: HPV_COLORS['positive_other'] }, { code: 'positive_other', label: 'Positivo sin genotipo', color: HPV_COLORS['positive_other'] },
]; ];
const REQUESTS = [
{ 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. */ /** The screening route's bars: a median, and the marks of its quartiles. */
const TINT = { bar: DURATION, mark: QUARTILE }; const TINT = { bar: DURATION, mark: QUARTILE };
@@ -81,10 +80,8 @@ const ROUND_CAPTION =
/** The views the cytology and HPV-by-genotype cards share (one selector for both). */ /** The views the cytology and HPV-by-genotype cards share (one selector for both). */
const GENERAL = 'General'; const GENERAL = 'General';
const BY_AGE = 'Por grupo de edad'; const BY_AGE = 'Por grupo de edad';
const BY_STATUS = 'Por estatus de seguimiento';
const BY_ROUND = 'Por detección inicial y subsecuente'; const BY_ROUND = 'Por detección inicial y subsecuente';
const AGE_GROUPS = ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data']; const AGE_GROUPS = ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data'];
const STATUSES = ['pre_colposcopy', 'post_colposcopy', 'post_treatment', 'case', 'no_data'];
/** HPV categories the cards do not draw (their reports stay in the total and the percentages). */ /** HPV categories the cards do not draw (their reports stay in the total and the percentages). */
const HPV_HIDDEN = { const HPV_HIDDEN = {
codes: ['positive_incomplete', 'inconsistent', 'no_result'], codes: ['positive_incomplete', 'inconsistent', 'no_result'],
@@ -96,18 +93,17 @@ const groupViews = (
measure: string, measure: string,
catalog: { code: string; label: string; color: string }[], catalog: { code: string; label: string; color: string }[],
unit: string, unit: string,
more: { ofAll?: boolean; hidden?: { codes: string[]; unit: string } } = {}, more: { ofAll?: boolean; hidden?: { codes: string[]; unit: string }; aggregate?: typeof ABNORMAL } = {},
): Mode[] => ): Mode[] =>
[ [
{ label: BY_AGE, stratum: 'age_group', order: AGE_GROUPS }, { label: BY_AGE, stratum: 'age_group', order: AGE_GROUPS },
{ label: BY_STATUS, stratum: 'follow_up_status', order: STATUSES },
{ label: BY_ROUND, stratum: 'round', order: ROUNDS, complete: true }, { label: BY_ROUND, stratum: 'round', order: ROUNDS, complete: true },
].map((v) => ({ ].map((v) => ({
kind: 'grouped' as const, kind: 'grouped' as const,
measure, measure,
catalog, catalog,
unit, unit,
caption: more.ofAll caption: measure === 'CACU_VPH_GENOTIPO'
? 'Porcentaje de reportes de VPH del grupo por genotipo.' ? 'Porcentaje de reportes de VPH del grupo por genotipo.'
: 'Porcentaje de pacientes del grupo por resultado citológico.', : 'Porcentaje de pacientes del grupo por resultado citológico.',
...v, ...v,
@@ -245,7 +241,7 @@ export const CACU: Page = {
{ {
kind: 'days', kind: 'days',
tint: TINT, tint: TINT,
label: 'Primer diagnóstico', label: 'Diagnóstico precolposcópico',
steps: [{ label: 'Toma a primer diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' }], steps: [{ label: 'Toma a primer diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' }],
}, },
{ {
@@ -267,7 +263,7 @@ export const CACU: Page = {
kind: 'columns', kind: 'columns',
title: 'Resultados de citología, VPH y biopsia', title: 'Resultados de citología, VPH y biopsia',
viewsLabel: 'Lectura de la distribución citológica y del VPH por genotipo', viewsLabel: 'Lectura de la distribución citológica y del VPH por genotipo',
views: [GENERAL, BY_AGE, BY_STATUS, BY_ROUND], views: [GENERAL, BY_AGE, BY_ROUND],
sections: [ sections: [
{ {
kind: 'readings', kind: 'readings',
@@ -280,10 +276,11 @@ export const CACU: Page = {
label: GENERAL, label: GENERAL,
measure: 'CACU_EU7', measure: 'CACU_EU7',
catalog: CYTOLOGY.categories, catalog: CYTOLOGY.categories,
aggregate: ABNORMAL,
unit: 'Pacientes', unit: 'Pacientes',
percentLabel: 'Porcentaje de pacientes', percentLabel: 'Porcentaje de pacientes',
}, },
...groupViews('CACU_EU7', CYTOLOGY.categories, 'pacientes'), ...groupViews('CACU_EU7', CYTOLOGY.categories, 'pacientes', { aggregate: ABNORMAL, ofAll: true }),
], ],
}, },
{ {
@@ -344,15 +341,6 @@ export const CACU: Page = {
'Tasa de confirmación histopatológica de referencia a biopsia', 'Tasa de confirmación histopatológica de referencia a biopsia',
'Pacientes con biopsia reportada, por fecha de solicitud.', 'Pacientes con biopsia reportada, por fecha de solicitud.',
'Porcentaje de biopsias reportadas', 'Porcentaje de biopsias reportadas',
{
kind: 'counts',
label: 'Solicitudes',
caption: 'Solicitudes de biopsia registradas, según su resultado.',
measure: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION',
catalog: REQUESTS,
unit: 'Solicitudes',
percentLabel: 'Porcentaje de solicitudes',
},
), ),
}, },
], ],
+12 -11
View File
@@ -250,6 +250,16 @@ export const PAGES: Record<string, Page> = {
cama: { cama: {
anchor: 'CAMA_BIRADS456_PACIENTE', anchor: 'CAMA_BIRADS456_PACIENTE',
kpis: [ kpis: [
{
measure: 'CAMA_EU38A',
title: 'Días de toma de mastografía a interpretación radiológica',
...CAMA_DAYS,
},
{
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Días de interpretación radiológica a diagnóstico',
...CAMA_DAYS,
},
{ {
measure: 'CAMA_BIRADS456_PACIENTE', measure: 'CAMA_BIRADS456_PACIENTE',
title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6', title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
@@ -262,16 +272,6 @@ export const PAGES: Record<string, Page> = {
value: '{pct} %', value: '{pct} %',
note: '{num} de {den} biopsias con grado conocido presentan carcinoma (in situ o invasor).', note: '{num} de {den} biopsias con grado conocido presentan carcinoma (in situ o invasor).',
}, },
{
measure: 'CAMA_EU38A',
title: 'Días de toma de mastografía a interpretación radiológica',
...CAMA_DAYS,
},
{
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Días de interpretación radiológica a diagnóstico',
...CAMA_DAYS,
},
], ],
opportunity: [ opportunity: [
{ {
@@ -338,9 +338,9 @@ export const PAGES: Record<string, Page> = {
kind: 'counts', kind: 'counts',
label: 'Todas las categorías', label: 'Todas las categorías',
heading: 'Resultados por paciente', 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: [...BIOPSY_GRADES, ...NO_RESULT],
unit: 'Pacientes',
percent: true, percent: true,
percentLabel: 'Porcentaje de pacientes', percentLabel: 'Porcentaje de pacientes',
}, },
@@ -366,6 +366,7 @@ export const PAGES: Record<string, Page> = {
heading: 'Biopsias reportadas', heading: 'Biopsias reportadas',
measure: 'CAMA_BIOPSIAS', measure: 'CAMA_BIOPSIAS',
catalog: [...BIOPSY_GRADES, NO_RESULT[1]], catalog: [...BIOPSY_GRADES, NO_RESULT[1]],
unit: 'Biopsias',
percent: true, percent: true,
percentLabel: 'Porcentaje de reportes de biopsia', percentLabel: 'Porcentaje de reportes de biopsia',
}, },
+21 -1
View File
@@ -2,7 +2,7 @@ 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, grouped, hiddenNote, Mode, unavailable } from './bars'; import { bars, grouped, hiddenNote, Mode, subsequentHistory, 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. */
@@ -77,6 +77,21 @@ import { Reading } from './measures';
@if (g.note) { @if (g.note) {
<p class="state">{{ g.note }}</p> <p class="state">{{ g.note }}</p>
} }
@if (historyBreakdown(); as history) {
<section aria-label="Antecedente declarado en detección subsecuente">
<h4>Dentro de detección subsecuente: antecedente declarado</h4>
<p class="state">
Las categorías son respuestas del formulario; el denominador es el total de la ronda
subsecuente. La diferencia incluye valores no registrados o primera vez declarada con
procedimientos previos.
</p>
<ul>
@for (item of history; track item.label) {
<li>{{ item.label }}: {{ item.text }}</li>
}
</ul>
</section>
}
} @else if (figure(); as f) { } @else if (figure(); as f) {
<app-plot [figure]="f" [height]="height()" /> <app-plot [figure]="f" [height]="height()" />
@if (hidden(); as why) { @if (hidden(); as why) {
@@ -373,6 +388,11 @@ export class Readings {
() => this.modes().find((m) => m.label === (this.view() || this.chosen())) ?? this.modes()[0], () => this.modes().find((m) => m.label === (this.view() || this.chosen())) ?? this.modes()[0],
); );
protected readonly groups = computed(() => grouped(this.mode(), this.read())); protected readonly groups = computed(() => grouped(this.mode(), this.read()));
protected readonly historyBreakdown = computed(() => {
const mode = this.mode();
if (mode.kind !== 'grouped' || mode.stratum !== 'round') return undefined;
return subsequentHistory(this.read()(mode.measure));
});
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. */ /** The bars of a scenarios figure need more room than a donut. */
protected readonly height = computed(() => { protected readonly height = computed(() => {
+69 -18
View File
@@ -40,6 +40,50 @@
} }
@if (page(); as pg) { @if (page(); as pg) {
@if (applied(); as period) { @if (applied(); as period) {
@if (domain() === 'cama') {
<section class="card opportunity" aria-labelledby="opportunity-title">
<div class="section-head">
<h2 id="opportunity-title">Indicadores de oportunidad</h2>
<span class="period">Periodo {{ period }}</span>
</div>
<div class="kpis" style="--kpi-cols-md: 2; --kpi-cols-lg: 2">
@for (k of pg.kpis.slice(0, 2); track k.title) {
<ng-container *ngTemplateOutlet="kpiView; context: { $implicit: k }" />
}
</div>
@for (section of pg.opportunity ?? []; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section>
<section class="card clinical-page" aria-labelledby="clinical-title">
<h2 id="clinical-title">Indicadores clínicos</h2>
@for (section of pg.clinical; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
@if ($index === 0) {
<div class="kpis">
<ng-container *ngTemplateOutlet="kpiView; context: { $implicit: pg.kpis[2] }" />
</div>
}
}
<div class="kpis">
<ng-container *ngTemplateOutlet="kpiView; context: { $implicit: pg.kpis[3] }" />
</div>
</section>
} @else {
@if (domain() === 'cacu') {
<section class="card clinical-page" aria-labelledby="clinical-title">
<h2 id="clinical-title">Indicadores clínicos</h2>
@for (section of pg.clinical; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section>
}
<section class="card opportunity" aria-labelledby="opportunity-title"> <section class="card opportunity" aria-labelledby="opportunity-title">
<div class="section-head"> <div class="section-head">
<h2 id="opportunity-title">Indicadores de oportunidad</h2> <h2 id="opportunity-title">Indicadores de oportunidad</h2>
@@ -51,6 +95,30 @@
[style.--kpi-cols-lg]="pg.kpis.length < 5 ? pg.kpis.length : 5" [style.--kpi-cols-lg]="pg.kpis.length < 5 ? pg.kpis.length : 5"
> >
@for (k of pg.kpis; track k.title) { @for (k of pg.kpis; track k.title) {
<ng-container *ngTemplateOutlet="kpiView; context: { $implicit: k }" />
}
</div>
@for (section of pg.opportunity ?? []; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section>
@if (domain() !== 'cacu') {
<section class="card clinical-page" aria-labelledby="clinical-title">
<h2 id="clinical-title">Indicadores clínicos</h2>
@for (section of pg.clinical; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section>
}
}
}
<ng-template #kpiView let-k>
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null"> <mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null">
<mat-card-content> <mat-card-content>
<h3 class="kpi-title">{{ k.title }}</h3> <h3 class="kpi-title">{{ k.title }}</h3>
@@ -68,24 +136,7 @@
} }
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
} </ng-template>
</div>
@for (section of pg.opportunity ?? []; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section>
<section class="card clinical-page" aria-labelledby="clinical-title">
<h2 id="clinical-title">Indicadores clínicos</h2>
@for (section of pg.clinical; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section>
}
<ng-template #sectionView let-section let-period="period"> <ng-template #sectionView let-section let-period="period">
@switch (section.kind) { @switch (section.kind) {
+14 -2
View File
@@ -31,6 +31,10 @@ interface Drawn {
<mat-button-toggle value="month">Mensual</mat-button-toggle> <mat-button-toggle value="month">Mensual</mat-button-toggle>
<mat-button-toggle value="semester">Semestral</mat-button-toggle> <mat-button-toggle value="semester">Semestral</mat-button-toggle>
</mat-button-toggle-group> </mat-button-toggle-group>
@if (domain() === 'cama' || domain() === 'cacu') {
<label>Fecha de corte <input type="date" [value]="chosenCutoff()" (input)="chosenCutoff.set($any($event.target).value)" /></label>
<button type="button" (click)="cutoff.set(chosenCutoff())">Aplicar</button>
}
</section> </section>
@if (series.isLoading()) { @if (series.isLoading()) {
<app-loading what="el histórico" text="Cargando histórico…" /> <app-loading what="el histórico" text="Cargando histórico…" />
@@ -95,13 +99,16 @@ export class TabTrazabilidad {
readonly domain = input.required<string>(); readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>(); readonly measures = input.required<Measure[]>();
protected readonly type = signal<PeriodType>('month'); protected readonly type = signal<PeriodType>('month');
protected readonly chosenCutoff = signal('');
protected readonly cutoff = signal('');
protected readonly series = resource({ protected readonly series = resource({
params: () => ({ domain: this.domain(), type: this.type(), measures: this.measures() }), params: () => ({ domain: this.domain(), type: this.type(), measures: this.measures(), cutoff: this.cutoff() }),
loader: async ({ params }) => { loader: async ({ params }) => {
const history = HISTORY[params.domain]; const history = HISTORY[params.domain];
if (!history) return []; if (!history) return [];
const asked = periods(params.type).reverse(); const day = params.cutoff ? new Date(`${params.cutoff}T12:00:00`) : new Date();
const asked = periods(params.type, 6, day).reverse();
return Promise.all( return Promise.all(
history.panels.map(async (panel) => { history.panels.map(async (panel) => {
const measure = params.measures.find((m) => m.name === panel.measure); const measure = params.measures.find((m) => m.name === panel.measure);
@@ -109,6 +116,11 @@ export class TabTrazabilidad {
const pages = await this.fhir.all(params.domain, 'MeasureReport', { const pages = await this.fhir.all(params.domain, 'MeasureReport', {
measure: measure.id!, measure: measure.id!,
'reporting-period': asked.join(','), 'reporting-period': asked.join(','),
...(params.cutoff ? {
'as-of': `${params.cutoff}T23:59:59.999999Z`,
'event-cutoff': params.cutoff,
'period-cutoff': params.cutoff,
} : {}),
}); });
// One report per period asked, in the order asked. // One report per period asked, in the order asked.
const found = resources<MeasureReport>(pages, 'MeasureReport'); const found = resources<MeasureReport>(pages, 'MeasureReport');
+7 -2
View File
@@ -151,7 +151,7 @@
<td> <td>
{{ h.text }} {{ h.text }}
@if (h.code && h.code !== h.text) { @if (h.code && h.code !== h.text) {
<span class="muted">({{ h.code }})</span> <span class="muted">(CIE-10: {{ h.code }})</span>
} }
</td> </td>
</tr> </tr>
@@ -258,9 +258,14 @@
</mat-card> </mat-card>
} }
@if (riskExclusion() || groups().length || domain() !== 'cacu' || riskModels().length) { @if (
riskExclusion() || withheld() || groups().length || domain() !== 'cacu' || riskModels().length
) {
<mat-card appearance="outlined" class="wide" data-section="riesgos"> <mat-card appearance="outlined" class="wide" data-section="riesgos">
<mat-card-content> <mat-card-content>
@if (withheld(); as why) {
<p role="status" data-state="withheld">{{ why }}</p>
}
@if (riskExclusion(); as reason) { @if (riskExclusion(); as reason) {
<p role="status">{{ reason }}</p> <p role="status">{{ reason }}</p>
} @else { } @else {
+6 -1
View File
@@ -197,6 +197,11 @@ export class Paciente {
? `No disponible por: histerectomía registrada el ${recorded}.` ? `No disponible por: histerectomía registrada el ${recorded}.`
: undefined; : undefined;
}); });
/** CaCu: why the backend withholds some of her estimates at the cut-off, if it does. */
protected readonly withheld = computed(() => {
const patient = this.patient();
return patient ? ext(patient, 'risk-withheld')?.valueString : undefined;
});
/** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */ /** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */
protected readonly stages = computed(() => { protected readonly stages = computed(() => {
const cytologies = (this.data.value()?.reports ?? []).filter( const cytologies = (this.data.value()?.reports ?? []).filter(
@@ -312,7 +317,7 @@ export class Paciente {
['Estatus de seguimiento', this.status()], ['Estatus de seguimiento', this.status()],
['Fecha de corte', this.cutoff()], ['Fecha de corte', this.cutoff()],
]; ];
if (this.riskExclusion()) facts.push(['Evaluación de riesgo', this.riskExclusion()]); if (this.riskExclusion()) facts.push(['Evaluación de probabilidad', this.riskExclusion()]);
const sheets = recordSheets( const sheets = recordSheets(
facts, facts,
this.stages() ?? [], this.stages() ?? [],
+1 -1
View File
@@ -51,7 +51,7 @@ describe('the PDF of a record', () => {
'Historial médico', 'Historial médico',
'Antecedentes y evaluación ginecológica', 'Antecedentes y evaluación ginecológica',
'Pruebas y resultados', 'Pruebas y resultados',
'Riesgos', 'Probabilidades',
]); ]);
}); });
it('writes each stage with its state, its day or its request, and where it comes from', () => { it('writes each stage with its state, its day or its request, and where it comes from', () => {
+2 -2
View File
@@ -75,8 +75,8 @@ export function recordSheets(
]), ]),
}, },
{ {
title: 'Riesgos', title: 'Probabilidades',
head: ['Riesgo', 'Probabilidad', 'IC 95 %'], head: ['Estimación', 'Probabilidad', 'IC 95 %'],
rows: scales.map(({ label, risk }) => [ rows: scales.map(({ label, risk }) => [
label, label,
risk ? percent(risk.p) : NONE, risk ? percent(risk.p) : NONE,
+6 -6
View File
@@ -5,7 +5,7 @@ import type { Parameters, ParametersParameter } from 'fhir/r4';
/** The states a resolution ends in, as the screens say them. */ /** The states a resolution ends in, as the screens say them. */
export const STATUS_TEXT: Record<string, string> = { export const STATUS_TEXT: Record<string, string> = {
resolved: 'Referencia disponible', resolved: 'Referencia disponible',
not_published: 'Riesgo no publicado en las tablas', not_published: 'Probabilidad no publicada en las tablas',
missing_data: 'Falta un dato clínico', missing_data: 'Falta un dato clínico',
history_not_demonstrable: 'Antecedente no demostrable', history_not_demonstrable: 'Antecedente no demostrable',
not_applicable: 'Escenario no aplicable', not_applicable: 'Escenario no aplicable',
@@ -44,7 +44,7 @@ export const REASON_TEXT: Record<string, string> = {
hsil_cin2_cin3: 'La histología «LIEAG» no distingue CIN2 de CIN3, que las tablas separan.', hsil_cin2_cin3: 'La histología «LIEAG» no distingue CIN2 de CIN3, que las tablas separan.',
cis_ais: 'El carcinoma in situ no distingue el adenocarcinoma in situ, que las tablas separan.', cis_ais: 'El carcinoma in situ no distingue el adenocarcinoma in situ, que las tablas separan.',
biopsy_without_histology: 'La biopsia no tiene histología.', biopsy_without_histology: 'La biopsia no tiene histología.',
risk_blank_in_the_tables: 'Las tablas dejan este riesgo en blanco.', risk_blank_in_the_tables: 'Las tablas dejan esta probabilidad en blanco.',
no_row_for_the_combination: 'Las tablas no publican esa combinación.', no_row_for_the_combination: 'Las tablas no publican esa combinación.',
several_rows: 'Más de una fila podría corresponder.', several_rows: 'Más de una fila podría corresponder.',
no_institutional_model: 'Ningún modelo institucional ha evaluado a la paciente.', no_institutional_model: 'Ningún modelo institucional ha evaluado a la paciente.',
@@ -54,7 +54,7 @@ export const REASON_TEXT: Record<string, string> = {
index_date_differs: 'La fecha índice del modelo no es la de la citología evaluada.', index_date_differs: 'La fecha índice del modelo no es la de la citología evaluada.',
population_not_verified: population_not_verified:
'No se verificó que la población y el escenario del modelo coincidan con los de la tabla.', 'No se verificó que la población y el escenario del modelo coincidan con los de la tabla.',
no_reference: 'Las tablas no dan un riesgo a este horizonte.', no_reference: 'Las tablas no dan una probabilidad a este horizonte.',
}; };
const KEY_TEXT: Record<string, string> = { const KEY_TEXT: Record<string, string> = {
@@ -304,9 +304,9 @@ const OFFICIAL: Record<string, string> = {
<section <section
class="reference" class="reference"
data-section="referencia-nci" data-section="referencia-nci"
aria-label="Comparación de riesgos de referencia" aria-label="Comparación de probabilidades de referencia"
> >
<h3>Comparación de riesgos de referencia</h3> <h3>Comparación de probabilidades de referencia</h3>
<dl class="meta"> <dl class="meta">
<div> <div>
<dt>Estado</dt> <dt>Estado</dt>
@@ -458,7 +458,7 @@ const OFFICIAL: Record<string, string> = {
</section> </section>
} }
<p class="muted note"> <p class="muted note">
La diferencia es el riesgo institucional menos el riesgo NCI y solo se calcula si ambos La diferencia es la probabilidad institucional menos la probabilidad NCI y solo se calcula si ambos
estiman lo mismo (desenlace, horizonte, fecha índice y población verificados). estiman lo mismo (desenlace, horizonte, fecha índice y población verificados).
</p> </p>
} }
+2 -2
View File
@@ -18,7 +18,7 @@ describe('the institutional curves', () => {
model('Riesgo cáncer v2', [{ years: 5, p: 0.015 }]), model('Riesgo cáncer v2', [{ years: 5, p: 0.015 }]),
]); ]);
const lines = found.filter((t) => !t.name?.startsWith('IC')); const lines = found.filter((t) => !t.name?.startsWith('IC'));
expect(lines.map((t) => t.name)).toEqual(['Riesgo LIEAG+', 'Riesgo cáncer']); expect(lines.map((t) => t.name)).toEqual(['Probabilidad LIEAG+', 'Probabilidad cáncer']);
expect(lines[0].x).toEqual([1, 3, 5]); expect(lines[0].x).toEqual([1, 3, 5]);
expect(lines[0].y.map((y: number) => Math.round(y))).toEqual([8, 21, 34]); expect(lines[0].y.map((y: number) => Math.round(y))).toEqual([8, 21, 34]);
expect(lines[1].x).toEqual([5]); // a single horizon is a point, not a line to nowhere expect(lines[1].x).toEqual([5]); // a single horizon is a point, not a line to nowhere
@@ -94,7 +94,7 @@ describe('the institutional curves', () => {
model('Vacío v1', []), model('Vacío v1', []),
]), ]),
).toEqual([ ).toEqual([
'Riesgo LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 %; 5 años: 34.0 % (IC 95 %: 26.0–44.0 %).', 'Probabilidad LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 %; 5 años: 34.0 % (IC 95 %: 26.0–44.0 %).',
]); ]);
}); });
}); });
+4 -1
View File
@@ -16,7 +16,10 @@ export interface CurveModel {
const percent = (n: number) => const percent = (n: number) =>
(Math.round(n * 1000) / 10).toLocaleString('es-MX', { minimumFractionDigits: 1 }); (Math.round(n * 1000) / 10).toLocaleString('es-MX', { minimumFractionDigits: 1 });
const title = (m: CurveModel) => m.text.replace(/ v\d+$/, ''); const title = (m: CurveModel) =>
m.text
.replace(/ v\d+$/, '')
.replace(/riesgo/gi, (word) => (word[0] === 'R' ? 'Probabilidad' : 'probabilidad'));
const interval = (p: CurvePrediction) => p.low !== undefined && p.high !== undefined; const interval = (p: CurvePrediction) => p.low !== undefined && p.high !== undefined;
/** The institutional models' risk by horizon: one series per model, drawn only at the horizons it /** The institutional models' risk by horizon: one series per model, drawn only at the horizons it
+5 -5
View File
@@ -37,7 +37,7 @@ describe('the risk scales', () => {
]); ]);
expect(groups.map((g) => g.title)).toEqual(['Supervivencia', 'Recurrencia', 'Otro']); expect(groups.map((g) => g.title)).toEqual(['Supervivencia', 'Recurrencia', 'Otro']);
expect(groups.map((g) => g.index)).toEqual(['2026-02-01', '2026-03-01', '2026-03-02']); expect(groups.map((g) => g.index)).toEqual(['2026-02-01', '2026-03-01', '2026-03-02']);
const labels = ['Riesgo inmediato (al índice)', 'Riesgo a 5 años']; const labels = ['Probabilidad inmediata (al índice)', 'Probabilidad a 5 años'];
for (const g of groups) expect(g.scales.map((s) => s.label)).toEqual(labels); for (const g of groups) expect(g.scales.map((s) => s.label)).toEqual(labels);
expect(groups[0].scales.map((s) => s.risk?.p)).toEqual([0, 0.5]); expect(groups[0].scales.map((s) => s.risk?.p)).toEqual([0, 0.5]);
expect(groups[1].scales.map((s) => s.risk?.p)).toEqual([undefined, 0.98]); expect(groups[1].scales.map((s) => s.risk?.p)).toEqual([undefined, 0.98]);
@@ -48,15 +48,15 @@ describe('the risk scales', () => {
expect(rest).toEqual([]); expect(rest).toEqual([]);
expect(none.title).toBeUndefined(); expect(none.title).toBeUndefined();
expect(none.scales.map((s) => [s.label, s.risk])).toEqual([ expect(none.scales.map((s) => [s.label, s.risk])).toEqual([
['Riesgo inmediato (al índice)', undefined], ['Probabilidad inmediata (al índice)', undefined],
['Riesgo a 5 años', undefined], ['Probabilidad a 5 años', undefined],
]); ]);
}); });
it('the PDF keeps its flat list, with no scale for a page with no model', () => { it('the PDF keeps its flat list, with no scale for a page with no model', () => {
expect(riskScales([])).toEqual([]); expect(riskScales([])).toEqual([]);
expect(riskScales([{ text: 'M', predictions: [at(5, 0.1)] }]).map((s) => s.label)).toEqual([ expect(riskScales([{ text: 'M', predictions: [at(5, 0.1)] }]).map((s) => s.label)).toEqual([
'M, riesgo inmediato', 'M, probabilidad inmediata',
'M, riesgo a 5 años', 'M, probabilidad a 5 años',
]); ]);
}); });
}); });
+7 -4
View File
@@ -21,7 +21,7 @@ export const isRiskModel = (model: string) => !/.(survival|recurrence)$/.test(mo
export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] { export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] {
return models.flatMap((m) => return models.flatMap((m) =>
[0, 5].map((years) => ({ [0, 5].map((years) => ({
label: `${m.text}, riesgo ${years ? 'a 5 años' : 'inmediato'}`, label: `${m.text.replace(/riesgo/gi, (word) => (word[0] === 'R' ? 'Probabilidad' : 'probabilidad'))}, probabilidad ${years ? 'a 5 años' : 'inmediata'}`,
risk: m.predictions.find((p) => p.years === years), risk: m.predictions.find((p) => p.years === years),
})), })),
); );
@@ -97,14 +97,17 @@ export function survivalGroups(
} }
const HORIZONS: [number, string][] = [ const HORIZONS: [number, string][] = [
[0, 'Riesgo inmediato (al índice)'], [0, 'Probabilidad inmediata (al índice)'],
[5, 'Riesgo a 5 años'], [5, 'Probabilidad a 5 años'],
]; ];
/** A model's published title, "Riesgo de X en <escenario> v1", as its outcome and its scenario. */ /** A model's published title, "Riesgo de X en <escenario> v1", as its outcome and its scenario. */
export function titleParts(text: string): { title: string; scenario?: string } { export function titleParts(text: string): { title: string; scenario?: string } {
const [, title, scenario] = /^(.*?)(?: en (.+?))?(?: v\d+)?$/.exec(text)!; const [, title, scenario] = /^(.*?)(?: en (.+?))?(?: v\d+)?$/.exec(text)!;
return { title, scenario }; return {
title: title.replace(/riesgo/gi, (word) => (word[0] === 'R' ? 'Probabilidad' : 'probabilidad')),
scenario,
};
} }
/** The scales the page draws: both horizons of every model, or, with no model, both horizons /** The scales the page draws: both horizons of every model, or, with no model, both horizons