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 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 = {
cytology: 'Distribución de resultados citológicos',
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
.locator('h2, app-readings h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
'Indicadores de oportunidad',
'Tiempos de tamizaje',
expect(headings.slice(headings.indexOf('Indicadores clínicos'))).toEqual([
'Indicadores clínicos',
'Resultados de citología, VPH y biopsia',
'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',
'Tasa de confirmación histopatológica',
'Tasa de confirmación histopatológica de referencia a colposcopía',
'Indicadores de oportunidad',
'Tiempos de tamizaje',
]);
const route = tab.locator('app-readings').first();
for (const mode of ['Por ventana de tiempo', 'Primer diagnóstico', 'Diagnóstico tras biopsia', 'Acumulado desde la toma']) {
const route = tab.locator('app-readings').filter({ has: page.getByRole('heading', { name: 'Tiempos de tamizaje' }) });
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 expect(
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(
tab.getByRole('heading', { name: 'Tasa de confirmación histopatológica de referencia a biopsia' }),
).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 }) => {
+22 -3
View File
@@ -251,9 +251,28 @@ for (const domain of ['cama', 'tea']) {
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
const from = headings.indexOf('Indicadores de oportunidad');
expect(headings.slice(from).map(period)).toEqual(
old.filter((i) => i.kind !== 'plot').map((i) => period(domain === 'cama' ? i.text.replace(/^Tiempo de /, 'Días de ') : i.text)),
);
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(
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
);
}
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab
.locator('.js-plotly-plot')
+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 { Reading } from './measures';
@@ -17,6 +17,59 @@ describe('bars', () => {
['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', () => {
const r: Reading = {
populations: {},
+58 -5
View File
@@ -16,6 +16,7 @@ export type Mode = {
kind: 'counts';
measure: string;
catalog: Category[];
aggregate?: { label: string; color: string; codes: string[] };
/** The records counted in the category distribution. */
unit?: string;
/** What the share in the second column is a share of. */
@@ -54,6 +55,7 @@ export type Mode = {
measure: string;
/** the categories drawn in each group, in this order (each in its own colour) */
catalog: Category[];
aggregate?: { label: string; color: string; codes: string[] };
/** the groups' stratifier (its crossed cells `<stratum>-category`) and their order */
stratum: 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));
return {
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 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),
};
@@ -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
* 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`). */
@@ -464,13 +497,18 @@ export function grouped(
const den = total(code);
return {
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,
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 percent = den ? (100 * count) / den : undefined;
return {
const row = {
label: c.label,
color: c.color,
count,
@@ -478,6 +516,21 @@ export function grouped(
percent,
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_LEVEL_COLORS,
QUARTILE,
REQUEST_COLORS,
ROUND_COLORS,
} from './cacu-palette';
import type { Catalog, Page, ReadingsCard } from './pages';
const OLIVE = '#A8C243';
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. */
const CYTOLOGY: Catalog = {
@@ -29,6 +29,12 @@ const CYTOLOGY: Catalog = {
{ code: 'ASC-H', label: 'ASC-H', color: CYTOLOGY_COLORS['ASC-H'], group: 'abnormal' },
{ code: 'HSIL', label: 'LIEAG', color: CYTOLOGY_COLORS['HSIL'], group: 'abnormal' },
{ code: 'CIS', label: 'Carcinoma in situ', color: CYTOLOGY_COLORS['CIS'], group: 'abnormal' },
{
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_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. */
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). */
const GENERAL = 'General';
const BY_AGE = 'Por grupo de edad';
const BY_STATUS = 'Por estatus de seguimiento';
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 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). */
const HPV_HIDDEN = {
codes: ['positive_incomplete', 'inconsistent', 'no_result'],
@@ -96,18 +93,17 @@ const groupViews = (
measure: string,
catalog: { code: string; label: string; color: string }[],
unit: string,
more: { ofAll?: boolean; hidden?: { codes: string[]; unit: string } } = {},
more: { ofAll?: boolean; hidden?: { codes: string[]; unit: string }; aggregate?: typeof ABNORMAL } = {},
): Mode[] =>
[
{ 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 },
].map((v) => ({
kind: 'grouped' as const,
measure,
catalog,
unit,
caption: more.ofAll
caption: measure === 'CACU_VPH_GENOTIPO'
? 'Porcentaje de reportes de VPH del grupo por genotipo.'
: 'Porcentaje de pacientes del grupo por resultado citológico.',
...v,
@@ -245,7 +241,7 @@ export const CACU: Page = {
{
kind: 'days',
tint: TINT,
label: 'Primer diagnóstico',
label: 'Diagnóstico precolposcópico',
steps: [{ label: 'Toma a primer diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' }],
},
{
@@ -267,7 +263,7 @@ export const CACU: Page = {
kind: 'columns',
title: 'Resultados de citología, VPH y biopsia',
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: [
{
kind: 'readings',
@@ -280,10 +276,11 @@ export const CACU: Page = {
label: GENERAL,
measure: 'CACU_EU7',
catalog: CYTOLOGY.categories,
aggregate: ABNORMAL,
unit: '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',
'Pacientes con biopsia reportada, por fecha de solicitud.',
'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: {
anchor: 'CAMA_BIRADS456_PACIENTE',
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',
title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
@@ -262,16 +272,6 @@ export const PAGES: Record<string, Page> = {
value: '{pct} %',
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: [
{
@@ -338,9 +338,9 @@ export const PAGES: Record<string, Page> = {
kind: 'counts',
label: 'Todas las categorías',
heading: 'Resultados por paciente',
caption: `Todas las categorías BI-RADS juntas. ${NO_BIOPSY_MEANS}`,
measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
catalog: [...BIOPSY_GRADES, ...NO_RESULT],
unit: 'Pacientes',
percent: true,
percentLabel: 'Porcentaje de pacientes',
},
@@ -366,6 +366,7 @@ export const PAGES: Record<string, Page> = {
heading: 'Biopsias reportadas',
measure: 'CAMA_BIOPSIAS',
catalog: [...BIOPSY_GRADES, NO_RESULT[1]],
unit: 'Biopsias',
percent: true,
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 { Loading } from '../loading';
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';
/** 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) {
<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) {
<app-plot [figure]="f" [height]="height()" />
@if (hidden(); as why) {
@@ -373,6 +388,11 @@ export class Readings {
() => this.modes().find((m) => m.label === (this.view() || this.chosen())) ?? this.modes()[0],
);
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()));
/** The bars of a scenarios figure need more room than a donut. */
protected readonly height = computed(() => {
+92 -41
View File
@@ -40,53 +40,104 @@
}
@if (page(); as pg) {
@if (applied(); as period) {
<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]="pg.kpis.length < 3 ? pg.kpis.length : 3"
[style.--kpi-cols-lg]="pg.kpis.length < 5 ? pg.kpis.length : 5"
>
@for (k of pg.kpis; track k.title) {
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null">
<mat-card-content>
<h3 class="kpi-title">{{ k.title }}</h3>
@if (reports.isLoading() && k.measure) {
<app-loading [what]="k.title.toLowerCase()" />
} @else {
<div class="kpi-value" [class.pending]="!k.measure">
@let v = kpiParts(kpiValue(k));
{{ v[0] }}
@if (v[1]) {
<span class="kpi-qualifier">{{ v[1] }}</span>
}
</div>
<div class="kpi-detail">{{ kpiNote(k) }}</div>
}
</mat-card-content>
</mat-card>
@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 }"
/>
}
</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>
<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]="pg.kpis.length < 3 ? pg.kpis.length : 3"
[style.--kpi-cols-lg]="pg.kpis.length < 5 ? pg.kpis.length : 5"
>
@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>
<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 (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>
}
}
<ng-template #kpiView let-k>
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null">
<mat-card-content>
<h3 class="kpi-title">{{ k.title }}</h3>
@if (reports.isLoading() && k.measure) {
<app-loading [what]="k.title.toLowerCase()" />
} @else {
<div class="kpi-value" [class.pending]="!k.measure">
@let v = kpiParts(kpiValue(k));
{{ v[0] }}
@if (v[1]) {
<span class="kpi-qualifier">{{ v[1] }}</span>
}
</div>
<div class="kpi-detail">{{ kpiNote(k) }}</div>
}
</mat-card-content>
</mat-card>
</ng-template>
<ng-template #sectionView let-section let-period="period">
@switch (section.kind) {
@case ('readings')
+14 -2
View File
@@ -31,6 +31,10 @@ interface Drawn {
<mat-button-toggle value="month">Mensual</mat-button-toggle>
<mat-button-toggle value="semester">Semestral</mat-button-toggle>
</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>
@if (series.isLoading()) {
<app-loading what="el histórico" text="Cargando histórico…" />
@@ -95,13 +99,16 @@ export class TabTrazabilidad {
readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>();
protected readonly type = signal<PeriodType>('month');
protected readonly chosenCutoff = signal('');
protected readonly cutoff = signal('');
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 }) => {
const history = HISTORY[params.domain];
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(
history.panels.map(async (panel) => {
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', {
measure: measure.id!,
'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.
const found = resources<MeasureReport>(pages, 'MeasureReport');
+7 -2
View File
@@ -151,7 +151,7 @@
<td>
{{ h.text }}
@if (h.code && h.code !== h.text) {
<span class="muted">({{ h.code }})</span>
<span class="muted">(CIE-10: {{ h.code }})</span>
}
</td>
</tr>
@@ -258,9 +258,14 @@
</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-content>
@if (withheld(); as why) {
<p role="status" data-state="withheld">{{ why }}</p>
}
@if (riskExclusion(); as reason) {
<p role="status">{{ reason }}</p>
} @else {
+6 -1
View File
@@ -197,6 +197,11 @@ export class Paciente {
? `No disponible por: histerectomía registrada el ${recorded}.`
: 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. */
protected readonly stages = computed(() => {
const cytologies = (this.data.value()?.reports ?? []).filter(
@@ -312,7 +317,7 @@ export class Paciente {
['Estatus de seguimiento', this.status()],
['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(
facts,
this.stages() ?? [],
+1 -1
View File
@@ -51,7 +51,7 @@ describe('the PDF of a record', () => {
'Historial médico',
'Antecedentes y evaluación ginecológica',
'Pruebas y resultados',
'Riesgos',
'Probabilidades',
]);
});
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',
head: ['Riesgo', 'Probabilidad', 'IC 95 %'],
title: 'Probabilidades',
head: ['Estimación', 'Probabilidad', 'IC 95 %'],
rows: scales.map(({ label, risk }) => [
label,
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. */
export const STATUS_TEXT: Record<string, string> = {
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',
history_not_demonstrable: 'Antecedente no demostrable',
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.',
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.',
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.',
several_rows: 'Más de una fila podría corresponder.',
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.',
population_not_verified:
'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> = {
@@ -304,9 +304,9 @@ const OFFICIAL: Record<string, string> = {
<section
class="reference"
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">
<div>
<dt>Estado</dt>
@@ -458,7 +458,7 @@ const OFFICIAL: Record<string, string> = {
</section>
}
<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).
</p>
}
+2 -2
View File
@@ -18,7 +18,7 @@ describe('the institutional curves', () => {
model('Riesgo cáncer v2', [{ years: 5, p: 0.015 }]),
]);
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].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
@@ -94,7 +94,7 @@ describe('the institutional curves', () => {
model('Vacío v1', []),
]),
).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) =>
(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;
/** 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.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);
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]);
@@ -48,15 +48,15 @@ describe('the risk scales', () => {
expect(rest).toEqual([]);
expect(none.title).toBeUndefined();
expect(none.scales.map((s) => [s.label, s.risk])).toEqual([
['Riesgo inmediato (al índice)', undefined],
['Riesgo a 5 años', undefined],
['Probabilidad inmediata (al índice)', undefined],
['Probabilidad a 5 años', undefined],
]);
});
it('the PDF keeps its flat list, with no scale for a page with no model', () => {
expect(riskScales([])).toEqual([]);
expect(riskScales([{ text: 'M', predictions: [at(5, 0.1)] }]).map((s) => s.label)).toEqual([
'M, riesgo inmediato',
'M, riesgo a 5 años',
'M, probabilidad inmediata',
'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[] {
return models.flatMap((m) =>
[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),
})),
);
@@ -97,14 +97,17 @@ export function survivalGroups(
}
const HORIZONS: [number, string][] = [
[0, 'Riesgo inmediato (al índice)'],
[5, 'Riesgo a 5 años'],
[0, 'Probabilidad inmediata (al índice)'],
[5, 'Probabilidad a 5 años'],
];
/** 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 } {
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