Compare commits

...

14 Commits

20 changed files with 573 additions and 245 deletions
+7 -7
View File
@@ -14,8 +14,8 @@ 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',
biopsy: 'Resultados de biopsia cervical', biopsy: 'Resultados de biopsia cervical',
colposcopy: 'Valor predictivo positivo de la colposcopía', colposcopy: 'Tasa de confirmación histopatológica de referencia a colposcopía',
ppvBiopsy: 'Valor predictivo positivo de la biopsia', ppvBiopsy: 'Tasa de confirmación histopatológica de referencia a biopsia',
}; };
test('indicadores cacu: its sections in order, each card read one mode at a time', async ({ test('indicadores cacu: its sections in order, each card read one mode at a time', async ({
@@ -30,17 +30,17 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
.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 de oportunidad'))).toEqual([
'Indicadores de oportunidad', 'Indicadores de oportunidad',
'Tiempos de la ruta del tamizaje', 'Días de la ruta del 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',
'Resultados de VPH por genotipo', 'Resultados de VPH por genotipo',
'Resultados de biopsia cervical', 'Resultados de biopsia cervical',
'Tasa de confirmación histopatológica', 'Tasa de confirmación histopatológica',
'Valor predictivo positivo de la colposcopía', 'Tasa de confirmación histopatológica de referencia a colposcopía',
]); ]);
const route = tab.locator('app-readings').first(); const route = tab.locator('app-readings').first();
for (const mode of ['Por pasos', 'Por CIE-10', 'Acumulado desde la toma']) { for (const mode of ['Por pasos', 'Primer diagnóstico', '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.')),
@@ -105,14 +105,14 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
.getByRole('radio', ROUND) .getByRole('radio', ROUND)
.click(); .click();
await expect( await expect(
tab.getByRole('heading', { name: 'Valor predictivo positivo de la 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 tab.getByRole('radio', { name: 'Solicitudes' }).click();
}); });
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 }) => {
await page.goto('/indicadores/cacu'); await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Seguimiento' }).click();
const list = page.locator('table.worklist tbody tr'); const list = page.locator('table.worklist tbody tr');
await expect(list.first().locator('app-stages li')).toHaveCount(5); await expect(list.first().locator('app-stages li')).toHaveCount(5);
await list.first().getByRole('button', { name: 'Detalle' }).click(); await list.first().getByRole('button', { name: 'Detalle' }).click();
+2 -2
View File
@@ -14,7 +14,7 @@ test.beforeEach(async ({ page }) => {
/** The record of the first patient of the risk list, as an address. */ /** The record of the first patient of the risk list, as an address. */
async function firstRecord(page: Page): Promise<{ url: string; sample: string }> { async function firstRecord(page: Page): Promise<{ url: string; sample: string }> {
await page.goto('/indicadores/cacu'); await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Seguimiento' }).click();
const link = page.locator('table.worklist tbody tr a').first(); const link = page.locator('table.worklist tbody tr a').first();
await link.waitFor({ timeout: 120_000 }); await link.waitFor({ timeout: 120_000 });
const url = (await link.getAttribute('href'))!; const url = (await link.getAttribute('href'))!;
@@ -1587,7 +1587,7 @@ test('elegibilidad (simulado): a new patient never inherits the previous risk ex
await open(page, firstUrl); await open(page, firstUrl);
await expect(reason).toBeVisible(); await expect(reason).toBeVisible();
await page.getByRole('link', { name: 'Regresar' }).click(); await page.getByRole('link', { name: 'Regresar' }).click();
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Seguimiento' }).click();
await page.locator(`a[href*="/pacientes/${secondId}?"]`).first().click(); await page.locator(`a[href*="/pacientes/${secondId}?"]`).first().click();
await expect(historial(page)).toBeVisible({ timeout: 120_000 }); await expect(historial(page)).toBeVisible({ timeout: 120_000 });
await expect(riskBox(page).locator('app-risk-scales')).toBeVisible(); await expect(riskBox(page).locator('app-risk-scales')).toBeVisible();
+16 -6
View File
@@ -58,14 +58,14 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
); );
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible(); await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Trazabilidad' }).click(); await page.getByRole('tab', { name: 'Histórico' }).click();
await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9); await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click(); await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21); await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?')); const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Seguimiento' }).click();
const bundle = await (await list).json(); const bundle = await (await list).json();
const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource; const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource;
const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10); const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10);
@@ -84,8 +84,8 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
).not.toContainText('Sin estudios'); ).not.toContainText('Sin estudios');
await page.goto('/indicadores/cama'); await page.goto('/indicadores/cama');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible(); await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Seguimiento' }).click();
await page.locator('mat-form-field', { hasText: 'Ventana' }).click(); await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
await page.getByRole('option', { name: '12 meses' }).click(); await page.getByRole('option', { name: '12 meses' }).click();
const camaRows = page.locator('table.worklist tbody tr'); const camaRows = page.locator('table.worklist tbody tr');
@@ -205,6 +205,16 @@ function captured(domain: string) {
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>'); const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+'); const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
for (const domain of ['cacu', 'cama', 'tea']) {
test(`pestañas de indicadores ${domain} tienen nombres únicos`, async ({ page }) => {
await page.goto(`/indicadores/${domain}`);
await expect(page.getByRole('tab', { name: 'Seguimiento', exact: true })).toHaveCount(1);
await expect(page.getByRole('tab', { name: 'Histórico', exact: true })).toHaveCount(1);
const labels = await page.getByRole('tab').allTextContents();
expect(new Set(labels.map((s) => s.trim())).size).toBe(labels.length);
});
}
// CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one. // CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one.
for (const domain of ['cama', 'tea']) { for (const domain of ['cama', 'tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({ test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
@@ -242,7 +252,7 @@ for (const domain of ['cama', 'tea']) {
.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');
expect(headings.slice(from).map(period)).toEqual( expect(headings.slice(from).map(period)).toEqual(
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)), old.filter((i) => i.kind !== 'plot').map((i) => period(domain === 'cama' ? i.text.replace(/^Tiempo de /, 'Días de ') : 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
@@ -268,7 +278,7 @@ for (const domain of ['cacu', 'cama', 'tea']) {
['h2', 'h3', 'plot'].includes(i.kind), ['h2', 'h3', 'plot'].includes(i.kind),
); );
await page.goto(`/indicadores/${domain}`); await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Trazabilidad' }).click(); await page.getByRole('tab', { name: 'Histórico' }).click();
const tab = page.locator('app-tab-trazabilidad'); const tab = page.locator('app-tab-trazabilidad');
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible(); await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 }); await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
+21
View File
@@ -54,6 +54,8 @@ export type Mode = {
hidden?: Hidden; hidden?: Hidden;
} }
| { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint } | { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint }
/** A proportion as one bar of 0 to 100 %, its 95 % interval as the two marks on it */
| { kind: 'ratio'; measure: string; colors?: Colors }
| { kind: 'days-by'; measure: string; stratum: string; tint?: Tint } | { kind: 'days-by'; measure: string; stratum: string; tint?: Tint }
/** A proportion as its two parts (what counted and what did not), in units, with the shares */ /** A proportion as its two parts (what counted and what did not), in units, with the shares */
| { kind: 'split'; measure: string; yes: string; no: string; colors?: [string, string] } | { kind: 'split'; measure: string; yes: string; no: string; colors?: [string, string] }
@@ -204,6 +206,25 @@ const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
/** The bars of a mode; none when the period has nothing to draw. */ /** The bars of a mode; none when the period has nothing to draw. */
export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined { export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
switch (mode.kind) { switch (mode.kind) {
case 'ratio': {
const r = of(mode.measure);
const n = r?.populations['numerator'] ?? 0;
const total = r?.populations['denominator'] ?? 0;
if (r?.score === undefined || !total) return undefined;
const ends = r.low !== undefined && r.high !== undefined ? [r.low, r.high] : [];
return {
head: ['n/N', '%', 'IC 95 %'],
rows: [
{
label: 'Total',
color: mode.colors?.['numerator'],
width: 100 * r.score,
marks: ends.map((v) => 100 * v),
cells: [`${n}/${total}`, pct(n, total), ends.map((v) => pct(v, 1)).join('–') || '—'],
},
],
};
}
case 'counts': { case 'counts': {
const cells = of(mode.measure)?.strata['category'] ?? {}; const cells = of(mode.measure)?.strata['category'] ?? {};
const total = Object.values(cells).reduce((n, c) => n + size(c), 0); const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
+5 -5
View File
@@ -36,28 +36,28 @@ import { Loading } from '../loading';
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p> <p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
} @else { } @else {
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms"> <mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
<mat-tab [label]="domain() === 'tea' ? 'Resumen' : 'Indicadores'"> <mat-tab label="Resumen">
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" /> <app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
</mat-tab> </mat-tab>
<mat-tab label="Trazabilidad"> <mat-tab label="Histórico">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-trazabilidad [domain]="domain()" [measures]="measures.value()!" /> <app-tab-trazabilidad [domain]="domain()" [measures]="measures.value()!" />
</ng-template> </ng-template>
</mat-tab> </mat-tab>
@if (domain() === 'cacu') { @if (domain() === 'cacu') {
<mat-tab label="Análisis de riesgos"> <mat-tab label="Seguimiento">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-riesgos [domain]="domain()" /> <app-tab-riesgos [domain]="domain()" />
</ng-template> </ng-template>
</mat-tab> </mat-tab>
} @else if (domain() === 'tea') { } @else if (domain() === 'tea') {
<mat-tab label="Análisis de Riesgo"> <mat-tab label="Seguimiento">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-riesgos-tea [domain]="domain()" /> <app-tab-riesgos-tea [domain]="domain()" />
</ng-template> </ng-template>
</mat-tab> </mat-tab>
} @else if (domain() === 'cama') { } @else if (domain() === 'cama') {
<mat-tab label="Análisis de riesgos"> <mat-tab label="Seguimiento">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-seguimiento [domain]="domain()" /> <app-tab-seguimiento [domain]="domain()" />
</ng-template> </ng-template>
+2 -2
View File
@@ -19,8 +19,8 @@ export const LAYOUTS: Record<string, Layout> = {
], ],
route: [ route: [
{ {
label: 'Resultado de citología', label: 'Días de toma de citología a resultado',
step: 'Toma a resultado de citología', step: 'Días de toma de citología a resultado',
fromSample: 'CACU_EU_TIEMPO_REPORTE', fromSample: 'CACU_EU_TIEMPO_REPORTE',
fromStep: 'CACU_EU_TIEMPO_REPORTE', fromStep: 'CACU_EU_TIEMPO_REPORTE',
}, },
+28 -18
View File
@@ -116,9 +116,10 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
kind: 'readings', kind: 'readings',
title, title,
headline: measure, headline: measure,
footnote: true,
note: `${note} Confirma la histología LIEBG o mayor.`, note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [ modes: [
{ kind: 'figure', label: 'Total', measure, figure: 'donut', colors: PPV_DONUT }, { kind: 'ratio', label: 'Total', measure, colors: PPV_DONUT },
{ {
kind: 'shares', kind: 'shares',
label: 'Citología previa', label: 'Citología previa',
@@ -174,34 +175,29 @@ export const CACU: Page = {
}, },
{ {
measure: 'CACU_EU_TIEMPO_REPORTE', measure: 'CACU_EU_TIEMPO_REPORTE',
title: 'Tiempo desde la toma de muestra al resultado', title: 'Días de toma de citología a resultado',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a primer diagnóstico',
...CACU_DAYS, ...CACU_DAYS,
}, },
{ {
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
title: 'Tiempo de tamizaje a diagnóstico tras biopsia', title: 'Días de tamizaje a diagnóstico tras biopsia',
...CACU_DAYS, ...CACU_DAYS,
}, },
{ {
measure: 'CACU_DIAS_TOMA_TRATAMIENTO', measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Tiempo de tamizaje a tratamiento', title: 'Días de tamizaje a tratamiento',
...CACU_DAYS, ...CACU_DAYS,
}, },
{ {
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento', title: 'Días de diagnóstico a tratamiento',
...CACU_DAYS, ...CACU_DAYS,
}, },
], ],
opportunity: [ opportunity: [
{ {
kind: 'readings', kind: 'readings',
title: 'Tiempos de la ruta del tamizaje', title: 'Días de la ruta del tamizaje',
note: 'Mediana en días; las marcas son el primer y el tercer cuartil.', note: 'Mediana en días; las marcas son el primer y el tercer cuartil.',
modes: [ modes: [
{ {
@@ -209,10 +205,13 @@ export const CACU: Page = {
tint: TINT, tint: TINT,
label: 'Acumulado desde la toma', label: 'Acumulado desde la toma',
steps: [ steps: [
{ label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' }, { label: 'Días de toma de citología a resultado', measure: 'CACU_EU_TIEMPO_REPORTE' },
{ label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' }, { label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' }, { label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
{ label: 'Diagnóstico tras biopsia', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA' }, {
label: 'Diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
},
], ],
}, },
{ {
@@ -221,7 +220,10 @@ export const CACU: Page = {
label: 'Por pasos', label: 'Por pasos',
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.', caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
steps: [ steps: [
{ label: 'Toma a resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' }, {
label: 'Días de toma de citología a resultado',
measure: 'CACU_EU_TIEMPO_REPORTE',
},
{ label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' }, { label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
{ label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' }, { label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' },
{ label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' }, { label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' },
@@ -237,7 +239,12 @@ export const CACU: Page = {
kind: 'days', kind: 'days',
tint: TINT, tint: TINT,
label: 'Diagnóstico tras biopsia', label: 'Diagnóstico tras biopsia',
steps: [{ label: 'Toma a diagnóstico tras biopsia', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA' }], steps: [
{
label: 'Toma a diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
},
],
}, },
], ],
}, },
@@ -272,7 +279,10 @@ export const CACU: Page = {
catalog: HPV, catalog: HPV,
hidden: HPV_HIDDEN, hidden: HPV_HIDDEN,
}, },
...groupViews('CACU_VPH_GENOTIPO', HPV, 'reportes', { ofAll: true, hidden: HPV_HIDDEN }), ...groupViews('CACU_VPH_GENOTIPO', HPV, 'reportes', {
ofAll: true,
hidden: HPV_HIDDEN,
}),
], ],
}, },
{ {
@@ -298,7 +308,7 @@ export const CACU: Page = {
label: 'Colposcopía', label: 'Colposcopía',
section: ppv( section: ppv(
'CACU_VPP_COLPOSCOPIA', 'CACU_VPP_COLPOSCOPIA',
'Valor predictivo positivo de la colposcopía', 'Tasa de confirmación histopatológica de referencia a colposcopía',
'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.', 'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.',
), ),
}, },
@@ -306,7 +316,7 @@ export const CACU: Page = {
label: 'Biopsia', label: 'Biopsia',
section: ppv( section: ppv(
'CACU_VPP_BIOPSIA', 'CACU_VPP_BIOPSIA',
'Valor predictivo positivo de la 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.',
{ {
kind: 'counts', kind: 'counts',
+12 -10
View File
@@ -26,6 +26,8 @@ export interface ReadingsCard {
kind: 'readings'; kind: 'readings';
title: string; title: string;
headline?: string; headline?: string;
/** say the headline under the figure instead of above it */
footnote?: boolean;
/** what the headline proportion counts, in the plural (default: pacientes) */ /** what the headline proportion counts, in the plural (default: pacientes) */
unit?: string; unit?: string;
note?: string; note?: string;
@@ -263,16 +265,16 @@ export const PAGES: Record<string, Page> = {
}, },
{ {
measure: 'CAMA_EU38A', measure: 'CAMA_EU38A',
title: 'Tiempo de toma de mastografía a interpretación radiológica', title: 'Días de toma de mastografía a interpretación radiológica',
...CAMA_DAYS, ...CAMA_DAYS,
}, },
{ {
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO', measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Tiempo de interpretación radiológica a diagnóstico', title: 'Días de interpretación radiológica a diagnóstico',
...CAMA_DAYS, ...CAMA_DAYS,
}, },
{ {
title: 'Tiempo de diagnóstico a tratamiento', title: 'Días de diagnóstico a tratamiento',
value: 'Indicador no disponible', value: 'Indicador no disponible',
note: PENDING, note: PENDING,
}, },
@@ -280,12 +282,12 @@ export const PAGES: Record<string, Page> = {
opportunity: [ opportunity: [
{ {
kind: 'route', kind: 'route',
title: 'Tiempo de tamizaje a diagnóstico', title: 'Días de tamizaje a diagnóstico',
// from the mammography: only the two measures that start at it // from the mammography: only the two measures that start at it
sample: [ sample: [
{ label: 'Interpretación radiológica', measure: 'CAMA_EU38A' }, { label: 'Interpretación radiológica', measure: 'CAMA_EU38A' },
{ {
label: 'Diagnóstico (tiempo total de tamizaje a diagnóstico)', label: 'Diagnóstico (días de tamizaje a diagnóstico)',
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
}, },
], ],
@@ -476,27 +478,27 @@ export const HISTORY: Record<string, History> = {
], ],
), ),
{ {
title: 'Días de la toma de la citología a su resultado', title: 'Días de toma de citología a resultado',
measure: 'CACU_EU_TIEMPO_REPORTE', measure: 'CACU_EU_TIEMPO_REPORTE',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Tiempo de tamizaje a primer diagnóstico', title: 'Días de tamizaje a primer diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Tiempo de tamizaje a diagnóstico tras biopsia', title: 'Días de tamizaje a diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Tiempo de tamizaje a tratamiento', title: 'Días de tamizaje a tratamiento',
measure: 'CACU_DIAS_TOMA_TRATAMIENTO', measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Tiempo de diagnóstico a tratamiento', title: 'Días de diagnóstico a tratamiento',
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
kind: 'median', kind: 'median',
}, },
+5
View File
@@ -146,6 +146,9 @@ import { Reading } from './measures';
} @else { } @else {
<p class="state">Sin datos en el periodo.</p> <p class="state">Sin datos en el periodo.</p>
} }
@if (foot()) {
<p class="state">{{ foot() }}</p>
}
`, `,
styles: ` styles: `
:host { :host {
@@ -347,6 +350,8 @@ export class Readings {
readonly title = input.required<string>(); readonly title = input.required<string>();
readonly headline = input(''); readonly headline = input('');
readonly note = input(''); readonly note = input('');
/** a line under the figure */
readonly foot = input('');
/** the card around it names it already (tabs inside one card) */ /** the card around it names it already (tabs inside one card) */
readonly hideTitle = input(false); readonly hideTitle = input(false);
readonly camaStyle = input(false); readonly camaStyle = input(false);
+10 -2
View File
@@ -28,7 +28,8 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
<app-readings <app-readings
[title]="s.title" [title]="s.title"
[camaStyle]="hasCamaHeading(s)" [camaStyle]="hasCamaHeading(s)"
[headline]="headlineOf(s)" [headline]="s.footnote ? '' : headlineOf(s)"
[foot]="footOf(s)"
[note]="s.note ?? ''" [note]="s.note ?? ''"
[modes]="s.modes" [modes]="s.modes"
[view]="view()" [view]="view()"
@@ -58,7 +59,8 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
[title]="c.section.title" [title]="c.section.title"
[hideTitle]="true" [hideTitle]="true"
[camaStyle]="true" [camaStyle]="true"
[headline]="headlineOf(c.section)" [headline]="c.section.footnote ? '' : headlineOf(c.section)"
[foot]="footOf(c.section)"
[note]="c.section.note ?? ''" [note]="c.section.note ?? ''"
[modes]="c.section.modes" [modes]="c.section.modes"
[loading]="of().loading" [loading]="of().loading"
@@ -162,6 +164,12 @@ export class ReadingsSection {
const words = detail(measure, r, s.unit); const words = detail(measure, r, s.unit);
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`; return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
} }
/** The headline of a card that says it under its figure, as one line separated by commas. */
protected footOf(s: ReadingsCard): string {
return s.footnote
? this.headlineOf(s).replace(' · ', ', ').replace('. IC 95 %', ', IC 95 %')
: '';
}
protected readonly draw = computed(() => (mode: Mode) => { protected readonly draw = computed(() => (mode: Mode) => {
if (mode.kind !== 'figure') return undefined; if (mode.kind !== 'figure') return undefined;
const r = this.of().reading(mode.measure); const r = this.of().reading(mode.measure);
+2 -2
View File
@@ -33,10 +33,10 @@ interface Drawn {
</mat-button-toggle-group> </mat-button-toggle-group>
</section> </section>
@if (series.isLoading()) { @if (series.isLoading()) {
<app-loading what="la trazabilidad" text="Cargando trazabilidad…" /> <app-loading what="el histórico" text="Cargando histórico…" />
} @else if (series.error()) { } @else if (series.error()) {
<p class="muted" role="alert"> <p class="muted" role="alert">
No se pudo cargar la trazabilidad. No se pudo cargar el histórico.
<button type="button" class="retry" (click)="series.reload()">Reintentar</button> <button type="button" class="retry" (click)="series.reload()">Reintentar</button>
</p> </p>
} @else { } @else {
+132 -82
View File
@@ -246,66 +246,68 @@
</mat-card> </mat-card>
} }
<mat-card appearance="outlined" class="wide" data-section="riesgos"> @if (riskExclusion() || groups().length || domain() !== 'cacu' || riskModels().length) {
<mat-card-content> <mat-card appearance="outlined" class="wide" data-section="riesgos">
@if (riskExclusion(); as reason) { <mat-card-content>
<p role="status">{{ reason }}</p> @if (riskExclusion(); as reason) {
} @else { <p role="status">{{ reason }}</p>
<app-risk-scales [groups]="groups()" /> } @else {
} <app-risk-scales [groups]="groups()" />
@if (riskModels().length) { }
<details data-section="modelos"> @if (riskModels().length) {
<summary>Modelos y valores</summary> <details data-section="modelos">
<table class="plain"> <summary>Modelos y valores</summary>
<thead> <table class="plain">
<tr> <thead>
<th>Modelo</th> <tr>
<th>Fecha índice</th> <th>Modelo</th>
<th>Horizonte</th> <th>Fecha índice</th>
<th>Probabilidad</th> <th>Horizonte</th>
<th>IC 95 %</th> <th>Probabilidad</th>
</tr> <th>IC 95 %</th>
</thead> </tr>
<tbody> </thead>
@for (m of riskModels(); track m.model) { <tbody>
@for (p of m.predictions; track p.years) { @for (m of riskModels(); track m.model) {
<tr> @for (p of m.predictions; track p.years) {
<td>{{ $first ? m.text : '' }}</td> <tr>
<td>{{ $first ? m.index : '' }}</td> <td>{{ $first ? m.text : '' }}</td>
<td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td> <td>{{ $first ? m.index : '' }}</td>
<td>{{ p.p * 100 | number: '1.1-2' }} %</td> <td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td>
<td> <td>{{ p.p * 100 | number: '1.1-2' }} %</td>
@if (p.low !== undefined) { <td>
{{ p.low * 100 | number: '1.1-2' }}–{{ @if (p.low !== undefined) {
p.high! * 100 | number: '1.1-2' {{ p.low * 100 | number: '1.1-2' }}–{{
}} p.high! * 100 | number: '1.1-2'
% }}
} @else { %
— } @else {
} —
</td> }
</tr> </td>
</tr>
}
} }
} </tbody>
</tbody> </table>
</table> </details>
</details> }
} @if (!riskExclusion() && (riskModels().length || riskSeries.value()?.length)) {
@if (!riskExclusion() && (riskModels().length || riskSeries.value()?.length)) { <details class="curves" open data-section="curvas">
<details class="curves" open data-section="curvas"> <summary>Curvas de probabilidad con su intervalo</summary>
<summary>Curvas de probabilidad con su intervalo</summary> @if (riskSeries.value()?.length) {
@if (riskSeries.value()?.length) { <app-risk-series [series]="riskSeries.value()!" />
<app-risk-series [series]="riskSeries.value()!" /> } @else {
} @else { <app-plot [figure]="curve()" [height]="300" [toolbar]="false" />
<app-plot [figure]="curve()" [height]="300" /> }
} </details>
</details> }
} @if (!riskModels().length && !riskExclusion()) {
@if (!riskModels().length && !riskExclusion()) { <p class="muted">Sin evaluación de un modelo en producción.</p>
<p class="muted">Sin evaluación de un modelo en producción.</p> }
} </mat-card-content>
</mat-card-content> </mat-card>
</mat-card> }
@if (domain() === 'tea') { @if (domain() === 'tea') {
<mat-card appearance="outlined" class="wide" data-section="tea"> <mat-card appearance="outlined" class="wide" data-section="tea">
<mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header> <mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header>
@@ -557,19 +559,72 @@
<mat-card appearance="outlined" class="wide" data-section="supervivencia"> <mat-card appearance="outlined" class="wide" data-section="supervivencia">
<mat-card-header> <mat-card-header>
<mat-card-title>{{ <mat-card-title>{{
domain() === 'cacu' ? 'Supervivencia por escenario clínico' : 'Riesgo de muerte' domain() === 'cacu' ? 'Supervivencia' : 'Riesgo de muerte'
}}</mat-card-title> }}</mat-card-title>
</mat-card-header> </mat-card-header>
<mat-card-content> <mat-card-content>
<h3>Análisis de supervivencia</h3> @if (domain() !== 'cacu') {
@if (domain() === 'cacu') { <h3>Análisis de supervivencia</h3>
<p class="muted" data-note="grupo">
Las curvas son estimaciones del grupo de pacientes del escenario clínico
correspondiente (S(t), probabilidad de supervivencia); no son predicciones
individuales.
</p>
} }
@if (survival.isLoading()) { @if (domain() === 'cacu') {
<app-risk-scales [groups]="survivalScales()" />
@for (g of survivalScales(); track $index) {
<details data-section="valores-supervivencia">
<summary>Modelos y valores</summary>
<table class="plain">
<thead>
<tr>
<th>Modelo</th>
<th>Fecha índice</th>
<th>Horizonte</th>
<th>Supervivencia</th>
<th>IC 95 %</th>
</tr>
</thead>
<tbody>
@for (v of g.scales; track v.label) {
<tr>
<td>{{ $first ? g.model : '' }}</td>
<td>{{ $first ? g.index : '' }}</td>
<td>{{ v.risk!.years }} {{ v.risk!.years === 1 ? 'año' : 'años' }}</td>
<td>{{ v.risk!.p * 100 | number: '1.1-2' }} %</td>
<td>
@if (v.risk!.low !== undefined && v.risk!.high !== undefined) {
{{ v.risk!.low! * 100 | number: '1.1-2' }}–{{
v.risk!.high! * 100 | number: '1.1-2'
}}
%
} @else {
—
}
</td>
</tr>
}
</tbody>
</table>
</details>
}
<h3>Curva de supervivencia</h3>
@if (combination.isLoading()) {
<app-loading what="la curva de supervivencia" [figure]="true" />
} @else if (combination.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else if (combination.value(); as c) {
@if (c.figure) {
<p class="muted">
Kaplan-Meier de pacientes con sus mismos valores (IC 95 % Greenwood log-log; n =
{{ c.n }}, fallecidos = {{ c.fallecidos }}).
</p>
<app-plot [figure]="c.figure" [height]="340" [toolbar]="false" />
} @else {
<p class="muted">{{ c.missing }}</p>
}
} @else {
<p class="muted">
No disponible: la estimación no conserva los valores usados para elegir la curva.
</p>
}
} @else if (survival.isLoading()) {
<app-loading what="las curvas de supervivencia" [figure]="true" /> <app-loading what="las curvas de supervivencia" [figure]="true" />
} @else if (survival.value(); as s) { } @else if (survival.value(); as s) {
<h3>Escenario clínico de la paciente</h3> <h3>Escenario clínico de la paciente</h3>
@@ -579,12 +634,14 @@
} }
</ul> </ul>
@if (s.methods.length) { @if (s.methods.length) {
<h3>Métodos</h3> <details>
<ul class="scenarios methods"> <summary>Métodos</summary>
@for (name of s.methods; track name) { <ul class="scenarios methods">
<li>{{ name }}</li> @for (name of s.methods; track name) {
} <li>{{ name }}</li>
</ul> }
</ul>
</details>
} }
@for (f of s.figures; track f.title) { @for (f of s.figures; track f.title) {
<h4>{{ f.title }}</h4> <h4>{{ f.title }}</h4>
@@ -608,14 +665,7 @@
} @else if (survival.error()) { } @else if (survival.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p> <p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else { } @else {
<p class="muted" data-state="sin-informe"> <p class="muted" data-state="sin-informe">No disponible: datos insuficientes.</p>
@if (domain() === 'cacu') {
No disponible: no hay un informe de supervivencia para los escenarios de la
paciente.
} @else {
No disponible: datos insuficientes.
}
</p>
} }
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
+61 -11
View File
@@ -32,7 +32,8 @@ import { eligibilityFailure, eligibilityView, type EligibilityState } from './el
import { ineligibility } from './ineligibility'; import { ineligibility } from './ineligibility';
import { parseSeries, RiskSeries, Series } from './risk-series'; import { parseSeries, RiskSeries, Series } from './risk-series';
import { curveFigure } from './risk-curve'; import { curveFigure } from './risk-curve';
import { isRiskModel, riskGroups, riskScales, RiskScales } from './risk-scales'; import { riskGroups, riskScales, RiskScales, survivalGroups } from './risk-scales';
import { combinationFigure, combinationOf, noCurveText } from './survival-combination';
import { route, Stages } from './stages'; import { route, Stages } from './stages';
import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up'; import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
import { LABELS, name, PRIORITY } from '../indicadores/measures'; import { LABELS, name, PRIORITY } from '../indicadores/measures';
@@ -79,6 +80,25 @@ function methods(figures: { figure: { data: unknown[] } }[]): string[] {
return [...new Set(names.filter((n): n is string => !!n))]; return [...new Set(names.filter((n): n is string => !!n))];
} }
/** The day of an instant in the hospital's time zone (America/Monterrey). */
function localDay(instant: string | undefined): string | undefined {
return instant
? new Date(instant).toLocaleDateString('en-CA', { timeZone: 'America/Monterrey' })
: undefined;
}
function modelInputs(value: string | undefined): Record<string, unknown> | undefined {
if (!value) return undefined;
try {
const parsed: unknown = JSON.parse(value);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: undefined;
} catch {
return undefined;
}
}
@Component({ @Component({
selector: 'app-paciente', selector: 'app-paciente',
imports: [ imports: [
@@ -158,18 +178,17 @@ export class Paciente {
}); });
protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv')); protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv'));
protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff())); protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff()));
/** Why she has no risk estimate; nothing when she is eligible. Only while the backend gives /** Why she has no risk estimate; nothing when she is eligible. The backend's reason first; the
* no decision (failure, gold not updated) is the hysterectomy of her record held against it. */ * hysterectomy of her record is still held against her when the backend does not report it,
* as with evidence loaded without the day it was available. */
protected readonly riskExclusion = computed(() => { protected readonly riskExclusion = computed(() => {
if (this.domain() !== 'cacu') return undefined; if (this.domain() !== 'cacu') return undefined;
const patient = this.patient(); const patient = this.patient();
const sample = this.citologia()?.slice(0, 10); const sample = this.citologia()?.slice(0, 10);
const index = sample && sample < this.cutoff() ? sample : this.cutoff(); const index = sample && sample < this.cutoff() ? sample : this.cutoff();
const state = this.eligibility(); const status = (patient && ext(patient, 'follow-up-status')?.valueCoding?.code) ?? '';
if (state.kind === 'evaluated' || state.kind === 'none') { const reported = ineligibility(this.eligibility(), status, index);
const status = (patient && ext(patient, 'follow-up-status')?.valueCoding?.code) ?? ''; if (reported) return reported;
return ineligibility(state, status, index);
}
const recorded = patient && ext(patient, 'first-hysterectomy-recorded')?.valueDate; const recorded = patient && ext(patient, 'first-hysterectomy-recorded')?.valueDate;
return recorded && recorded <= index return recorded && recorded <= index
? `No disponible por: histerectomía registrada el ${recorded}.` ? `No disponible por: histerectomía registrada el ${recorded}.`
@@ -184,14 +203,42 @@ export class Paciente {
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined; return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
}); });
/** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */ /** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */
protected readonly riskModels = computed(() => this.models().filter((m) => isRiskModel(m.model))); protected readonly riskModels = computed(() => this.models().filter((m) => m.measure === 'risk'));
protected readonly scales = computed(() => protected readonly scales = computed(() =>
this.domain() === 'cacu' ? riskScales(this.riskModels()) : [], this.domain() === 'cacu' ? riskScales(this.riskModels()) : [],
); );
/** CaCu: both horizons of every model, or both unavailable (the PDF keeps `scales`). */ /** CaCu: both horizons of every risk model, or both unavailable (the PDF keeps `scales`). With
* survival only there is nothing to draw here: its scales are in the survival section. */
protected readonly groups = computed(() => protected readonly groups = computed(() =>
this.domain() === 'cacu' ? riskGroups(this.riskModels()) : [], this.domain() === 'cacu' && (this.riskModels().length || !this.survivalScales().length)
? riskGroups(this.riskModels())
: [],
); );
protected readonly survivalScales = computed(() =>
this.domain() === 'cacu'
? survivalGroups(this.models().filter((m) => m.measure === 'mortality'))
: [],
);
/** CaCu: the one Kaplan-Meier curve of the patients who share all her values, from the report of
* the model version that scored her. */
protected readonly combination = resource({
params: () => {
const m = this.models().find((x) => x.model === 'cacu.survival' && x.version && x.inputs);
return this.domain() === 'cacu' && m ? { version: m.version, inputs: m.inputs! } : undefined;
},
loader: async ({ params: { version, inputs } }) => {
const report = await this.api.invoke(readReport$Json, {
domain: 'cacu' as Domain,
name: 'survival',
version,
report: 'interpretability',
});
const found = combinationOf(report as Record<string, unknown>, inputs);
return found?.km
? { n: found.n, fallecidos: found.fallecidos, figure: combinationFigure(found.km) }
: { missing: noCurveText(report as Record<string, unknown>, found) };
},
});
/** CaCu, experimental: the series her record can compare; none while the API has it off. */ /** CaCu, experimental: the series her record can compare; none while the API has it off. */
protected readonly riskSeries = resource({ protected readonly riskSeries = resource({
params: () => params: () =>
@@ -342,6 +389,9 @@ export class Paciente {
text: r.method?.text ?? '', text: r.method?.text ?? '',
version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0), version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0),
index: r.occurrenceDateTime ?? '', index: r.occurrenceDateTime ?? '',
measure: ext(r, 'prediction-measure')?.valueCode,
inputs: modelInputs(ext(r, 'model-inputs')?.valueString),
evaluated: localDay(r.meta?.lastUpdated),
// the clinical scenarios of the model's report she falls in // the clinical scenarios of the model's report she falls in
scenarios: (r.extension ?? []) scenarios: (r.extension ?? [])
.filter((e) => e.url === EXT + 'escenario-clinico') .filter((e) => e.url === EXT + 'escenario-clinico')
+19 -1
View File
@@ -1,4 +1,4 @@
import { horizon, isRiskModel, riskGroups, riskScales } from './risk-scales'; import { horizon, isRiskModel, riskGroups, riskScales, survivalGroups } from './risk-scales';
const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high }); const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high });
@@ -84,3 +84,21 @@ describe('which models feed the risk scales', () => {
]); ]);
}); });
}); });
describe('survival scales', () => {
it('complements mortality and reverses interval bounds at every published horizon', () => {
const [g] = survivalGroups([{ index: '2026-01-01', predictions: [at(1, 0.2, 0.1, 0.3)] }]);
expect(g.survival).toBe(true);
expect(g.index).toBe('2026-01-01');
expect(g.scales[0].risk?.p).toBeCloseTo(0.8);
expect(g.scales[0].risk?.low).toBeCloseTo(0.7);
expect(g.scales[0].risk?.high).toBeCloseTo(0.9);
});
it('keeps the inputs attached to the estimate and leaves old estimates without them', () => {
const inputs = { age_group: '45-54', cytology: 'HSIL+', hpv: 'positive' };
expect(survivalGroups([{ index: '2026-01-01', predictions: [at(1, 0.2)], inputs }])[0].inputs)
.toEqual(inputs);
expect(riskGroups([{ text: 'Riesgo', index: '2026-01-01', predictions: [at(5, 0.2)] }])[0].inputs)
.toBeUndefined();
});
});
+134 -8
View File
@@ -48,9 +48,54 @@ export interface RiskGroup {
title?: string; title?: string;
scenario?: string; scenario?: string;
index?: string; index?: string;
survival?: boolean;
inputs?: Record<string, unknown>;
/** the model and version that scored her, and the day it did */
model?: string;
evaluated?: string;
scales: { label: string; risk?: Prediction }[]; scales: { label: string; risk?: Prediction }[];
} }
/** Stored survival-model probabilities are mortality: complement them to obtain S(t). */
export function survivalGroups(
models: {
index: string;
predictions: Prediction[];
scenarios?: string[];
inputs?: Record<string, unknown>;
text?: string;
evaluated?: string;
}[],
): RiskGroup[] {
return models
.map((m) => ({
title: 'Supervivencia',
index: m.index,
survival: true,
inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scenario: m.scenarios?.join(' · '),
scales: m.predictions.flatMap((p) => {
const v = horizon(m.predictions, p.years);
return v
? [
{
label: `Supervivencia a ${p.years} ${p.years === 1 ? 'año' : 'años'}`,
risk: {
years: p.years,
p: 1 - v.p,
low: v.high === undefined ? undefined : 1 - v.high,
high: v.low === undefined ? undefined : 1 - v.low,
},
},
]
: [];
}),
}))
.filter((g) => g.scales.length);
}
const HORIZONS: [number, string][] = [ const HORIZONS: [number, string][] = [
[0, 'Riesgo inmediato (al índice)'], [0, 'Riesgo inmediato (al índice)'],
[5, 'Riesgo a 5 años'], [5, 'Riesgo a 5 años'],
@@ -65,7 +110,13 @@ export function titleParts(text: string): { title: string; scenario?: string } {
/** 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
* unavailable. */ * unavailable. */
export function riskGroups( export function riskGroups(
models: { text: string; index: string; predictions: Prediction[] }[], models: {
text: string;
index: string;
predictions: Prediction[];
inputs?: Record<string, unknown>;
evaluated?: string;
}[],
): RiskGroup[] { ): RiskGroup[] {
const scales = (predictions: Prediction[]) => const scales = (predictions: Prediction[]) =>
HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) })); HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) }));
@@ -73,6 +124,9 @@ export function riskGroups(
? models.map((m) => ({ ? models.map((m) => ({
...titleParts(m.text), ...titleParts(m.text),
index: m.index, index: m.index,
inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scales: scales(m.predictions), scales: scales(m.predictions),
})) }))
: [{ scales: scales([]) }]; : [{ scales: scales([]) }];
@@ -85,9 +139,6 @@ export function riskGroups(
selector: 'app-risk-scales', selector: 'app-risk-scales',
imports: [DecimalPipe], imports: [DecimalPipe],
template: ` template: `
@if (groups().length) {
<p class="muted note">Divisiones numéricas descriptivas; no representan umbrales clínicos.</p>
}
@for (g of groups(); track $index) { @for (g of groups(); track $index) {
@if (g.title) { @if (g.title) {
<h3>{{ g.title }}</h3> <h3>{{ g.title }}</h3>
@@ -105,7 +156,7 @@ export function riskGroups(
· No disponible · No disponible
} }
</p> </p>
<div class="risk-plot" [class.unavailable]="!s.risk"> <div class="risk-plot" [class.unavailable]="!s.risk" [class.survival]="g.survival">
<div class="risk-line" aria-hidden="true"></div> <div class="risk-line" aria-hidden="true"></div>
@if (s.risk; as r) { @if (s.risk; as r) {
@if (r.low !== undefined && r.high !== undefined) { @if (r.low !== undefined && r.high !== undefined) {
@@ -134,12 +185,55 @@ export function riskGroups(
{{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }} {{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }}
</p> </p>
} }
@if (g.title && !g.survival) {
<section>
<h4>Factores de riesgo considerados</h4>
@if (g.inputs) {
<dl>
@for (item of entries(g.inputs); track item[0]) {
<div>
<dt>{{ inputName(item[0]) }}</dt>
<dd>{{ inputValue(item[0], item[1]) }}</dd>
</div>
}
</dl>
} @else {
<p class="muted">Los valores utilizados no están disponibles para esta estimación.</p>
}
</section>
}
@if (g.model) {
<details data-section="metodos">
<summary>Métodos</summary>
<dl>
<div>
<dt>Modelo y versión</dt>
<dd>{{ g.model }}</dd>
</div>
<div>
<dt>Fecha índice</dt>
<dd>{{ g.index }}</dd>
</div>
<div>
<dt>Fecha de evaluación</dt>
<dd>{{ g.evaluated ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Covariables</dt>
<dd>
@for (item of entries(g.inputs ?? {}); track item[0]) {
<div>{{ inputName(item[0]) }}: {{ inputValue(item[0], item[1]) }}</div>
} @empty {
No disponibles para esta estimación.
}
</dd>
</div>
</dl>
</details>
}
} }
`, `,
styles: ` styles: `
.note {
margin: 0 0 8px;
}
.risk-scale { .risk-scale {
margin: 8px 0 14px; margin: 8px 0 14px;
max-width: 740px; max-width: 740px;
@@ -170,6 +264,15 @@ export function riskGroups(
#fff 25% #fff 25%
); );
} }
.survival .risk-line {
background: linear-gradient(
to right,
#c24269 0 25%,
#df8640 25% 50%,
#a8c243 50% 75%,
#42a77e 75% 100%
);
}
.risk-interval { .risk-interval {
border-left: 2px solid #17324d; border-left: 2px solid #17324d;
border-right: 2px solid #17324d; border-right: 2px solid #17324d;
@@ -216,4 +319,27 @@ export function riskGroups(
}) })
export class RiskScales { export class RiskScales {
readonly groups = input.required<RiskGroup[]>(); readonly groups = input.required<RiskGroup[]>();
protected readonly entries = Object.entries;
protected readonly inputName = (name: string) =>
(
({
age_group: 'Edad al diagnóstico',
cytology: 'Citología',
hpv: 'VPH',
hpv_positive: 'VPH',
hpv_16_18: 'VPH 16/18',
referral_grade: 'Referencia',
bethesda: 'Citología',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
}) as Record<string, string>
)[name] ?? name;
protected readonly inputValue = (name: string, value: unknown) => {
if (value === null || value === undefined) return 'No documentado';
if (name.startsWith('hpv') && (value === 0 || value === 1 || typeof value === 'boolean'))
return value ? 'Positivo' : 'Negativo';
if (name.startsWith('hpv') && value === 'positive') return 'Positivo';
if (name.startsWith('hpv') && value === 'negative') return 'Negativo';
return String(value);
};
} }
+4 -1
View File
@@ -24,6 +24,9 @@ describe('risk series', () => {
], ],
}); });
expect(series.points).toEqual([{ years: 0, p: 0, low: undefined, high: undefined }]); expect(series.points).toEqual([{ years: 0, p: 0, low: undefined, high: undefined }]);
expect(seriesName(series)).toBe('Institucional · LIEAG+ (CIN2+)'); expect(seriesName(series)).toBe('ISSSTELEON, LIEAG+');
expect(seriesName({ ...series, source: 'NCI (tabla de ingreso)' })).toBe(
'NCI, ingreso a LIEAG+',
);
}); });
}); });
+21 -87
View File
@@ -1,12 +1,8 @@
import { DecimalPipe } from '@angular/common';
import { Component, computed, input, signal } from '@angular/core'; import { Component, computed, input, signal } from '@angular/core';
import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import type { Parameters, ParametersParameter } from 'fhir/r4'; import type { Parameters, ParametersParameter } from 'fhir/r4';
import { Plot } from '../plot'; import { Plot } from '../plot';
import { curveFigure } from './risk-curve'; import { curveFigure } from './risk-curve';
import { REASON_TEXT } from './reference-risk';
export interface SeriesPoint { export interface SeriesPoint {
years: number; years: number;
@@ -32,12 +28,16 @@ const OUTCOME_TEXT: Record<string, string> = {
'CIN3+': 'CIN3+', 'CIN3+': 'CIN3+',
cancer: 'Cáncer', cancer: 'Cáncer',
}; };
const REASONS: Record<string, string> = {
...REASON_TEXT,
history_is_registered: 'Tiene antecedentes registrados: no corresponde la tabla de ingreso.',
};
export const seriesName = (s: Series) => `${s.source} · ${OUTCOME_TEXT[s.outcome] ?? s.outcome}`; export const seriesName = (s: Series) => {
const outcome = OUTCOME_TEXT[s.outcome] ?? s.outcome;
if (s.source === 'NCI (tabla de ingreso)')
return `NCI, ingreso a ${outcome.replace(' (CIN2+)', '').replace(/^Cáncer$/, 'cáncer')}`;
// the platform's own models are the hospital's: its name, and the outcome without its synonym
return s.source === 'Institucional'
? `ISSSTELEON, ${outcome.replace(' (CIN2+)', '')}`
: `${s.source} · ${outcome}`;
};
/** The series of the answer. A value absent from it stays absent. */ /** The series of the answer. A value absent from it stays absent. */
export function parseSeries(answer: Parameters): Series[] { export function parseSeries(answer: Parameters): Series[] {
@@ -61,11 +61,10 @@ export function parseSeries(answer: Parameters): Series[] {
})); }));
} }
/** The chosen series as bars at one horizon and as curves. Series are shown side by side; no /** The chosen series as curves. Series are shown side by side; no difference is computed. */
* difference between them is computed. */
@Component({ @Component({
selector: 'app-risk-series', selector: 'app-risk-series',
imports: [DecimalPipe, MatCheckboxModule, MatFormFieldModule, MatSelectModule, Plot], imports: [MatCheckboxModule, Plot],
template: ` template: `
<p class="muted">Cada serie tiene su propio desenlace y población: no se restan entre sí.</p> <p class="muted">Cada serie tiene su propio desenlace y población: no se restan entre sí.</p>
<div class="choices"> <div class="choices">
@@ -76,44 +75,13 @@ export function parseSeries(answer: Parameters): Series[] {
} }
</div> </div>
@if (selected().length) { @if (selected().length) {
<mat-form-field appearance="outline" subscriptSizing="dynamic"> @for (assumption of assumptions(); track assumption) {
<mat-label>Horizonte</mat-label> <p class="muted">{{ assumption }}</p>
<mat-select [value]="horizon()" (selectionChange)="picked.set($event.value)"> }
@for (h of horizons(); track h) { <app-plot [figure]="figure()" [height]="340" [toolbar]="false" />
<mat-option [value]="h">{{ h === 0 ? 'Al índice' : h + ' años' }}</mat-option>
}
</mat-select>
</mat-form-field>
<ul class="bars">
@for (b of bars(); track b.series.id) {
<li>
<span>{{ name(b.series) }}</span>
<small class="muted">{{ b.series.label }}</small>
@if (b.point; as p) {
<span class="track"><span class="fill" [style.width.%]="p.p * 100"></span></span>
<span>
{{ p.p * 100 | number: '1.1-2' }} %
@if (p.low !== undefined && p.high !== undefined) {
(IC 95 %: {{ p.low * 100 | number: '1.1-2' }}–{{
p.high * 100 | number: '1.1-2'
}})
} @else {
(IC 95 % no publicado)
}
</span>
} @else {
<span class="muted">No disponible en este horizonte.</span>
}
@for (a of b.series.assumptions; track a) {
<small class="muted">{{ a }}</small>
}
</li>
}
</ul>
<app-plot [figure]="figure()" [height]="340" />
} }
@for (s of unavailable(); track s.id) { @if (!available().length) {
<p class="muted">{{ name(s) }}: no disponible. {{ why(s) }}</p> <p class="muted">No disponible: datos insuficientes.</p>
} }
`, `,
styles: ` styles: `
@@ -126,31 +94,12 @@ export function parseSeries(answer: Parameters): Series[] {
gap: 0 16px; gap: 0 16px;
margin-bottom: 8px; margin-bottom: 8px;
} }
.bars {
list-style: none;
padding: 0;
}
.bars li {
display: flex;
flex-direction: column;
margin-bottom: 10px;
}
.track {
background: var(--color-action-hover, #f1f6f6);
height: 10px;
}
.fill {
background: #4269a0;
display: block;
height: 100%;
}
`, `,
}) })
export class RiskSeries { export class RiskSeries {
readonly series = input.required<Series[]>(); readonly series = input.required<Series[]>();
protected readonly name = seriesName; protected readonly name = seriesName;
protected readonly available = computed(() => this.series().filter((s) => s.points.length)); protected readonly available = computed(() => this.series().filter((s) => s.points.length));
protected readonly unavailable = computed(() => this.series().filter((s) => !s.points.length));
/** what the user toggled away from the default (the institutional series) */ /** what the user toggled away from the default (the institutional series) */
private readonly toggled = signal(new Set<string>()); private readonly toggled = signal(new Set<string>());
protected readonly chosen = computed( protected readonly chosen = computed(
@@ -164,21 +113,10 @@ export class RiskSeries {
protected readonly selected = computed(() => protected readonly selected = computed(() =>
this.available().filter((s) => this.chosen().has(s.id)), this.available().filter((s) => this.chosen().has(s.id)),
); );
protected readonly horizons = computed(() => /** what the chosen series assume, each said once */
[...new Set(this.selected().flatMap((s) => s.points.map((p) => p.years)))].sort( protected readonly assumptions = computed(() => [
(a, b) => a - b, ...new Set(this.selected().flatMap((s) => s.assumptions)),
), ]);
);
protected readonly picked = signal(5);
protected readonly horizon = computed(() =>
this.horizons().includes(this.picked()) ? this.picked() : this.horizons().at(-1)!,
);
protected readonly bars = computed(() =>
this.selected().map((series) => ({
series,
point: series.points.find((p) => p.years === this.horizon()),
})),
);
protected readonly figure = computed(() => { protected readonly figure = computed(() => {
const shown = this.selected().map((s) => ({ const shown = this.selected().map((s) => ({
model: s.id, model: s.id,
@@ -198,8 +136,4 @@ export class RiskSeries {
if (!next.delete(id)) next.add(id); if (!next.delete(id)) next.add(id);
this.toggled.set(next); this.toggled.set(next);
} }
protected why(s: Series) {
return s.reasons.map((r) => REASONS[r] ?? r).join(' ');
}
} }
@@ -0,0 +1,25 @@
import { combinationOf, noCurveText } from './survival-combination';
describe('combinationOf', () => {
const values = { age_group: '<30', cytology: 'NA', hpv: 'positive' };
const report = { km_combinaciones: [{ valores: values, n: 9, fallecidos: 6 }] };
it('takes only the entry with all her values, a missing one as NA', () => {
expect(combinationOf(report, { age_group: '<30', cytology: null, hpv: 'positive' })?.n).toBe(9);
expect(combinationOf(report, { age_group: '<30', cytology: null, hpv: 'negative' })).toBe(
undefined,
);
expect(combinationOf(report, { age_group: '<30' })).toBe(undefined);
expect(combinationOf({}, values)).toBe(undefined);
});
it('tells an old report apart from a combination with too few deaths', () => {
expect(noCurveText({}, undefined)).toContain('no publica esta curva');
expect(
noCurveText(
{ ...report, min_fallecidos_escenario: 5 },
{ valores: values, n: 9, fallecidos: 2 },
),
).toContain('n = 9, fallecidos = 2; mínimo requerido: 5');
});
});
+61
View File
@@ -0,0 +1,61 @@
import { Figure, PALETTE } from '../plot';
/** One entry of the survival report's `km_combinaciones`: the patients who share every value. */
export interface Combination {
valores: Record<string, string>;
n: number;
fallecidos: number;
km?: { months: number[]; S: number[]; low: number[]; high: number[] };
}
/** The entry with exactly her values (a missing one is the report's "NA"); never a partial match. */
export function combinationOf(
report: Record<string, unknown> | null | undefined,
inputs: Record<string, unknown>,
): Combination | undefined {
const all = report?.['km_combinaciones'];
return (Array.isArray(all) ? (all as Combination[]) : []).find((c) => {
const keys = Object.keys(c.valores);
return (
keys.length === Object.keys(inputs).length &&
keys.every((k) => k in inputs && c.valores[k] === String(inputs[k] ?? 'NA'))
);
});
}
/** Why there is no curve for her: these are not the same thing, so each is said apart. (A patient
* outside the survival scenario has no survival section at all.) */
export function noCurveText(
report: Record<string, unknown> | null | undefined,
found: Combination | undefined,
): string {
if (!Array.isArray(report?.['km_combinaciones']))
return 'No disponible: la versión del modelo que la evaluó no publica esta curva.';
const minimum = report['min_fallecidos_escenario'];
const counts = `n = ${found?.n ?? 0}, fallecidos = ${found?.fallecidos ?? 0}`;
return `No disponible: datos insuficientes para su combinación de valores (${counts}${
typeof minimum === 'number' ? `; mínimo requerido: ${minimum} fallecidos` : ''
}).`;
}
export function combinationFigure(km: NonNullable<Combination['km']>): Figure {
const line = (y: number[], more: object) => ({
type: 'scatter',
mode: 'lines',
x: km.months,
y,
line: { shape: 'hv', color: PALETTE[0], width: 0 },
...more,
});
return {
data: [
line(km.low, { showlegend: false, hoverinfo: 'skip' }),
line(km.high, { name: 'IC 95 %', fill: 'tonexty', fillcolor: 'rgba(23, 50, 77, 0.15)' }),
line(km.S, { name: 'Kaplan-Meier', line: { shape: 'hv', color: PALETTE[0], width: 2 } }),
],
layout: {
xaxis: { title: { text: 'Meses desde el índice' } },
yaxis: { title: { text: 'Supervivencia S(t)' }, range: [0, 1.02], tickformat: '.0%' },
},
} as Figure;
}
+6 -1
View File
@@ -75,12 +75,17 @@ const CONFIG: Partial<Plotly.Config> = {
export class Plot implements OnDestroy { export class Plot implements OnDestroy {
readonly figure = input.required<Figure>(); readonly figure = input.required<Figure>();
readonly height = input(320); readonly height = input(320);
/** Plotly's buttons over the chart; a record's curves go without them */
readonly toolbar = input(true);
private readonly host = viewChild.required<ElementRef<HTMLDivElement>>('host'); private readonly host = viewChild.required<ElementRef<HTMLDivElement>>('host');
constructor() { constructor() {
effect(() => { effect(() => {
const { data, layout } = this.figure(); const { data, layout } = this.figure();
void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), CONFIG); void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), {
...CONFIG,
...(this.toolbar() ? {} : { displayModeBar: false }),
});
}); });
} }